-
Notifications
You must be signed in to change notification settings - Fork 58
/
SocketIOClient.cpp
519 lines (456 loc) · 13.8 KB
/
SocketIOClient.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
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/*
socket.io-arduino-client: a Socket.IO client for the Arduino
Based on the Kevin Rohling WebSocketClient & Bill Roy Socket.io Lbrary
Copyright 2015 Florent Vidal
Supports Socket.io v1.x
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#define ESP32
#include <SocketIOClient.h>
String tmpdata = ""; //External variables
String RID = "";
String Rname = "";
String Rcontent = "";
bool SocketIOClient::connect(char thehostname[], int theport, char thequery[] = "") {
if (!client.connect(thehostname, theport)) return false;
hostname = thehostname;
port = theport;
query = thequery;
sendHandshake(hostname, query);
return readHandshake();
}
bool SocketIOClient::connectHTTP(char thehostname[], int theport) {
if (!client.connect(thehostname, theport)) return false;
hostname = thehostname;
port = theport;
return true;
}
bool SocketIOClient::reconnect(char thehostname[], int theport, char thequery[] = "")
{
if (!client.connect(thehostname, theport)) return false;
hostname = thehostname;
port = theport;
query = thequery;
sendHandshake(hostname, query);
return readHandshake();
}
bool SocketIOClient::connected() {
return client.connected();
}
void SocketIOClient::disconnect() {
client.stop();
}
// find the nth colon starting from dataptr
void SocketIOClient::findColon(char which) {
while (*dataptr) {
if (*dataptr == ':') {
if (--which <= 0) return;
}
++dataptr;
}
}
// terminate command at dataptr at closing double quote
void SocketIOClient::terminateCommand(void) {
dataptr[strlen(dataptr) - 3] = 0;
}
void SocketIOClient::parser(int index) {
String rcvdmsg = "";
int sizemsg = databuffer[index + 1]; // 0-125 byte, index ok Fix provide by Galilei11. Thanks
if (databuffer[index + 1]>125)
{
sizemsg = databuffer[index + 2]; // 126-255 byte
index += 1; // index correction to start
}
Serial.print("Message size = "); //Can be used for debugging
Serial.println(sizemsg); //Can be used for debugging
for (int i = index + 2; i < index + sizemsg + 2; i++)
rcvdmsg += (char)databuffer[i];
Serial.print("Received message = "); //Can be used for debugging
Serial.println(rcvdmsg); //Can be used for debugging
switch (rcvdmsg[0])
{
case '2':
Serial.println("Ping received - Sending Pong");
heartbeat(1);
break;
case '3':
Serial.println("Pong received - All good");
break;
case '4':
switch (rcvdmsg[1])
{
case '0':
Serial.println("Upgrade to WebSocket confirmed");
break;
case '2':
int end = rcvdmsg.indexOf("\",");
if (end == -1) {
end = rcvdmsg.indexOf("\"]");
}
RID = rcvdmsg.substring(rcvdmsg.indexOf("[\"")+2, end);
RID = rcvdmsg.substring(4, rcvdmsg.indexOf("\","));
Rname = rcvdmsg.substring(rcvdmsg.indexOf("\",") + 4, rcvdmsg.indexOf("\":"));
Rcontent = rcvdmsg.substring(rcvdmsg.indexOf("\":") + 3, rcvdmsg.indexOf("\"}"));
//Serial.println("RID = " + RID);
//Serial.println("Rname = " + Rname);
//Serial.println("Rcontent = " + Rcontent);
Serial.println(rcvdmsg);
break;
}
}
}
bool SocketIOClient::monitor() {
int index = -1;
int index2 = -1;
String tmp = "";
*databuffer = 0;
//Checking for client availability, If not returning false
if (!client.connected() &&
!client.connect(hostname, port) &&
!client.available()) {
return false;
}
while (client.available()) {
readLine();
tmp = databuffer;
Serial.println(databuffer);
dataptr = databuffer;
index = tmp.indexOf((char)129); //129 DEC = 0x81 HEX = sent for proper communication
index2 = tmp.indexOf((char)129, index + 1);
/*Serial.print("Index = "); //Can be used for debugging
Serial.print(index);
Serial.print(" & Index2 = ");
Serial.println(index2);*/
if (index != -1)
{
parser(index);
}
if (index2 != -1)
{
parser(index2);
}
}
return true;
}
void SocketIOClient::sendHandshake(char hostname[], char query[] = "") {
client.print(F("GET /socket.io/1/?"));
client.print(query);
client.println(F("&transport=polling&b64=true HTTP/1.1"));
client.print(F("Host: "));
client.println(hostname);
client.println(F("Origin: Arduino\r\n"));
}
bool SocketIOClient::waitForInput(void) {
unsigned long now = millis();
while (!client.available() && ((millis() - now) < 30000UL)) { ; }
return client.available();
}
void SocketIOClient::eatHeader(void) {
while (client.available()) { // consume the header
readLine();
if (strlen(databuffer) == 0) break;
}
}
bool SocketIOClient::readHandshake() {
if (!waitForInput()) return false;
// check for happy "HTTP/1.1 200" response
readLine();
if (atoi(&databuffer[9]) != 200) {
while (client.available()) readLine();
client.stop();
return false;
}
eatHeader();
readLine();
String tmp = databuffer;
int sidindex = tmp.indexOf("sid");
int sidendindex = tmp.indexOf("\"", sidindex + 6);
int count = sidendindex - sidindex - 6;
for (int i = 0; i < count; i++)
{
sid[i] = databuffer[i + sidindex + 6];
}
Serial.println(" ");
Serial.print(F("Connected. SID="));
Serial.println(sid); // sid:transport:timeout
while (client.available()) readLine();
client.stop();
delay(1000);
// reconnect on websocket connection
if (!client.connect(hostname, port)) {
Serial.print(F("Websocket failed."));
return false;
}
Serial.println(F("Connecting via Websocket"));
client.print(F("GET /socket.io/1/websocket/?"));
client.print(query);
client.print(F("&transport=websocket&b64=true&sid="));
client.print(sid);
client.print(F(" HTTP/1.1\r\n"));
client.print(F("Host: "));
client.print(hostname);
client.print("\r\n");
client.print(F("Sec-WebSocket-Version: 13\r\n"));
client.print(F("Origin: ArduinoSocketIOClient\r\n"));
client.print(F("Sec-WebSocket-Extensions: permessage-deflate\r\n"));
client.print(F("Sec-WebSocket-Key: IAMVERYEXCITEDESP32FTW==\r\n")); // can be anything
client.print(F("Cookie: io="));
client.print(sid);
client.print("\r\n");
client.print(F("Connection: Upgrade\r\n"));
client.println(F("Upgrade: websocket\r\n")); // socket.io v2.0.3 supported
if (!waitForInput()) return false;
readLine();
if (atoi(&databuffer[9]) != 101) { // check for "HTTP/1.1 101 response, means Updrage to Websocket OK
while (client.available()) readLine();
client.stop();
return false;
}
readLine();
readLine();
readLine();
for (int i = 0; i < 28; i++)
{
key[i] = databuffer[i + 22]; //key contains the Sec-WebSocket-Accept, could be used for verification
}
eatHeader();
/*
Generating a 32 bits mask requiered for newer version
Client has to send "52" for the upgrade to websocket
*/
randomSeed(analogRead(0));
String mask = "";
String masked = "52";
String message = "52";
for (int i = 0; i < 4; i++) //generate a random mask, 4 bytes, ASCII 0 to 9
{
char a = random(48, 57);
mask += a;
}
for (int i = 0; i < message.length(); i++)
masked[i] = message[i] ^ mask[i % 4]; //apply the "mask" to the message ("52")
client.print((char)0x81); //has to be sent for proper communication
client.print((char)130); //size of the message (2) + 128 because message has to be masked
client.print(mask);
client.print(masked);
monitor(); // treat the response as input
return true;
}
void SocketIOClient::getREST(String path)
{
String message = "GET /" + path + "/ HTTP/1.1";
client.println(message);
client.print(F("Host: "));
client.println(hostname);
client.println(F("Origin: Arduino"));
client.println(F("Connection: close\r\n"));
}
void SocketIOClient::postREST(String path, String type, String data)
{
String message = "POST /" + path + "/ HTTP/1.1";
client.println(message);
client.print(F("Host: "));
client.println(hostname);
client.println(F("Origin: Arduino"));
client.println(F("Connection: close\r\n"));
client.print(F("Content-Length: "));
client.println(data.length());
client.print(F("Content-Type: "));
client.println(type);
client.println("\r\n");
client.println(data);
}
void SocketIOClient::putREST(String path, String type, String data)
{
String message = "PUT /" + path + "/ HTTP/1.1";
client.println(message);
client.print(F("Host: "));
client.println(hostname);
client.println(F("Origin: Arduino"));
client.println(F("Connection: close\r\n"));
client.print(F("Content-Length: "));
client.println(data.length());
client.print(F("Content-Type: "));
client.println(type);
client.println("\r\n");
client.println(data);
}
void SocketIOClient::deleteREST(String path)
{
String message = "DELETE /" + path + "/ HTTP/1.1";
client.println(message);
client.print(F("Host: "));
client.println(hostname);
client.println(F("Origin: Arduino"));
client.println(F("Connection: close\r\n"));
}
void SocketIOClient::readLine() {
for (int i = 0; i < DATA_BUFFER_LEN; i++)
databuffer[i] = ' ';
dataptr = databuffer;
while (client.available() && (dataptr < &databuffer[DATA_BUFFER_LEN - 2]))
{
char c = client.read();
Serial.print(c); //Can be used for debugging
if (c == 0) Serial.print("");
else if (c == 255) Serial.println("");
else if (c == '\r') { ; }
else if (c == '\n') break;
else *dataptr++ = c;
}
*dataptr = 0;
}
void SocketIOClient::send(String RID, String Rname, String Rcontent) {
String message = "42[\"" + RID + "\",{\"" + Rname + "\":\"" + Rcontent + "\"}]";
int header[10];
header[0] = 0x81;
int msglength = message.length();
randomSeed(analogRead(0));
String mask = "";
String masked = message;
for (int i = 0; i < 4; i++)
{
char a = random(48, 57);
mask += a;
}
for (int i = 0; i < msglength; i++)
masked[i] = message[i] ^ mask[i % 4];
client.print((char)header[0]); //has to be sent for proper communication
//Depending on the size of the message
if (msglength <= 125)
{
header[1] = msglength + 128;
client.print((char)header[1]); //size of the message + 128 because message has to be masked
}
else if (msglength >= 126 && msglength <= 65535)
{
header[1] = 126 + 128;
client.print((char)header[1]);
header[2] = (msglength >> 8) & 255;
client.print((char)header[2]);
header[3] = (msglength)& 255;
client.print((char)header[3]);
}
else
{
header[1] = 127 + 128;
client.print((char)header[1]);
header[2] = (msglength >> 56) & 255;
client.print((char)header[2]);
header[3] = (msglength >> 48) & 255;
client.print((char)header[4]);
header[4] = (msglength >> 40) & 255;
client.print((char)header[4]);
header[5] = (msglength >> 32) & 255;
client.print((char)header[5]);
header[6] = (msglength >> 24) & 255;
client.print((char)header[6]);
header[7] = (msglength >> 16) & 255;
client.print((char)header[7]);
header[8] = (msglength >> 8) & 255;
client.print((char)header[8]);
header[9] = (msglength)& 255;
client.print((char)header[9]);
}
client.print(mask);
client.print(masked);
}
void SocketIOClient::sendJSON(String RID, String JSON) {
String message = "42[\"" + RID + "\"," + JSON + "]";
int header[10];
header[0] = 0x81;
int msglength = message.length();
randomSeed(analogRead(0));
String mask = "";
String masked = message;
for (int i = 0; i < 4; i++)
{
char a = random(48, 57);
mask += a;
}
for (int i = 0; i < msglength; i++)
masked[i] = message[i] ^ mask[i % 4];
client.print((char)header[0]); //has to be sent for proper communication
//Depending on the size of the message
if (msglength <= 125)
{
header[1] = msglength + 128;
client.print((char)header[1]); //size of the message + 128 because message has to be masked
}
else if (msglength >= 126 && msglength <= 65535)
{
header[1] = 126 + 128;
client.print((char)header[1]);
header[2] = (msglength >> 8) & 255;
client.print((char)header[2]);
header[3] = (msglength)& 255;
client.print((char)header[3]);
}
else
{
header[1] = 127 + 128;
client.print((char)header[1]);
header[2] = (msglength >> 56) & 255;
client.print((char)header[2]);
header[3] = (msglength >> 48) & 255;
client.print((char)header[4]);
header[4] = (msglength >> 40) & 255;
client.print((char)header[4]);
header[5] = (msglength >> 32) & 255;
client.print((char)header[5]);
header[6] = (msglength >> 24) & 255;
client.print((char)header[6]);
header[7] = (msglength >> 16) & 255;
client.print((char)header[7]);
header[8] = (msglength >> 8) & 255;
client.print((char)header[8]);
header[9] = (msglength)& 255;
client.print((char)header[9]);
}
client.print(mask);
client.print(masked);
}
void SocketIOClient::heartbeat(int select) {
randomSeed(analogRead(0));
String mask = "";
String masked = "";
String message = "";
if (select == 0)
{
masked = "2";
message = "2";
}
else
{
masked = "3";
message = "3";
}
for (int i = 0; i < 4; i++) //generate a random mask, 4 bytes, ASCII 0 to 9
{
char a = random(48, 57);
mask += a;
}
for (int i = 0; i < message.length(); i++)
masked[i] = message[i] ^ mask[i % 4]; //apply the "mask" to the message ("2" : ping or "3" : pong)
client.print((char)0x81); //has to be sent for proper communication
client.print((char)129); //size of the message (1) + 128 because message has to be masked
client.print(mask);
client.print(masked);
}