Repository navigation
Expand file tree
/
Copy pathOpenThingsFramework.cpp
More file actions
executable file
·666 lines (609 loc) · 23.1 KB
/
Copy pathOpenThingsFramework.cpp
File metadata and controls
executable file
·666 lines (609 loc) · 23.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
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
#include "OpenThingsFramework.h"
#include "ForwardedRequest.h"
#include "HttpParser.h"
#include "StringBuilder.hpp"
#include <string>
#include <stdlib.h>
#include <new>
#if !defined(ARDUINO)
#include <unistd.h>
#endif
// The timeout for reading and parsing incoming requests.
#define WIFI_CONNECTION_TIMEOUT 1500
/* How often to try to reconnect to the websocket if the connection is lost. Each reconnect attempt is blocking and has
* a 5 second timeout.
*/
#define WEBSOCKET_RECONNECT_INTERVAL 5000
// Upper bound on Content-Length we'll allocate for the request body. Anything
// larger is rejected with 413 — protects against rogue/malformed clients
// declaring huge bodies that would exhaust heap on small targets.
#ifndef OTF_MAX_BODY_SIZE
#define OTF_MAX_BODY_SIZE 8192
#endif
// Reserve space for the normalized request terminator and intermediate writes.
static const size_t HEADER_BUFFER_RESERVED_BYTES = 10;
using namespace OTF;
static void waitForRequestData() {
#if defined(ARDUINO)
delay(1);
#else
usleep(1000);
#endif
}
/* Reads one physical line through its '\n', which is consumed but not stored.
* At most cap-1 bytes are kept, NUL-terminated; `overflow` reports a longer line,
* whose remainder is consumed and discarded so it can never be parsed as another
* line. Returns false once `start` is WIFI_CONNECTION_TIMEOUT old, whether or
* not input is still arriving. */
static bool readRequestLine(LocalClient *client, char *buf, size_t cap, size_t &len, bool &overflow,
uint32_t start) {
len = 0;
overflow = false;
buf[0] = 0;
for (;;) {
// One deadline for the whole request line and headers, checked on every
// byte: a client that keeps sending cannot extend it.
if (millis() - start >= WIFI_CONNECTION_TIMEOUT) {
buf[len] = 0;
return false;
}
char c;
if (client->availableBytes() == 0 || client->readBytes(&c, 1) != 1) {
waitForRequestData();
continue;
}
if (c == '\n') {
buf[len] = 0;
return true;
}
if (len + 1 < cap) buf[len++] = c;
else overflow = true;
}
}
static bool isKeptHeader(const char *line, size_t len) {
// `line` is NUL-terminated, so a short line ends the comparison safely.
static const char *const kept[] = {"content-length:", "if-none-match:"};
for (const char *name : kept) {
const size_t n = strlen(name);
if (len >= n && strncasecmp(line, name, n) == 0) return true;
}
return false;
}
OpenThingsFramework::OpenThingsFramework(uint16_t webServerPort, char *hdBuffer, int hdBufferSize) : localServer(webServerPort) {
OTF_DEBUG("Instantiating OTF...\n");
if(hdBuffer != NULL) { // if header buffer is externally provided, use it directly
headerBuffer = hdBuffer;
headerBufferSize = (hdBufferSize > 0) ? static_cast<size_t>(hdBufferSize) : HEADERS_BUFFER_SIZE;
ownsHeaderBuffer = false;
} else { // otherwise allocate one
headerBuffer = new (std::nothrow) char[HEADERS_BUFFER_SIZE];
headerBufferSize = headerBuffer ? HEADERS_BUFFER_SIZE : 0;
ownsHeaderBuffer = true;
}
if (headerBuffer && headerBufferSize > 0) headerBuffer[0] = '\0';
missingPageCallback = defaultMissingPageCallback;
localServer.begin();
};
OpenThingsFramework::~OpenThingsFramework() {
delete webSocket;
#if defined(ARDUINO)
clearPendingCloudRequest();
#endif
if (ownsHeaderBuffer) {
delete[] headerBuffer;
}
}
#if defined(ARDUINO)
OpenThingsFramework::OpenThingsFramework(uint16_t webServerPort, const String &webSocketHost, uint16_t webSocketPort,
const String &deviceKey, bool useSsl, char *hdBuffer, int hdBufferSize) : OpenThingsFramework(webServerPort, hdBuffer, hdBufferSize) {
#else
OpenThingsFramework::OpenThingsFramework(uint16_t webServerPort, const char* webSocketHost, uint16_t webSocketPort,
const char* deviceKey, bool useSsl, char *hdBuffer, int hdBufferSize) : OpenThingsFramework(webServerPort, hdBuffer, hdBufferSize) {
#endif
setCloudStatus(UNABLE_TO_CONNECT);
OTF_DEBUG(F("Initializing websocket...\n"));
webSocket = new WebsocketClient();
// Wrap the member function in a static function.
webSocket->onEvent([this](WSEvent_t type, uint8_t *payload, size_t length) -> void {
OTF_DEBUG((char *) F("Received websocket event of type %d\n"), type);
webSocketEventCallback(type, payload, length);
});
if (useSsl) {
OTF_DEBUG(F("Connecting to websocket with SSL\n"));
#ifdef OTF_SECURE_CLOUD
webSocket->connectSecure(webSocketHost,webSocketPort,"/socket/v1?deviceKey="+deviceKey);
#endif
} else {
OTF_DEBUG(F("Connecting to websocket without SSL\n"));
#if defined(ARDUINO)
webSocket->connect(webSocketHost, webSocketPort, "/socket/v1?deviceKey=" + deviceKey);
#else
std::string path = std::string("/socket/v1?deviceKey=") + deviceKey;
webSocket->connect(std::string(webSocketHost), webSocketPort, path);
#endif
}
OTF_DEBUG(F("Initialized websocket\n"));
// Try to reconnect to the websocket if the connection is lost.
webSocket->setReconnectInterval(WEBSOCKET_RECONNECT_INTERVAL);
// Ping the server every 15 seconds with a timeout of 5 seconds, and treat 1 missed ping as a lost connection.
webSocket->enableHeartbeat(15000, 5000, 1);
}
// Allocate a route key sized exactly for "<methodDigit><path>". Caller passes
// the resulting pointer to LinkedMap::addOwned, which transfers ownership to
// the node and frees it on destruction.
static char *makeStoredKey(HTTPMethod method, const char *path) {
int len = snprintf(nullptr, 0, "%d%s", (int)method, path);
char *key = new char[len + 1];
snprintf(key, len + 1, "%d%s", (int)method, path);
return key;
}
void OpenThingsFramework::on(const char *path, callback_t callback, HTTPMethod method) {
callbacks.addOwned(makeStoredKey(method, path), callback);
}
#if defined(ARDUINO)
void OpenThingsFramework::on(const __FlashStringHelper *path, callback_t callback, HTTPMethod method) {
// Cast: works on ESP8266/ESP32 where flash is byte-addressable like RAM.
// Not portable to AVR — same constraint as the previous makeMapKey path.
callbacks.addOwned(makeStoredKey(method, (const char *)path), callback);
}
#endif
void OpenThingsFramework::onMissingPage(callback_t callback) {
missingPageCallback = callback;
}
bool OpenThingsFramework::localServerLoop() {
static uint32_t wait_to = 0; // timeout to wait for client data
auto closeCurrentClient = [this]() {
localClient->flush();
localClient->stop();
localClient = localServer.acceptClient();
wait_to = localClient ? millis() + WIFI_CONNECTION_TIMEOUT : 0;
};
if (!wait_to) {
localClient = localServer.acceptClient();
// If a client wasn't available from the server, exit the local server loop.
if (!localClient) {
return false;
}
// set a timeout to wait for client data
wait_to = millis()+WIFI_CONNECTION_TIMEOUT;
}
if (!localClient->dataAvailable()) {
// If data isn't available from the client yet, exit the local server loop and check again next iteration.
// but if we reached timeout, then reset wait_to to 0 and flush localClient so we can accept new client
if((int32_t)(millis()-wait_to) >= 0) {
wait_to=0;
OTF_DEBUG(F("client wait timeout\n"));
localClient->flush();
localClient->stop();
}
return true;
}
// got new client data, reset wait_to to 0
wait_to = 0;
if (!headerBuffer || headerBufferSize <= HEADER_BUFFER_RESERVED_BYTES) {
OTF_DEBUG(F("Header buffer is unavailable or too small\n"));
localClient->print(F("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\nInsufficient header buffer"));
closeCurrentClient();
return true;
}
// Update the timeout for each data read to ensure that the total timeout is WIFI_CONNECTION_TIMEOUT.
uint32_t timeoutStart = millis();
char *buffer = headerBuffer;
size_t length = 0;
bool overflow = false;
// The request line goes directly into the main buffer, which supports long
// query strings (up to headerBufferSize). One that does not fit is rejected
// rather than truncated, after its headers are read: closing with unread
// input makes TCP reset the connection, which can discard the reply.
if (!readRequestLine(localClient, buffer, headerBufferSize - HEADER_BUFFER_RESERVED_BYTES, length, overflow,
timeoutStart)) {
OTF_DEBUG(F("Timed out reading the request line\n"));
localClient->print(F("HTTP/1.1 408 Request Timeout\r\nConnection: close\r\n\r\nIncomplete request"));
closeCurrentClient();
return true;
}
const bool requestLineTooLong = overflow;
if (requestLineTooLong) length = 0;
else buffer[length++] = '\n';
// Header lines: keep only the ones the application uses, to save RAM.
for (;;) {
char line[128];
size_t lineLen = 0;
if (!readRequestLine(localClient, line, sizeof(line), lineLen, overflow, timeoutStart)) {
OTF_DEBUG(F("Timed out reading request headers\n"));
localClient->print(F("HTTP/1.1 408 Request Timeout\r\nConnection: close\r\n\r\nIncomplete request headers"));
closeCurrentClient();
return true;
}
// An empty line ends the headers.
if (lineLen == 0 || (lineLen == 1 && line[0] == '\r')) break;
// Longer than any header we keep (e.g. a long User-Agent): already consumed, skip it.
if (overflow) continue;
if (!requestLineTooLong && isKeptHeader(line, lineLen) && length + lineLen + 1 < headerBufferSize - 4) {
memcpy(&buffer[length], line, lineLen);
length += lineLen;
buffer[length++] = '\n';
}
}
if (requestLineTooLong) {
OTF_DEBUG(F("Request line exceeds the header buffer\n"));
localClient->print(F("HTTP/1.1 414 URI Too Long\r\nConnection: close\r\n\r\nThe request line is too long"));
closeCurrentClient();
return true;
}
// Standardize end of headers with \r\n\r\n for the Request parser
// (Ensuring we have at least one \r\n before the final one)
if (length > 0 && buffer[length-1] == '\n') {
if (length > 1 && buffer[length-2] != '\r') {
buffer[length-1] = '\r';
buffer[length++] = '\n';
}
}
buffer[length++] = '\r';
buffer[length++] = '\n';
buffer[length] = 0;
OTF_DEBUG((char *) F("Finished reading selective data from client. Stored headers size: %zu bytes\n"), length);
OTF_DEBUG(F("Parsing request"));
Request request(buffer, length, false);
char *bodyBuffer = NULL;
// If the request was valid, read the body and add it to the Request object.
if (request.getType() > INVALID) {
char *contentLengthString = request.getHeader(F("content-length"));
// If the header was not specified, the message has no body.
if (contentLengthString != nullptr) {
size_t contentLength = 0;
ContentLengthResult lengthResult =
parseContentLength(contentLengthString, OTF_MAX_BODY_SIZE, contentLength);
if (lengthResult == CONTENT_LENGTH_INVALID) {
OTF_DEBUG(F("Invalid Content-Length\n"));
localClient->print(F("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\nInvalid Content-Length"));
closeCurrentClient();
return true;
}
if (lengthResult == CONTENT_LENGTH_TOO_LARGE) {
OTF_DEBUG(F("Content-Length exceeds OTF_MAX_BODY_SIZE\n"));
localClient->print(F("HTTP/1.1 413 Payload Too Large\r\nConnection: close\r\n\r\nThe request body exceeds the configured limit"));
closeCurrentClient();
return true;
}
if (contentLength > 0) {
// Read the body from the client.
bodyBuffer = new (std::nothrow) char[contentLength + 1];
if (bodyBuffer == nullptr) {
OTF_DEBUG(F("Could not allocate request body buffer\n"));
localClient->print(F("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\nInsufficient memory"));
closeCurrentClient();
return true;
}
size_t bodyLength = 0;
timeoutStart = millis();
while (bodyLength < contentLength &&
millis() - timeoutStart < WIFI_CONNECTION_TIMEOUT) {
size_t available = localClient->availableBytes();
if (available == 0) {
waitForRequestData();
continue;
}
size_t size =
#if defined(ARDUINO)
min
#else
std::min
#endif
(contentLength - bodyLength, (size_t)1024);
size =
#if defined(ARDUINO)
min
#else
std::min
#endif
(size, available);
size_t read = localClient->readBytes(&bodyBuffer[bodyLength], size);
if (read == 0) {
waitForRequestData();
continue;
}
bodyLength += read;
}
if (bodyLength != contentLength) {
delete[] bodyBuffer;
bodyBuffer = nullptr;
OTF_DEBUG(F("Timed out before receiving the complete request body\n"));
localClient->print(F("HTTP/1.1 408 Request Timeout\r\nConnection: close\r\n\r\nIncomplete request body"));
closeCurrentClient();
return true;
}
bodyBuffer[bodyLength] = 0;
request.body = bodyBuffer;
request.bodyLength = bodyLength;
}
}
}
// Make response stream to client
Response res = Response();
res.enableStream([this](const char *buffer, size_t length, bool first_message) -> void {
localClient->write(buffer, length);
}, [this]() -> void {
localClient->flush();
}, [this]() -> void {
localClient->flush();
});
fillResponse(request, res);
// Make sure to end the stream if it was enabled.
res.end();
if(bodyBuffer) delete[] bodyBuffer;
if (res.isValid()) {
OTF_DEBUG("Sent response, %d bytes\n", res.getTotalLength());
} else {
localClient->print(F("HTTP/1.1 500 OTF error\r\nResponse string could not be built\r\n"));
OTF_DEBUG(F("An error occurred while building the response string.\n"));
}
// Properly close the client connection.
localClient->flush();
localClient->stop();
// Get a new client to indicate that the previous client is no longer needed.
localClient = localServer.acceptClient();
if (localClient) {
OTF_DEBUG(F("Accepted new client\n"));
wait_to = millis()+WIFI_CONNECTION_TIMEOUT;
}
OTF_DEBUG(F("Finished handling request\n"));
return true;
}
void OpenThingsFramework::loop(bool allowCloud) {
if (processingCloud) return;
bool localClientActive = localServerLoop();
if (!localClientActive && allowCloud && webSocket != nullptr) {
webSocket->poll();
#if defined(ARDUINO)
if (pendingCloudData && !closeCloud) {
uint8_t *data = pendingCloudData;
size_t length = pendingCloudLength;
uint32_t generation = pendingCloudGeneration;
pendingCloudData = nullptr;
pendingCloudLength = 0;
if (generation == cloudGeneration && cloudStatus == CONNECTED) {
processingCloud = true;
handleCloudMessage(data, length);
processingCloud = false;
}
free(data);
}
#endif
if (closeCloud) {
#if defined(ARDUINO)
clearPendingCloudRequest();
#endif
closeCloud = false;
webSocket->close(true);
}
}
}
#if defined(ARDUINO)
void OpenThingsFramework::clearPendingCloudRequest() {
free(pendingCloudData);
pendingCloudData = nullptr;
pendingCloudLength = 0;
}
#endif
void OpenThingsFramework::webSocketEventCallback(WSEvent_t type, uint8_t *payload, size_t length) {
switch (type) {
case WSEvent_DISCONNECTED: {
++cloudGeneration;
closeCloud = false;
#if defined(ARDUINO)
clearPendingCloudRequest();
#endif
OTF_DEBUG(F("Websocket connection closed\n"));
if (cloudStatus == CONNECTED) {
// Make sure the cloud status is only set to disconnected if it was previously connected.
setCloudStatus(DISCONNECTED);
}
// Clear any in-progress stream state — a disconnect during a response
// would otherwise leave isStreaming stuck true and break subsequent
// streams after reconnect.
this->webSocket->resetStreaming();
break;
}
case WSEvent_CONNECTED: {
++cloudGeneration;
closeCloud = false;
#if defined(ARDUINO)
clearPendingCloudRequest();
#endif
OTF_DEBUG(F("Websocket connection opened\n"));
setCloudStatus(CONNECTED);
this->webSocket->resetStreaming();
break;
}
case WSEvent_PING: {
OTF_DEBUG(F("Received a ping from the server\n"));
break;
}
case WSEvent_PONG: {
OTF_DEBUG(F("Received a pong from the server\n"));
break;
}
case WSEvent_TEXT: {
if (closeCloud || !validateForwardedRequest(payload, length)) break;
#if defined(ARDUINO)
if (webSocket->isStreamOpen()) {
closeCloud = true;
break;
}
// arduinoWebSockets delivers one frame per poll. Never run a handler
// beneath its recursive parser, even if the temporary copy cannot fit.
if (pendingCloudData || length > WEBSOCKETS_MAX_DATA_SIZE) {
sendCloudError(reinterpret_cast<const char *>(payload) + sizeof("FWD: ") - 1, 503);
break;
}
pendingCloudData = static_cast<uint8_t *>(malloc(length + 1));
if (!pendingCloudData) {
sendCloudError(reinterpret_cast<const char *>(payload) + sizeof("FWD: ") - 1, 503);
break;
}
memcpy(pendingCloudData, payload, length);
pendingCloudData[length] = '\0';
pendingCloudLength = length;
pendingCloudGeneration = cloudGeneration;
#else
processingCloud = true;
handleCloudMessage(payload, length);
processingCloud = false;
#endif
break;
}
default: {
OTF_DEBUG((char *) F("Received unsupported websocket event of type %d\n"), type);
break;
}
}
}
void OpenThingsFramework::sendCloudError(const char *requestId, uint16_t status) {
if (closeCloud || cloudStatus != CONNECTED) return;
#if defined(ARDUINO)
if (webSocket->isStreamOpen()) {
closeCloud = true;
return;
}
#endif
char message[96];
uint32_t generation = cloudGeneration;
int length = snprintf(message, sizeof(message),
"RES: %.4s\r\nHTTP/1.1 %s\r\nContent-Length: 0\r\n\r\n",
requestId, status == 503 ? "503 Service Unavailable" : "500 Internal Server Error");
if (length <= 0 || static_cast<size_t>(length) >= sizeof(message) ||
!webSocket->send(message, static_cast<size_t>(length))) {
if (generation == cloudGeneration) closeCloud = true;
}
}
void OpenThingsFramework::handleCloudMessage(uint8_t *payload, size_t length) {
ForwardedRequest forwarded;
if (!parseForwardedRequest(payload, length, forwarded)) return;
struct {
uint32_t generation;
bool started;
bool failed;
} state = {cloudGeneration, false, false};
Request request(forwarded.requestData, forwarded.requestLength, true);
Response res;
res.enableStream([this, &state](const char *buffer, size_t size, bool first) {
if (state.failed || state.generation != cloudGeneration || cloudStatus != CONNECTED) return;
state.started = true;
#if defined(ARDUINO)
if (first && !webSocket->stream()) {
state.failed = true;
if (state.generation == cloudGeneration) closeCloud = true;
return;
}
#else
// Keep TinyWebsockets' existing inline stream behavior on Linux.
if (first) webSocket->stream();
#endif
// Starting a stream can yield and report a connection change.
if (state.generation != cloudGeneration || cloudStatus != CONNECTED) return;
if (!webSocket->send(buffer, size)) {
#if defined(ARDUINO)
state.failed = true;
if (state.generation == cloudGeneration) closeCloud = true;
#endif
}
}, [this, &state]() {
if (!state.failed && state.generation == cloudGeneration && cloudStatus == CONNECTED &&
!webSocket->send("", 0)) {
#if defined(ARDUINO)
state.failed = true;
if (state.generation == cloudGeneration) closeCloud = true;
#endif
}
}, [this, &state]() {
#if defined(ARDUINO)
if (!state.failed && state.generation == cloudGeneration && cloudStatus == CONNECTED &&
webSocket->isStreamOpen() && !webSocket->end()) {
state.failed = true;
if (state.generation == cloudGeneration) closeCloud = true;
}
#else
if (state.generation == cloudGeneration && cloudStatus == CONNECTED) webSocket->end();
#endif
});
res.bprintf(F("RES: %s\r\n"), forwarded.requestId);
fillResponse(request, res);
if (state.generation != cloudGeneration || cloudStatus != CONNECTED) return;
if (!res.isValid()) {
// end() flushes even invalid buffers. Do not send corrupt data, or a
// second response after streaming has already started.
if (!state.started) sendCloudError(forwarded.requestId, 500);
#if defined(ARDUINO)
else closeCloud = true;
#else
else webSocket->end();
#endif
return;
}
res.end();
}
void OpenThingsFramework::fillResponse(const Request &req, Response &res) {
if (req.getType() == INVALID) {
res.writeStatus(400, F("Invalid request"));
res.writeHeader(F("content-type"), F("text/plain"));
res.writeBodyChunk(F("Could not parse request"));
return;
}
// TODO handle trailing slash in path?
OTF_DEBUG((char *) F("Attempting to route request to path '%s'\n"), req.getPath());
// Stack buffer for lookup keys — registered route keys are short
// (OS firmware's longest is ~5 chars including method digit + null).
// If the formatted key would not fit, the lookup is skipped — a request
// path longer than this cap falls through to missingPageCallback rather
// than risk a misroute via a truncated key.
char lookupKey[64];
callback_t callback = nullptr;
int n = snprintf(lookupKey, sizeof(lookupKey), "%d%s", (int)req.httpMethod, req.getPath());
if (n > 0 && (size_t)n < sizeof(lookupKey)) {
callback = callbacks.find(lookupKey);
}
// If there isn't a callback for the specific method, check if there's one for any method.
if (callback == nullptr) {
n = snprintf(lookupKey, sizeof(lookupKey), "%d%s", (int)HTTP_ANY, req.getPath());
if (n > 0 && (size_t)n < sizeof(lookupKey)) {
callback = callbacks.find(lookupKey);
}
}
OTF_DEBUG((char *) F("callback=%x\n"), callback);
if (callback != nullptr) {
OTF_DEBUG(F("Found callback\n"));
callback(req, res);
} else {
// Run the missing page callback if none of the registered paths matched.
missingPageCallback(req, res);
}
}
void OpenThingsFramework::defaultMissingPageCallback(const Request &req, Response &res) {
res.writeStatus(404, F("Not found"));
res.writeHeader(F("content-type"), F("text/plain"));
res.writeBodyChunk(F("The requested page does not exist"));
}
void OpenThingsFramework::setCloudStatus(CLOUD_STATUS status) {
this->cloudStatus = status;
lastCloudStatusChangeTime = millis();
}
CLOUD_STATUS OpenThingsFramework::getCloudStatus() {
return cloudStatus;
}
uint32_t OpenThingsFramework::getTimeSinceLastCloudStatusChange() {
return millis() - lastCloudStatusChangeTime;
}
#ifdef OTF_SECURE_CLOUD
bool OTF::OpenThingsFramework::pauseCloud() {
if(processingCloud)return false;
if(webSocket && !webSocket->pauseTransport())return false;
++cloudGeneration;
clearPendingCloudRequest();
closeCloud=false;
return true;
}
bool OTF::OpenThingsFramework::cloudTransportActive() const {
return webSocket && webSocket->transportActive();
}
#endif