-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebSocket.cpp
107 lines (81 loc) · 1.85 KB
/
WebSocket.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
#include <ArduinoJson.h>
#include "WebSocket.h"
#include "SumpThingHelpers.h"
using namespace std;
using namespace std::placeholders;
WebSocket::WebSocket()
{
strcpy(ip, SERVER_IP);
port = SERVER_PORT;
std::function<void(WStype_t type, uint8_t * payload, size_t length)> handleEvents = std::bind(&WebSocket::eventHandler, this, _1, _2, _3);
client.beginSocketIO(ip, port);
client.onEvent(handleEvents);
}
void WebSocket::loop()
{
client.loop();
if (isConnected) {
uint64_t now = millis();
if ((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
heartbeatTimestamp = now;
// socket.io heartbeat message
client.sendTXT("2");
}
}
}
void WebSocket::eventHandler(WStype_t type, uint8_t * payload, size_t length)
{
switch (type) {
case WStype_CONNECTED:
connect();
break;
case WStype_DISCONNECTED:
disconnect();
break;
case WStype_TEXT:
// Don't care about heartbeats
if (length > 3)
{
int offset = 2;
char * json = new char[length + 4]();
string jsonCoersion = "{\"0\":";
strcpy(json, jsonCoersion.c_str());
int index = offset;
Serial.printf("%s\n", payload);
while (index <= length)
{
json[(index - offset) + 5] = (char)payload[index];
index++;
}
json[length + 3] = *"}";
DynamicJsonBuffer jsonBuffer;
JsonObject& payloadJson = jsonBuffer.parseObject(json);
handleMessage(payloadJson);
jsonBuffer.clear();
}
}
}
void WebSocket::disconnect()
{
isConnected = false;
}
void WebSocket::connect()
{
isConnected = true;
// Socket.IO upgrade confirmation
client.sendTXT("5");
}
void WebSocket::handleMessage(JsonObject& payload)
{
String command = payload["0"][0];
JsonObject& args = payload["0"][1];
if (command == "UPDATE_OUTLET_BATCH")
{
commandHandler.batchUpdateOutlets(args);
}
else if (command == "UPDATE_OUTLET")
{
commandHandler.updateOutlet(args);
}
return;
}