-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcomms.cpp
More file actions
162 lines (147 loc) · 2.6 KB
/
comms.cpp
File metadata and controls
162 lines (147 loc) · 2.6 KB
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#include "comms.h"
#include "arduino.h"
void Comms::update()
{
while (true)
{
int b = Serial.read();
if (b == -1)
{
return;
}
if (b == '\n')
{
_processPacket();
}
else
{
_appendByte((uint8_t)b);
}
}
}
void Comms::_processPacket()
{
const uint8_t ctl = _nextByte();
switch (ctl)
{
case 'I':
Comms::_doInit();
break;
case 'R':
Comms::_doRGB();
break;
case 'H':
Comms::_doHSV();
break;
case 'S':
Comms::_doShow();
break;
case 'C':
Comms::_doClear();
break;
}
_index = _last; // Make sure we have cleared out the current packet.
}
void Comms::_doInit()
{
// Check for correct number of bytes.
if (_delta() < 2)
{
return;
}
int n = _nextU8();
// Short init command, no config.
if (_delta() < 2)
{
_d->setup(n);
return;
}
// Init with config (ie, used for setting different pixel types, like RGB, GRBW etc).
int c = _nextU8();
_d->setup(n, c);
}
void Comms::_doRGB()
{
const int delta = _delta();
// Check for correct number of bytes.
if (delta < 8 || (delta % 6 != 2))
{
return;
}
int n = _nextU8();
while (_index != _last)
{
uint8_t r = _nextU8();
uint8_t g = _nextU8();
uint8_t b = _nextU8();
_d->setRGB(n, r, g, b);
n++;
}
}
void Comms::_doHSV()
{
const int delta = _delta();
// Check for correct number of bytes.
if (delta < 8 || (delta % 6 != 2))
{
return;
}
int n = _nextU8();
while (_index != _last)
{
uint8_t h = _nextU8();
uint8_t s = _nextU8();
uint8_t v = _nextU8();
_d->setHSV(n, h, s, v);
n++;
}
}
void Comms::_doShow()
{
_d->show();
}
void Comms::_doClear()
{
_d->clear();
}
void Comms::_appendByte(uint8_t b)
{
_b[_last] = b;
_last++;
if (_last == SERIAL_BUFFER_SIZE)
{
_last = 0;
}
}
uint8_t Comms::_nextU8()
{
const char str[2]{
_nextByte(),
_nextByte(),
};
char *end;
return (uint8_t)strtol(str, &end, 16);
}
uint8_t Comms::_nextByte()
{
if (_index == _last)
{
return 0; // Not good...
}
uint8_t b = _b[_index];
_index++;
if (_index == SERIAL_BUFFER_SIZE)
{
_index = 0;
}
return b;
}
int Comms::_delta()
{
int last = _last;
if (last < _index)
{
last += SERIAL_BUFFER_SIZE;
}
return last - _index;
}