-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathWebsocket.h
More file actions
407 lines (358 loc) · 11.6 KB
/
Websocket.h
File metadata and controls
407 lines (358 loc) · 11.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
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
#ifndef WEBSOCKET_H
#define WEBSOCKET_H
#if defined(ARDUINO)
#include <Arduino.h>
#include <WebSocketsClient.h>
typedef String WSInterfaceString;
#else
#include <tiny_websockets/client.hpp>
#include <sys/time.h>
#include <functional>
typedef std::string WSInterfaceString;
#endif
#ifdef SERIAL_DEBUG
#if defined(ARDUINO)
#define WS_DEBUG(...) \
Serial.print("Websocket: "); \
Serial.printf(__VA_ARGS__)
#else
#define WS_DEBUG(...) \
fprintf(stdout, "Websocket: "); \
fprintf(stdout, __VA_ARGS__)
#endif
#else
#define WS_DEBUG(...)
#endif
typedef enum {
WSEvent_ERROR,
WSEvent_DISCONNECTED,
WSEvent_CONNECTED,
WSEvent_TEXT,
WSEvent_BIN,
// WStype_FRAGMENT_TEXT_START,
// WStype_FRAGMENT_BIN_START,
// WStype_FRAGMENT,
// WStype_FRAGMENT_FIN,
WSEvent_PING,
WSEvent_PONG,
} WSEvent_t;
typedef std::function<void(WSEvent_t type, uint8_t * payload, size_t length)> WebSocketEventCallback;
#if defined(ARDUINO)
class WebsocketClient : protected WebSocketsClient {
public:
WebsocketClient() : WebSocketsClient() {
// Set up a callback to handle incoming pings
WebSocketsClient::onEvent([this](WStype_t type, uint8_t *payload, size_t length) {
switch (type) {
case WStype_ERROR:
WS_DEBUG("Error!\n");
_callback(WSEvent_ERROR, payload, length);
break;
case WStype_DISCONNECTED:
WS_DEBUG("Disconnected!\n");
_callback(WSEvent_DISCONNECTED, payload, length);
break;
case WStype_CONNECTED: {
WS_DEBUG("Connected to url: %s\n", payload);
_callback(WSEvent_CONNECTED, payload, length);
} break;
case WStype_TEXT:
WS_DEBUG("get text: %s\n", payload);
_callback(WSEvent_TEXT, payload, length);
break;
case WStype_BIN:
WS_DEBUG("get binary length: %u\n", length);
_callback(WSEvent_BIN, payload, length);
break;
case WStype_PING:
WS_DEBUG("get ping\n");
_callback(WSEvent_PING, payload, length);
break;
case WStype_PONG:
WS_DEBUG("get pong\n");
_callback(WSEvent_PONG, payload, length);
break;
default:
WS_DEBUG("Unknown event type: %d\n", type);
break;
}
});
}
/**
* @brief Connect to a websocket server
*
* @param host String containing the host name or IP address of the server
* @param port Port number to connect to
* @param path Path to connect to on the server
*/
void connect(WSInterfaceString host, int port, WSInterfaceString path);
/**
* @brief Connect to a websocket server using a secure connection
*
* @param host String containing the host name or IP address of the server
* @param port Port number to connect to
* @param path Path to connect to on the server
*/
void connectSecure(WSInterfaceString host, int port, WSInterfaceString path);
/**
* @brief Close the connection to the websocket server
*
*/
void close() {
WS_DEBUG("Closing connection\n");
WebSocketsClient::disconnect();
}
/**
* @brief Enable a heartbeat to keep the connection alive
*
* @param interval Time in milliseconds between heartbeats
* @param timeout Time in milliseconds to wait for a response to the heartbeat
* @param maxMissed Maximum number of missed heartbeats before closing the connection
*/
void enableHeartbeat(unsigned long interval, unsigned long timeout, uint8_t maxMissed);
/**
* @brief Disable the heartbeat
*
*/
void disableHeartbeat();
/**
* @brief Sets the interval between reconnection attempts
*
* @param interval Time in milliseconds between reconnection attempts
*/
void setReconnectInterval(unsigned long interval);
/**
* @brief Poll the websocket connection
*
*/
void poll();
/**
* @brief Set the callback function to run when an event occurs
*
* @param callback Function to run when an event occurs
*/
void onEvent(WebSocketEventCallback callback);
/**
* @brief Sets is streaming to false, used for reconnecting
*
*/
void resetStreaming();
/**
* @brief Enable streaming mode
* @return true Streaming mode enabled
* @return false Streaming mode not enabled
*/
bool stream();
/**
* @brief Send a text message to the server
* @param payload Data to send
* @param length Length of the data to send
* @param headerToPayload bool (see sendFrame for more details)
* @return true Message was successful
* @return false Message was unsuccessful
*/
bool send(uint8_t *payload, size_t length, bool headerToPayload = false);
/**
* @brief Send a text message to the server
* @param payload Data to send
* @param length Length of the data to send
* @param headerToPayload bool (see sendFrame for more details)
* @return true Message was successful
* @return false Message was unsuccessful
*/
bool send(const char *payload, size_t length, bool headerToPayload = false);
/**
* @brief End the stream
* @return true Stream ended
* @return false Stream failed to end
*/
bool end();
private:
bool enableReconnect = false;
unsigned long reconnectInterval = 0;
WSInterfaceString host;
int port;
WSInterfaceString path;
WebSocketEventCallback eventCallback = nullptr;
void _callback(WSEvent_t type, uint8_t * payload, size_t length) {
if (eventCallback) {
eventCallback(type, payload, length);
}
}
bool isSecure = false;
bool isStreaming = false;
};
#else
unsigned long millis();
class WebsocketClient : protected websockets::WebsocketsClient {
public:
WebsocketClient() : websockets::WebsocketsClient() {
websockets::WebsocketsClient::onEvent([this](websockets::WebsocketsEvent event, websockets::WSInterfaceString message) {
switch (event) {
case websockets::WebsocketsEvent::GotPing:
// Respond to the ping
WS_DEBUG("Ponged a ping\n");
pong(message);
_callback(WSEvent_PING, (uint8_t *) message.c_str(), message.length());
break;
case websockets::WebsocketsEvent::GotPong:
WS_DEBUG("Received a pong\n");
if (heartbeatEnabled) {
// If heartbeat is enabled, reset the missed coun and set the heartbeat in progress flag to false
heartbeatMissed = 0;
heartbeatInProgress = false;
}
_callback(WSEvent_PONG, (uint8_t *) message.c_str(), message.length());
break;
case websockets::WebsocketsEvent::ConnectionOpened:
WS_DEBUG("Connection opened\n");
_callback(WSEvent_CONNECTED, (uint8_t *) message.c_str(), message.length());
break;
case websockets::WebsocketsEvent::ConnectionClosed:
WS_DEBUG("Connection closed\n");
// If the connection was closed, set the heartbeat in progress flag to false
if (heartbeatEnabled) {
heartbeatMissed = 0;
heartbeatInProgress = false;
}
_callback(WSEvent_DISCONNECTED, (uint8_t *) message.c_str(), message.length());
break;
}
});
websockets::WebsocketsClient::onMessage([this](websockets::WebsocketsMessage message) -> void {
WS_DEBUG("Received websocket message\n");
switch (message.type()) {
case websockets::MessageType::Text:
WS_DEBUG("get text: %s\n", message.c_str());
_callback(WSEvent_TEXT, (uint8_t *) message.c_str(), message.length());
break;
case websockets::MessageType::Binary:
WS_DEBUG("get binary length: %u\n", message.length());
_callback(WSEvent_BIN, (uint8_t *) message.c_str(), message.length());
break;
case websockets::MessageType::Ping:
case websockets::MessageType::Pong:
//Already handled
break;
default:
WS_DEBUG("unsupported message type %u\n", message.type());
break;
}
});
}
/**
* @brief Connect to a websocket server
*
* @param host String containing the host name or IP address of the server
* @param port Port number to connect to
* @param path Path to connect to on the server
*/
void connect(WSInterfaceString host, int port, WSInterfaceString path);
// /**
// * @brief Connect to a websocket server using a secure connection
// *
// * @param host String containing the host name or IP address of the server
// * @param port Port number to connect to
// * @param path Path to connect to on the server
// */
// void connectSecure(WSInterfaceString host, int port, WSInterfaceString path);
/**
* @brief Close the connection to the websocket server
*
*/
void close() {
shouldReconnect = false;
heartbeatMissed = 0;
heartbeatInProgress = false;
websockets::WebsocketsClient::close();
}
/**
* @brief Enable a heartbeat to keep the connection alive
*
* @param interval Time in milliseconds between heartbeats
* @param timeout Time in milliseconds to wait for a response to the heartbeat
* @param maxMissed Maximum number of missed heartbeats before closing the connection
*/
void enableHeartbeat(unsigned long interval, unsigned long timeout, uint8_t maxMissed);
/**
* @brief Disable the heartbeat
*
*/
void disableHeartbeat();
/**
* @brief Sets the interval between reconnection attempts
*
* @param interval Time in milliseconds between reconnection attempts
*/
void setReconnectInterval(unsigned long interval);
/**
* @brief Poll the websocket connection
*
*/
void poll();
/**
* @brief Set the callback function to run when an event occurs
*
* @param callback Function to run when an event occurs
*/
void onEvent(WebSocketEventCallback callback);
/**
* @brief Sets is streaming to false, used for reconnecting
*
*/
void resetStreaming();
/**
* @brief Enable streaming mode
* @return true Streaming mode enabled
* @return false Streaming mode not enabled
*/
bool stream();
/**
* @brief Send a text message to the server
* @param payload Data to send
* @param length Length of the data to send
* @param headerToPayload bool (see sendFrame for more details)
* @return true Message was successful
* @return false Message was unsuccessful
*/
bool send(uint8_t *payload, size_t length, bool headerToPayload = false);
/**
* @brief Send a text message to the server
* @param payload Data to send
* @param length Length of the data to send
* @param headerToPayload bool (see sendFrame for more details)
* @return true Message was successful
* @return false Message was unsuccessful
*/
bool send(const char *payload, size_t length, bool headerToPayload = false);
/**
* @brief End the stream
* @return true Stream ended
* @return false Stream failed to end
*/
bool end();
private:
unsigned int heartbeatInterval = 0;
unsigned int heartbeatTimeout = 0;
unsigned long heartbeatLastSent = 0;
unsigned int heartbeatMissed = 0;
unsigned int heartbeatMaxMissed = 0;
bool heartbeatInProgress = false;
bool heartbeatEnabled = false;
unsigned int reconnectInterval = 500;
unsigned long reconnectLastAttempt = 0;
bool shouldReconnect = false;
WSInterfaceString host;
int port;
WSInterfaceString path;
WebSocketEventCallback eventCallback = nullptr;
void _callback(WSEvent_t type, uint8_t * payload, size_t length) {
if (eventCallback) {
eventCallback(type, payload, length);
}
}
bool done = false;
bool isStreaming = false;
};
#endif
#endif