-
Notifications
You must be signed in to change notification settings - Fork 0
/
CommandReader.cpp
99 lines (78 loc) · 1.74 KB
/
CommandReader.cpp
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
#include "CommandReader.h"
#include <Arduino.h>
#include <errno.h>
CommandReader::CommandReader(IPositionConsumer *consumer) : _consumer(consumer), _size(0) {}
void CommandReader::run() {
if (read()) {
if (hasCommand()) {
Serial.println("");
Command *command = consumeCommand();
if (command) {
Serial.println("ok");
if ((command->type == Command::POSITION)) {
PositionCommand *positionCommand = static_cast<PositionCommand *>(command);
_consumer->consumeCommand(positionCommand);
}
} else {
Serial.print("invalid command");
if (errno) {
Serial.print(" errno=");
Serial.println(errno);
errno = 0;
}
Serial.print("\n");
}
}
}
}
bool CommandReader::read() {
if (Serial.available() > 0) {
if (isFull()) {
clear();
}
_buffer[_size] = Serial.read();
Serial.print(_buffer[_size]);
_size++;
return true;
}
return false;
}
Command * CommandReader::consumeCommand() {
int commandSize = getCommandSize();
if (commandSize == 0) { // No command to consume
return 0;
}
Command *command = getCommand();
// Remove command from buffer
for (int i = 0; i < _size - commandSize; i++) {
_buffer[i] = _buffer[commandSize + i];
}
_size -= commandSize;
return command;
}
Command * CommandReader::getCommand() {
Command *command;
switch (_buffer[0]) {
case CMD_CODE_POSITION:
command = PositionCommand::fromString(_buffer);
break;
}
return command;
}
bool CommandReader::isFull() {
return _size >= CMD_BUF_MAX_SIZE;
}
void CommandReader::clear() {
_size = 0;
}
int CommandReader::getCommandSize() {
for (int i = 0; i < _size; i++) {
if (_buffer[i] == CMD_BREAK) {
return i + 1;
}
}
return 0;
}
bool CommandReader::hasCommand() {
return getCommandSize() > 0;
}