Repository navigation
Expand file tree
/
Copy pathWebsocket.cpp
More file actions
295 lines (253 loc) · 8.28 KB
/
Copy pathWebsocket.cpp
File metadata and controls
295 lines (253 loc) · 8.28 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
#include "Websocket.h"
#if defined(ESP32)
#include <esp_random.h>
#elif !defined(ARDUINO)
#include <sys/random.h>
#include <time.h>
#include <unistd.h>
#endif
namespace {
uint32_t reconnectSeed() {
#if defined(ESP8266)
return uint32_t(secureRandom(0x7fffffffL)) ^ (uint32_t(secureRandom(0x7fffffffL)) << 1) ^ ESP.getChipId();
#elif defined(ESP32)
const uint64_t mac = ESP.getEfuseMac();
return esp_random() ^ uint32_t(mac) ^ uint32_t(mac >> 32);
#else
uint32_t seed;
if (getrandom(&seed, sizeof(seed), GRND_NONBLOCK) == sizeof(seed)) return seed;
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return uint32_t(ts.tv_nsec) ^ uint32_t(ts.tv_sec) ^ uint32_t(getpid());
#endif
}
struct PollGuard {
bool &flag;
explicit PollGuard(bool &value) : flag(value) { flag = true; }
~PollGuard() { flag = false; }
};
}
#if defined(ARDUINO)
#ifdef OTF_SECURE_CLOUD
bool WebsocketClient::pauseTransport() {
if(polling)return false;
// A disconnect callback may call poll(), including after slow TLS cleanup.
// Never allow it to allocate a new connection inside the intentional pause.
PollGuard guard(polling);
enableReconnect = true;
attemptActive = false;
WebSockets::clientDisconnect(&_client, 1000);
retry.paused(millis()); // Coalescing delay starts after cleanup completes.
return true;
}
#endif
void WebsocketClient::enableHeartbeat(uint32_t interval, uint32_t timeout, uint8_t maxMissed) {
WebSocketsClient::enableHeartbeat(interval, timeout, maxMissed);
}
void WebsocketClient::disableHeartbeat() {
WebSocketsClient::disableHeartbeat();
}
void WebsocketClient::setReconnectInterval(uint32_t interval) {
reconnectInterval = interval;
retry.configure(millis(), reconnectSeed(), interval);
// Only poll() may authorize a new attempt, never the transport's inner loop.
WebSocketsClient::setReconnectInterval(UINT32_MAX);
}
void WebsocketClient::resetStreaming() {
isStreaming = false;
}
void WebsocketClient::poll() {
if (polling) return;
PollGuard guard(polling);
clientIsConnected(&_client);
if (_client.status == WSC_NOT_CONNECTED) {
if (attemptActive) {
attemptActive = false;
retry.failed(millis());
}
if (!enableReconnect || !retry.ready(millis())) return;
attemptActive = true;
WebSocketsClient::setReconnectInterval(0);
WebSocketsClient::loop();
WebSocketsClient::setReconnectInterval(UINT32_MAX);
} else {
// If TCP dies between our check and loop(), its reconnect path stays gated.
_lastConnectionFail = millis();
WebSocketsClient::loop();
}
clientIsConnected(&_client); // Free failed sockets before starting the delay.
if (_client.status == WSC_NOT_CONNECTED && attemptActive) {
attemptActive = false;
retry.failed(millis());
}
if (_client.status == WSC_CONNECTED) retry.update(millis());
}
void WebsocketClient::onEvent(WebSocketEventCallback callback) {
WS_DEBUG("Setting event callback\n");
this->eventCallback = callback;
}
void WebsocketClient::connect(WSInterfaceString host, int port, WSInterfaceString path) {
WS_DEBUG("Connecting to ws://%s:%d%s\n", host.c_str(), port, path.c_str());
close(false);
WebSocketsClient::begin(host, port, path);
enableReconnect = true;
attemptActive = false;
setReconnectInterval(reconnectInterval);
}
void WebsocketClient::connectSecure(WSInterfaceString host, int port, WSInterfaceString path) {
close(false);
WebSocketsClient::beginSSL(host.c_str(), port, path.c_str());
enableReconnect = true;
attemptActive = false;
setReconnectInterval(reconnectInterval);
}
bool WebsocketClient::stream() {
if (isStreaming) {
WS_DEBUG("Already streaming\n");
return false;
}
if (clientIsConnected(&_client)) {
isStreaming = sendFrame(&_client, WSop_text, (uint8_t *) "", 0, false, false);
} else {
isStreaming = false;
}
return isStreaming;
}
bool WebsocketClient::send(uint8_t *payload, size_t length, bool headerToPayload) {
WS_DEBUG("Sending message of length %d\n", length);
if (length == 0) {
length = strlen((const char *) payload);
}
if (clientIsConnected(&_client)) {
if (isStreaming) {
return sendFrame(&_client, WSop_continuation, payload, length, false, headerToPayload);
} else {
return sendFrame(&_client, WSop_text, payload, length, true, headerToPayload);
}
}
return false;
}
bool WebsocketClient::send(const char *payload, size_t length, bool headerToPayload) {
return send((uint8_t *) payload, length, headerToPayload);
}
bool WebsocketClient::end() {
if (!isStreaming) {
return true;
}
WS_DEBUG("Ending stream\n");
bool res = sendFrame(&_client, WSop_continuation, (uint8_t *) "", 0, true, false);
isStreaming = !res;
return res;
}
#else
void WebsocketClient::enableHeartbeat(uint32_t interval, uint32_t timeout, uint8_t maxMissed) {
heartbeatEnabled = true;
heartbeatInterval = interval;
heartbeatTimeout = timeout;
heartbeatMaxMissed = maxMissed;
}
void WebsocketClient::disableHeartbeat() {
heartbeatEnabled = false;
}
void WebsocketClient::setReconnectInterval(uint32_t interval) {
reconnectInterval = interval;
retry.configure(millis(), reconnectSeed(), interval);
}
void WebsocketClient::resetStreaming() {
isStreaming = false;
}
// Monotonic time with Arduino's 32-bit wrap semantics; wall-clock corrections
// must not change retry or heartbeat deadlines.
uint32_t millis() {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return uint32_t(uint64_t(ts.tv_sec) * 1000 + ts.tv_nsec / 1000000);
}
void WebsocketClient::poll() {
if (polling) return;
PollGuard guard(polling);
websockets::WebsocketsClient::poll();
if (heartbeatEnabled && available()) {
if (!heartbeatInProgress && (millis() - heartbeatLastSent > heartbeatInterval)) {
if (heartbeatMissed >= heartbeatMaxMissed) {
// Too many missed heartbeats, close the connection
WS_DEBUG("Too many missed heartbeats, closing connection\n");
heartbeatMissed = 0;
websockets::WebsocketsClient::close();
heartbeatInProgress = false;
return;
}
WS_DEBUG("Sending ping\n");
ping();
heartbeatLastSent = millis();
heartbeatInProgress = true;
}
if (heartbeatInProgress && (millis() - heartbeatLastSent > heartbeatTimeout)) {
// Heartbeat timeout
WS_DEBUG("Heartbeat timeout\n");
heartbeatMissed++;
heartbeatInProgress = false;
return;
}
}
if (available()) {
retry.update(millis());
return;
}
if (attemptActive) {
attemptActive = false;
retry.failed(millis());
}
if (shouldReconnect && retry.ready(millis())) {
attemptActive = true;
if (!websockets::WebsocketsClient::connect(host, port, path)) {
attemptActive = false;
retry.failed(millis());
}
}
}
void WebsocketClient::onEvent(WebSocketEventCallback callback) {
WS_DEBUG("Setting event callback\n");
this->eventCallback = callback;
}
void WebsocketClient::connect(WSInterfaceString host, int port, WSInterfaceString path) {
WS_DEBUG("Connecting to ws://%s:%d%s\n", host.c_str(), port, path.c_str());
close(false);
this->host = host;
this->port = port;
this->path = path;
shouldReconnect = true;
heartbeatMissed = 0;
heartbeatInProgress = false;
// isSecure = false;
attemptActive = false;
setReconnectInterval(reconnectInterval);
}
// void WebsocketClient::connectSecure(WSInterfaceString host, int port, WSInterfaceString path) {
// WS_DEBUG("Connecting to wss://%s:%d%s\n", host.c_str(), port, path.c_str());
// this->host = host;
// this->port = port;
// this->path = path;
// shouldReconnect = true;
// heartbeatMissed = 0;
// heartbeatInProgress = false;
// isSecure = true;
// websockets::WebsocketsClient::connect(host, port, path);
// }
bool WebsocketClient::stream() {
return websockets::WebsocketsClient::stream();
}
bool WebsocketClient::send(uint8_t *payload, size_t length, bool headerToPayload) {
return send((const char*) payload, length, headerToPayload);
}
bool WebsocketClient::send(const char *payload, size_t length, bool headerToPayload) {
WS_DEBUG("Sending message of length %d\n", length);
if (length == 0) {
length = strlen(payload);
}
return websockets::WebsocketsClient::send((const char*) payload, length);
}
bool WebsocketClient::end() {
return websockets::WebsocketsClient::end();
}
#endif