- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArduinoReader.cpp
More file actions
Latest commit
281 lines (264 loc) · 10.1 KB
/
Copy pathArduinoReader.cpp
File metadata and controls
281 lines (264 loc) · 10.1 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#include"ArduinoReader.h"
#include<thread>
#include<String>
#include<iostream>
#defineDEBUGSTREAM \
if (debugDisabled) {} \
else std::cout
#defineRFERROR \
else { \
onFatalError("ReadFile", GetLastError()); \
returnfalse; \
}
voidArduinoReader::onFatalError(std::string function, unsignedlong error) {
if (error == 995) { //This is expected, as we call CancelSynchronousIo
std::cout << "Closing, aborted active I/O\n";
} else {
std::cout << function << " failed with error: ";
char buffer[255];
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ARGUMENT_ARRAY, NULL, error, 0, (LPSTR)&buffer, 255, NULL);
std::cout << buffer;
}
onFatalError();
}
voidArduinoReader::onFatalError() {
if (!shouldStop) { //if the program is already stopping, window will likely be invalid (fatal error on stop is pretty likely since CancelSynchronousIo triggers one)
std::cout << "Closing due to fatal error" << std::endl;
wxCloseEvent* event = newwxCloseEvent(wxEVT_CLOSE_WINDOW, WINDOW_ID);
event->SetEventObject(window);
window->GetEventHandler()->QueueEvent(event);
}
}
unsignedintArduinoReader::parseInt(unsignedchar* buffer) {
return ((unsignedint)buffer[0] << 24) | ((unsignedint)buffer[1] << 16) | ((unsignedint)buffer[2] << 8) | buffer[3];
}
ArduinoReader::ArduinoReader(mainWindow* window, threadSafeScreen* tss, bool resetFlag, bool debug, std::string comPort, long baud) : window{ window }, tss{ tss }, resetFlag{ resetFlag }, debugDisabled{ !debug }, comPort{ comPort }, baud{ baud } {
readerThread = std::thread(&ArduinoReader::startReal, this);
}
ArduinoReader::~ArduinoReader() {
//join owned thread
shouldStop = true; //setting a variable across threads would usually be risky, but that's the point of std::atomic
CancelSynchronousIo(readerThread.native_handle()); //without this, the code could get stuck indefinitely waiting for serial data
readerThread.join();
//close handle
CloseHandle(serialHandle);
}
boolArduinoReader::waitForArduinoStart() {
constexprchar startMessage[] = "VS START";
char buffer = '\0';
int index = 0;
unsignedlong bytesRead = 0;
if (!WriteFile(serialHandle, startMessage, 8, &bytesRead, NULL)) { //send VS START to arduino; arduino could use this to know when to send the image when not using --reset
onFatalError("WriteFile", GetLastError());
returnfalse;
}
while (!shouldStop) {
if (ReadFile(serialHandle, &buffer, 1, &bytesRead, NULL)) {
if (buffer == startMessage[index]) {
index++;
if (index == 8) {
std::cout << "VS START Received\n";
returntrue;
}
} else {
index = 0;
}
} RFERROR
}
returnfalse;
}
boolArduinoReader::readHeader() {
unsignedchar buffer[8];
unsignedlong bytesRead = 0;
if (ReadFile(serialHandle, &buffer, 8, &bytesRead, NULL)) {
xRes = parseInt(buffer);
yRes = parseInt(buffer + 4);
std::cout << "X resolution: " << xRes << "\nY resolution: " << yRes << std::endl;
tss->setImage(wxImage{ xRes,yRes,true });
window->updateNextFrame = true;
} RFERROR
returntrue;
}
boolArduinoReader::mainLoop() {
//get packet type
char buffer = 0;
unsignedlong bytesRead = 0;
if (ReadFile(serialHandle, &buffer, 1, &bytesRead, NULL)) {
switch (buffer) {
case0: {//update buffer
unsignedchar* data = (unsignedchar*)malloc((size_t)xRes * yRes * 3);//malloc, not new, because according to https://docs.wxwidgets.org/trunk/classwx_image.html#a2c97634b43bdd143f34418fb1f98a690
if (ReadFile(serialHandle, data, (unsignedlong)xRes * yRes * 3, &bytesRead, NULL)) {
tss->setImage(wxImage{ xRes,yRes,data,false });
window->updateNextFrame = true;
DEBUGSTREAM << "Received updated buffer\n";
} else {
free(data);
onFatalError("ReadFile", GetLastError());
returnfalse;
}
break;//wxImage takes ownership of the data, and frees it, but the data has to be allocated with malloc
}
case1: {//set pixel
unsignedchar data[11];
if (ReadFile(serialHandle, data, 11, &bytesRead, NULL)) {
int x = parseInt(data);
int y = parseInt(data + 4);
tss->setPixel(x, y, data[8], data[9], data[10]);
window->updateNextFrame = true;
DEBUGSTREAM << "Set pixel " << x << "," << y << " to [" << (int)data[8] << "," << (int)data[9] << "," << (int)data[10] << "]\n";
} RFERROR
break;
}
case2: {//draw line
unsignedchar data[19];
if (ReadFile(serialHandle, data, 19, &bytesRead, NULL)) {
int x1 = parseInt(data);
int y1 = parseInt(data + 4);
int x2 = parseInt(data + 8);
int y2 = parseInt(data + 12);
tss->drawLine(x1, y1, x2, y2, data[16], data[17], data[18]);
window->updateNextFrame = true;
DEBUGSTREAM << "Drew line from " << x1 << "," << y1 << " to " << x2 << "," << y2 << " with color [" << (int)data[16] << "," << (int)data[17] << "," << (int)data[18] << "]\n";
} RFERROR
break;
}
case3: {//draw triangle
unsignedchar data[27];
if (ReadFile(serialHandle, data, 27, &bytesRead, NULL)) {
int x1 = parseInt(data);
int y1 = parseInt(data + 4);
int x2 = parseInt(data + 8);
int y2 = parseInt(data + 12);
int x3 = parseInt(data + 16);
int y3 = parseInt(data + 20);
tss->drawTriangle(x1, y1, x2, y2, x3, y3, data[24], data[25], data[26]);
window->updateNextFrame = true;
DEBUGSTREAM << "Drew triangle with vertices [" << x1 << "," << y1 << "], [" << x2 << "," << y2 << "], [" << x3 << "," << y3 << "] and color [" << (int)data[24] << "," << (int)data[25] << "," << (int)data[26] << "]\n";
} RFERROR
break;
}
case4: {//draw rectangle
unsignedchar data[19];
if (ReadFile(serialHandle, data, 19, &bytesRead, NULL)) {
int x = parseInt(data);
int y = parseInt(data + 4);
int width = parseInt(data + 8);
int height = parseInt(data + 12);
tss->drawRectangle(x, y, width, height, data[16], data[17], data[18]);
window->updateNextFrame = true;
DEBUGSTREAM << "Drew rectangle with TL corner [" << x << "," << y << "], width " << width << ", height " << height << ", and color [" << (int)data[16] << "," << (int)data[17] << (int)data[18] << "]\n";
} RFERROR
break;
}
case5: {//draw polygon
char buffer = 0;
if (ReadFile(serialHandle, &buffer, 1, &bytesRead, NULL)) {
int vertices = (int)buffer;
if (vertices > 2) {
unsignedchar* data = newunsignedchar[8 * vertices + 3];
if (ReadFile(serialHandle, data, 8 * vertices + 3, &bytesRead, NULL)) {
std::vector<wxPoint> verticesArray{};
unsignedchar* ptr = data;
for (int i = 0; i < vertices; i++) {
verticesArray.push_back(wxPoint(parseInt(ptr), parseInt(ptr + 4)));
ptr += 8;
}
tss->drawPolygon(verticesArray, ptr[0], ptr[1], ptr[2]);
window->updateNextFrame = true;
DEBUGSTREAM << "Drew polygon with vertices ";
for (wxPoint p : verticesArray) {
DEBUGSTREAM << "[" << p.x << "," << p.y << "], ";
}
DEBUGSTREAM << "and color [" << (int)ptr[0] << "," << (int)ptr[1] << "," << (int)ptr[2] << "]\n";
} RFERROR
delete data;
} else {
std::cout << "Vertices was less than 3: " << vertices << std::endl;
onFatalError();
returnfalse;
}
} RFERROR
break;
}
case6: { //draw ellipse
unsignedchar data[19];
if (ReadFile(serialHandle, data, 19, &bytesRead, NULL)) {
int x = parseInt(data);
int y = parseInt(data + 4);
int width = parseInt(data + 8);
int height = parseInt(data + 12);
tss->drawEllipse(x, y, width, height, data[16], data[17], data[18]);
window->updateNextFrame = true;
DEBUGSTREAM << "Drew ellipse with center [" << x << "," << y << "], width " << width << ", height " << height << ", and color [" << (int)data[16] << "," << (int)data[17] << "," << (int)data[18] << "]\n";
} RFERROR
break;
}
case7: { //draw text
unsignedchar buffer[9];
if (ReadFile(serialHandle, buffer, 9, &bytesRead, NULL)) {
int x = parseInt(buffer);
int y = parseInt(buffer + 4);
int chars = (int)buffer[8];
unsignedchar* data = newunsignedchar[chars + 3];
if (ReadFile(serialHandle, data, chars + 3, &bytesRead, NULL)) {
std::string text((char*) data, chars);
tss->drawText(x, y, text, data[chars], data[chars + 1], data[chars + 2]);
window->updateNextFrame = true;
DEBUGSTREAM << "Drew text with corner [" << x << "," << y << "], text \"" << text << "\", and color [" << (int)data[chars] << "," << (int)data[chars + 1] << "," << (int)data[chars + 2] << "]\n";
} RFERROR
delete data;
} RFERROR
break;
}
default: {//invalid
std::cout << "Invalid packet type received: " << (int)buffer << std::endl;
onFatalError();
returnfalse;
}
}
} RFERROR
returntrue;
}
voidArduinoReader::startReal() {
if (initializeSerial()) {
if (waitForArduinoStart()) {
if (readHeader()) {
while (!shouldStop && mainLoop()) {}
}
}
}
}
boolArduinoReader::initializeSerial() {
std::cout << "Opening port " << comPort << " with baud rate " << baud << std::endl;
comPort = "\\\\.\\" + comPort;
serialHandle = CreateFileA(comPort.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (serialHandle == INVALID_HANDLE_VALUE) {
onFatalError("CreateFileA", GetLastError());
returnfalse;
}
dcb.DCBlength = sizeof(dcb);
if (!GetCommState(serialHandle, &dcb)) {
onFatalError("GetCommState", GetLastError());
returnfalse;
}
dcb.BaudRate = baud;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.fDtrControl = false;
dcb.fRtsControl = resetFlag; //RTS resets arduino, but leaving it on would keep it in a reset loop
if (!SetCommState(serialHandle, &dcb)) {
onFatalError("SetCommState", GetLastError());
returnfalse;
}
if (resetFlag) {
std::this_thread::sleep_for(std::chrono::milliseconds(1)); //sleep for 1 millisecond, to give RTS time to register
dcb.fRtsControl = false;
std::cout << "Reset Arduino\n";
if (!SetCommState(serialHandle, &dcb)) { //turn off rts, so the arduino is able to start
onFatalError("SetCommState", GetLastError()); //EscapeCommFunction failing isn't really fatal, since manual reset is always possible, but it implies a larger issue with the connection
returnfalse;
}
}
returntrue;
}