Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include "cli.h"
void Cli::resetNextWord ()
{
_currentWordIndex = -1;
_previousWordLength = 0;
}
const char* Cli::findNextWord ()
{
if (_currentWordIndex >= 0)
// skip current word
while (_currentWordIndex < (int)_currentInput.length())
{
if (_currentInput[_currentWordIndex] == 32)
break;
_currentWordIndex++;
}
else
_currentWordIndex = 0;
size_t _previousWordLength = 0;
// skip spaces
while (_currentWordIndex < (int)_currentInput.length())
{
if (_currentInput[_currentWordIndex] != 32)
break;
_currentWordIndex++;
_previousWordLength++;
}
const char* ret = _currentWordIndex < (int)_currentInput.length()? _currentInput.c_str() + _currentWordIndex: nullptr;
//if (ret)
// Serial.printf("# found new start of word '%s'\n", ret);
return ret;
}
void Cli::copyNextToTemp ()
{
findNextWord();
int start = _currentWordIndex;
findNextWord();
if (start < _currentWordIndex)
_temp = _currentInput.substring(start, _currentWordIndex);
else
_temp.clear();
}
bool Cli::kw (const __FlashStringHelper* keyWord, const char* input)
{
// return true if input matches keyWord
auto len = strlen_P((PGM_P)keyWord);
return len && strncasecmp_P((PGM_P)keyWord, input, len) == 0;
}
bool Cli::kw (const __FlashStringHelper* keyWord)
{
return kw(keyWord, _currentInput.c_str() + _currentWordIndex);
}
void Cli::syntax ()
{
syntax(_currentInput.c_str() + _currentWordIndex);
}
void Cli::syntaxFull ()
{
syntax((const char*)nullptr);
}
void Cli::syntax (const __FlashStringHelper* cmd)
{
syntax((PGM_P)cmd);
}
void Cli::syntax (const char* cmd)
{
if (!cmd || kw(F("AT"), cmd)) Serial.printf("# CLI: AT -> OK\n");
if (!cmd || kw(F("HELP"), cmd)) Serial.printf("# CLI: HELP [CMD]\n");
if (!cmd || kw(F("RAT"), cmd)) Serial.printf("# CLI: RAT [ C | I ] [ <rate> [ <unit>(UM/MM/UH/MH) ] ]\n");
if (!cmd || kw(F("VOL"), cmd)) Serial.printf("# CLI: VOL [ <vol> | <unit>(UL/ML) ]\n");
}
void Cli::loop (Stream& input)
{
while (true)
{
if (!input.available())
return;
int c = input.read();
if (c == 13)
break;
if (c >= 32 && c <= 127)
_currentInput += (char)c;
}
resetNextWord();
if (findNextWord())
{
if (kw(F("AT")))
{
Serial.printf("OK\n");
}
else if (kw(F("HELP")))
{
copyNextToTemp();
if (_temp.length())
syntax(_temp.c_str());
else
syntaxFull();
}
else if (kw(F("RAT")))
{
copyNextToTemp();
}
else if (kw(F("VOL")))
{
}
else
{
Serial.printf("# CLI: invalid command '%s'\n", _currentInput.c_str() + _currentWordIndex);
}
}
if (findNextWord())
Serial.printf("# CLI: garbage at end of line: '%s'\n", _currentInput.c_str() + _currentWordIndex);
resetNextWord();
_currentInput.clear();
}