Mutila: Mouse's Utilities for Arduino
Oft-used utilities: debouncing buttons, averaging samples, and so on.
CommandInterface.cpp
1 #include <MutilaDebug.h>
2 #include "CommandInterface.h"
3 
5  echo(true),
6  _stream(NULL),
7  _maxLen(maxCmdLen),
8  _idx(0),
9  _buf(NULL)
10 {
11  _buf = new char[_maxLen];
12 }
13 
15 {
16  if (_buf) {
17  delete _buf;
18  _buf = NULL;
19  }
20 }
21 
22 void CommandInterface::begin(Stream& stream)
23 {
24  clearBuf();
25  _stream = &stream;
26  DBLN(F("CommandInterface::begin"));
27 }
28 
30 {
31  if (_buf == NULL) return;
32  memset(_buf, 0, sizeof(char) * _maxLen);
33  _idx = 0;
34 }
35 
37 {
38  if (_stream == NULL || _buf == NULL) return;
39  while (_stream->available()) {
40  int c = _stream->read();
41  if (c < 0) {
42  return;
43  } else if (c == '\n' || c == '\r') {
44  if (echo) {
45  _stream->write('\n');
46  }
47  runCmd();
48  clearBuf();
49  } else if (_idx > 0 && (c == '\b' || c == 0x7F)) {
50  // backspace
51  _stream->write("\b \b");
52  _buf[--_idx] = '\0';
53  } else if (c >= ' ' && c <= '~' && _idx < _maxLen) {
54  _buf[_idx++] = (char)c;
55  if (echo) {
56  _stream->write((char)c);
57  }
58  }
59  }
60 }
61 
62 
virtual void begin(Stream &stream=Serial)
CommandInterface(uint8_t maxCmdLen=48)
virtual void runCmd()=0