forked from trcbots/linda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial_command.h
139 lines (118 loc) · 2.56 KB
/
serial_command.h
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
132
133
134
135
136
137
138
#define MAX_CHARS 24
#define MESSAGE_START 0x23
#define MESSAGE_END 0x21
#define NO_MESSAGE -1
// Message Format:
// char MESSAGE_START '#'
// char message type
// char 0x2c ','
// char[9] data1
// char 0x2c ','
// char[9] data2
// char MESSAGE_END '!'
class SerialCommand
{
public:
int message_type;
double message_data1;
double message_data2;
SerialCommand();
void ReadData();
void reset();
private:
String cmd_string;
int curr_pos;
bool reading_message;
bool haveValidMessage();
};
SerialCommand::SerialCommand()
{
Serial.begin(115200);
reset();
}
void SerialCommand::ReadData()
{
if (Serial.available() <= 0)
{
return;
}
int read_byte = Serial.read();
if (! reading_message) {
if (read_byte == MESSAGE_START) {
reading_message = true;
}
return;
}
if (read_byte != MESSAGE_END)
{
cmd_string += (char)read_byte;
curr_pos++;
if ( curr_pos >= MAX_CHARS ) {
reset();
}
return;
}
// Once we receive our MESSAGE_END, then
// validate we have a valid message packet
if ( ! haveValidMessage() ) {
reset();
return;
}
message_type = cmd_string.substring(0).toInt();
bool found = false;
char p = 2;
for (; p < MAX_CHARS; p++)
{
if ( ! ( isDigit( cmd_string.charAt(p) ) || cmd_string.charAt(p) == '.' ) ) {
// If the char is a comma, then parse the data we have
if ( cmd_string.charAt(p) == 0x2c ) {
message_data1 = cmd_string.substring(2, p).toFloat();
found = true;
break;
}
// otherwise we bail out
break;
}
}
if ( ! found ) {
reset();
return;
}
found = false;
for (int q = p + 1; q < MAX_CHARS; q++)
{
if ( ! ( isDigit( cmd_string.charAt(q) ) || cmd_string.charAt(q) == '.' ) ) {
// If the char is a comma, then parse the data we have
// if ( cmd_string.charAt(q) == NULL )
if ( ! cmd_string.charAt(q) ) {
message_data2 = cmd_string.substring(p + 1, q).toFloat();
found = true;
break;
}
// otherwise we bail out
break;
}
}
if ( ! found ) {
reset();
return;
}
}
void SerialCommand::reset() {
cmd_string = "";
reading_message = false;
curr_pos = 0;
message_type = -1;
message_data1 = -1;
message_data2 = -1;
}
bool SerialCommand::haveValidMessage() {
int comma_count = 0;
for ( int p = 1; p < cmd_string.length(); p++ ) {
if ( cmd_string.charAt(p) == ',' ) {
comma_count += 1;
}
}
// Did we find the expected 2 commas
return ( comma_count == 2 );
}