-
Notifications
You must be signed in to change notification settings - Fork 1
/
http_utils.cpp
610 lines (539 loc) · 18.3 KB
/
http_utils.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
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
/**
* @file http_utils.cpp
* @brief HTTP utility functions and configurations
*
* This file contains utility functions for handling HTTP requests,
* managing HTTP configurations, and processing HTTP responses.
*/
#include "http_utils.h"
#include "led.h"
#include "uart_utils.h"
#include <HTTPClient.h>
#include <WiFi.h>
/// Maximum content length for HTTP responses
const int MAX_CONTENT_LENGTH = 512 * 1024;
/**
* @struct HttpCallConfig
* @brief Configuration for HTTP calls
*/
struct HttpCallConfig {
String method; ///< HTTP method
String implementation; ///< Implementation type (e.g., "CALL" or "STREAM")
String url; ///< URL for the HTTP request
std::vector<std::pair<String, String>> headers; ///< HTTP headers
String payload; ///< Request payload
bool showResponseHeaders; ///< Flag to show response headers
void reset() { ///< Reset the configuration
method = "";
url = "";
implementation = "CALL";
headers.clear();
payload = "";
showResponseHeaders = false;
}
void removeHeader(String name) { ///< Remove a specific header
headers.erase(std::remove_if(headers.begin(), headers.end(),
[&](const std::pair<String, String> &header) {
return header.first == name;
}),
headers.end());
}
};
/// Global HTTP call configuration
HttpCallConfig httpCallConfig;
/**
* @brief Print response to UART or UDP packet
* @param response The response string to print
* @param packet Pointer to AsyncUDPPacket, can be null for UART output
*/
void printResponse(String response, AsyncUDPPacket *packet) {
if (response.isEmpty()) {
response = "empty";
}
if (packet) {
packet->printf("%s", response.c_str());
} else {
UART0.println(response);
}
}
/**
* @brief Set flag to show response headers
* @param show Boolean flag to show or hide headers
* @param packet Pointer to AsyncUDPPacket for response
*/
void setShowResponseHeaders(bool show, AsyncUDPPacket *packet) {
httpCallConfig.showResponseHeaders = show;
printResponse("HTTP_BUILDER_SHOW_RESPONSE_HEADERS: " +
String(show ? "true" : "false"),
packet);
}
/**
* @brief Get and print current HTTP builder configuration
* @param packet Pointer to AsyncUDPPacket for response
*/
void getHttpBuilderConfig(AsyncUDPPacket *packet) {
printResponse("HTTP_BUILDER_CONFIG: ", packet);
printResponse("HTTP_METHOD: " + httpCallConfig.method, packet);
printResponse("HTTP_URL: " + httpCallConfig.url, packet);
printResponse("HTTP_PAYLOAD: " + httpCallConfig.payload, packet);
printResponse("HTTP_IMPLEMENTATION: " + httpCallConfig.implementation,
packet);
printResponse("HTTP_HEADERS: ", packet);
for (const auto &header : httpCallConfig.headers) {
printResponse(header.first + ": " + header.second, packet);
}
}
/**
* @brief Set HTTP method for the request
* @param method HTTP method string
* @param packet Pointer to AsyncUDPPacket for response
*/
void setHttpMethod(String method, AsyncUDPPacket *packet) {
if (method != "GET" && method != "POST" && method != "PATCH" &&
method != "PUT" && method != "DELETE" && method != "HEAD") {
printResponse("HTTP_ERROR: Invalid HTTP method. Supported methods: GET, "
"POST, PATCH, PUT, DELETE, HEAD",
packet);
return;
}
httpCallConfig.method = method;
printResponse("HTTP_SET_METHOD: " + method, packet);
}
/**
* @brief Set URL for the HTTP request
* @param url URL string
* @param packet Pointer to AsyncUDPPacket for response
*/
void setHttpUrl(String url, AsyncUDPPacket *packet) {
httpCallConfig.url = ensureHttpsPrefix(url);
printResponse("HTTP_URL: " + httpCallConfig.url, packet);
}
/**
* @brief Add an HTTP header to the configuration
* @param header Header string in "name:value" format
* @param packet Pointer to AsyncUDPPacket for response
*/
void addHttpHeader(String header, AsyncUDPPacket *packet) {
int separatorIndex = header.indexOf(':');
if (separatorIndex != -1) {
String name = header.substring(0, separatorIndex);
String value = header.substring(separatorIndex + 1);
httpCallConfig.headers.push_back(std::make_pair(name, value));
printResponse("HTTP_ADD_HEADER: " + name + ": " + value, packet);
} else {
printResponse("HTTP_ERROR: Invalid header format, use HEADER name:value",
packet);
}
}
/**
* @brief Remove an HTTP header from the configuration
* @param name Name of the header to remove
* @param packet Pointer to AsyncUDPPacket for response
*/
void removeHttpHeader(String name, AsyncUDPPacket *packet) {
httpCallConfig.removeHeader(name);
printResponse("HTTP_REMOVE_HEADER: " + name, packet);
}
/**
* @brief Reset the HTTP configuration to default values
* @param packet Pointer to AsyncUDPPacket for response
*/
void resetHttpConfig(AsyncUDPPacket *packet) {
httpCallConfig.reset();
printResponse("HTTP_CONFIG_REST: All configurations reset", packet);
}
/**
* @brief Set the payload for the HTTP request
* @param payload Payload string
* @param packet Pointer to AsyncUDPPacket for response
*/
void setHttpPayload(String payload, AsyncUDPPacket *packet) {
httpCallConfig.payload = payload;
printResponse("HTTP_SET_PAYLOAD: " + payload, packet);
}
/**
* @brief Set the implementation type for HTTP requests
* @param implementation Implementation type string
* @param packet Pointer to AsyncUDPPacket for response
*/
void setHttpImplementation(String implementation, AsyncUDPPacket *packet) {
httpCallConfig.implementation = implementation;
printResponse("HTTP_SET_IMPLEMENTATION: " + implementation, packet);
}
/**
* @brief Get the content length of a resource at the given URL
* @param url URL to check
* @return int Content length or -1 if error
*/
int getContentLength(String url) {
HTTPClient http;
http.begin(url);
int httpResponseCode = http.sendRequest("HEAD");
if (httpResponseCode > 0) {
int contentLength = http.getSize();
http.end();
return contentLength;
} else {
http.end();
return -1; // Indicate an error
}
}
/**
* @brief Handle streaming HTTP response
* @param http HTTPClient object
* @param packet Pointer to AsyncUDPPacket for response
*/
void handleStreamResponse(HTTPClient &http, AsyncUDPPacket *packet) {
int len = http.getSize();
const size_t bufferSize = 512; // Buffer size for reading data
uint8_t buff[bufferSize + 1] = {0}; // Buffer with space for null-terminator
NetworkClient *stream = http.getStreamPtr();
printResponse("STREAM: ", packet);
while (http.connected() && (len > 0 || len == -1) ) {
size_t size = stream->available();
if (size) {
int c = stream->readBytes(buff, min(size, bufferSize - 1)); // Adjust for null terminator
buff[c] = '\0'; // Null-terminate the buffer
if (packet) {
packet->write(buff, c);
} else {
UART0.write(buff, c);
}
if (len > 0) {
len -= c;
}
}
delay(1); // Yield control to the system
}
printResponse("\nSTREAM_END", packet);
}
/**
* @brief Handle file streaming HTTP response
* @param http HTTPClient object
* @param packet Pointer to AsyncUDPPacket for response
*/
void handleFileStreamResponse(HTTPClient &http, AsyncUDPPacket *packet) {
int len = http.getSize();
uint8_t buff[512] = {0};
NetworkClient *stream = http.getStreamPtr();
while (http.connected() && (len > 0 || len == -1)) {
size_t size = stream->available();
if (size) {
int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));
UART0.write(buff, c);
if (len > 0) {
len -= c;
}
}
delay(1); // Yield control to the system
}
}
/**
* @brief Handle HTTP response as a string
* @param http HTTPClient object
* @param packet Pointer to AsyncUDPPacket for response
*/
void handleGetStringResponse(HTTPClient &http, AsyncUDPPacket *packet) {
// Check available heap memory
size_t freeHeap = ESP.getFreeHeap();
const size_t minHeapThreshold = 1024; // Minimum heap space to avoid overflow
if (freeHeap < minHeapThreshold) {
printResponse("WIFI_ERROR: Not enough memory to process the response.",
packet);
return;
}
String payload = http.getString();
if (payload.isEmpty()) {
payload = "empty";
}
// Check again after getting the payload
freeHeap = ESP.getFreeHeap();
if (freeHeap < minHeapThreshold) {
printResponse("WIFI_ERROR: Not enough memory to process the full response.",
packet);
return;
}
printResponse("RESPONSE:", packet);
printResponse(payload, packet);
printResponse("RESPONSE_END", packet);
}
/**
* @brief Make an HTTP GET request
* @param url URL for the request
* @param packet Pointer to AsyncUDPPacket for response
*/
void makeHttpRequest(String url, AsyncUDPPacket *packet) {
if (WiFi.status() == WL_CONNECTED) {
int contentLength = getContentLength(url);
if (contentLength > MAX_CONTENT_LENGTH) {
String warnMsg = "WARNING: Content of " + String(contentLength) +
" exceeds maximum length of " +
String(MAX_CONTENT_LENGTH) +
" bytes for simple calls. Using stream, if"
"the blue light stays on, reset the board.";
printResponse(warnMsg, packet);
}
if (contentLength == -1) {
String warnMsg =
"WARNING: Content-Length is unknown (-1). These calls tend to crash "
"to board. If the blue light stays on, reset the board.";
printResponse(warnMsg, packet);
}
HTTPClient http;
led_set_blue(255);
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = "STATUS: " + String(httpResponseCode) + "\n";
printResponse(response, packet);
if (contentLength == -1 || contentLength > MAX_CONTENT_LENGTH) {
handleStreamResponse(http, packet);
} else {
handleGetStringResponse(http, packet);
}
} else {
String errorMsg = "HTTP_ERROR: " + getHttpErrorMessage(httpResponseCode);
printResponse(errorMsg, packet);
}
http.end();
led_set_blue(0);
} else {
led_set_blue(0);
led_error();
String errorMsg = "HTTP_ERROR: WiFi Disconnected";
printResponse(errorMsg, packet);
}
}
/**
* @brief Make an HTTP GET request for file streaming
* @param url URL for the request
* @param packet Pointer to AsyncUDPPacket for response
*/
void makeHttpFileRequest(String url, AsyncUDPPacket *packet) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
led_set_blue(255);
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
handleFileStreamResponse(http, packet);
}
http.end();
led_set_blue(0);
}
}
/**
* @brief Make an HTTP GET request with streaming response
* @param url URL for the request
* @param packet Pointer to AsyncUDPPacket for response
*/
void makeHttpRequestStream(String url, AsyncUDPPacket *packet) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
led_set_blue(255);
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http.begin(url);
int contentLength = getContentLength(url);
if (contentLength > MAX_CONTENT_LENGTH) {
String warnMsg = "WARNING: Content of " + String(contentLength) +
" exceeds maximum length for stream of." +
String(MAX_CONTENT_LENGTH) +
" bytes. If"
"the blue light stays on,"
"reset the board.";
printResponse(warnMsg, packet);
}
if (contentLength == -1) {
String warnMsg =
"WARNING: Content-Length is unknown (-1). These calls tend to crash "
"to board. If the blue light stays on, reset the board.";
printResponse(warnMsg, packet);
}
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = "STATUS: " + String(httpResponseCode) + "\n";
printResponse(response, packet);
handleStreamResponse(http, packet);
} else {
String errorMsg =
"HTTP_ERROR: " + HTTPClient::errorToString(httpResponseCode) +
" (Code: " + String(httpResponseCode) + ")";
printResponse(errorMsg, packet);
}
http.end();
led_set_blue(0);
} else {
String errorMsg = "HTTP_ERROR: WiFi Disconnected";
printResponse(errorMsg, packet);
led_set_blue(0);
led_error();
}
}
/**
* @brief Make an HTTP POST request
* @param url URL for the request
* @param jsonPayload JSON payload for the request
* @param packet Pointer to AsyncUDPPacket for response
*/
void makeHttpPostRequest(String url, String jsonPayload,
AsyncUDPPacket *packet) {
if (WiFi.status() == WL_CONNECTED) {
led_set_blue(255);
HTTPClient http;
http.begin(url);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(jsonPayload);
if (httpResponseCode > 0) {
String response = "STATUS: " + String(httpResponseCode) + "\n";
printResponse(response, packet);
handleGetStringResponse(http, packet);
} else {
String errorMsg = "HTTP_ERROR: " + getHttpErrorMessage(httpResponseCode);
printResponse(errorMsg, packet);
led_set_blue(0);
led_error();
}
http.end();
led_set_blue(0);
} else {
String errorMsg = "HTTP_ERROR: WiFi Disconnected";
printResponse(errorMsg, packet);
led_set_blue(0);
led_error();
}
}
/**
* @brief Make an HTTP POST request for file streaming
* @param url URL for the request
* @param jsonPayload JSON payload for the request
* @param packet Pointer to AsyncUDPPacket for response
*/
void makeHttpPostFileRequest(String url, String jsonPayload, AsyncUDPPacket *packet) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
led_set_blue(255);
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http.begin(url);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(jsonPayload);
if (httpResponseCode > 0) {
handleFileStreamResponse(http, packet);
}
http.end();
led_set_blue(0);
}
}
/**
* @brief Execute an HTTP call based on the current configuration
* @param packet Pointer to AsyncUDPPacket for response
*/
void executeHttpCall(AsyncUDPPacket *packet) {
if (httpCallConfig.url.isEmpty() || httpCallConfig.method.isEmpty()) {
String errorMsg = "HTTP URL or Method not set";
printResponse(errorMsg, packet);
return;
}
if (WiFi.status() == WL_CONNECTED) {
led_set_blue(255);
HTTPClient http;
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http.begin(httpCallConfig.url);
for (const auto &header : httpCallConfig.headers) {
http.addHeader(header.first, header.second);
}
// Collect common headers
const char *headerKeys[] = {"Content-Type", "Content-Length", "Connection",
"Date", "Server"};
size_t headerKeysCount = sizeof(headerKeys) / sizeof(headerKeys[0]);
http.collectHeaders(headerKeys, headerKeysCount);
String response;
int httpResponseCode;
if (httpCallConfig.method == "GET") {
httpResponseCode = http.GET();
} else if (httpCallConfig.method == "POST") {
httpResponseCode = http.POST(httpCallConfig.payload);
} else if (httpCallConfig.method == "PATCH") {
httpResponseCode = http.PATCH(httpCallConfig.payload);
} else if (httpCallConfig.method == "PUT") {
httpResponseCode = http.PUT(httpCallConfig.payload);
} else if (httpCallConfig.method == "DELETE") {
httpResponseCode = http.sendRequest("DELETE", httpCallConfig.payload);
} else if (httpCallConfig.method == "HEAD") {
httpResponseCode = http.sendRequest("HEAD");
} else {
String errorMsg = "Unsupported HTTP method: " + httpCallConfig.method;
printResponse(errorMsg, packet);
http.end();
led_set_blue(0);
return;
}
if (httpResponseCode > 0) {
response = "STATUS: " + String(httpResponseCode) + "\n";
printResponse(response, packet);
if (httpCallConfig.showResponseHeaders) {
printResponse("HEADERS:", packet);
// Get the header count
int headerCount = http.headers();
// Iterate over the collected headers and print them
for (int i = 0; i < headerCount; i++) {
String headerName = http.headerName(i);
String headerValue = http.header(i);
printResponse(headerName + ": " + headerValue, packet);
}
}
if (httpCallConfig.implementation == "STREAM") {
handleStreamResponse(http, packet);
} else {
handleGetStringResponse(http, packet);
}
} else {
String errorMsg = "HTTP_ERROR: " + getHttpErrorMessage(httpResponseCode);
printResponse(errorMsg, packet);
led_set_blue(0);
led_error();
}
http.end();
response = "";
led_set_blue(0);
} else {
String errorMsg = "HTTP_ERROR: WiFi Disconnected";
led_set_blue(0);
led_error();
printResponse(errorMsg, packet);
}
}
/**
* @brief Get a human-readable error message for HTTP error codes
* @param httpCode HTTP error code
* @return String Error message
*/
String getHttpErrorMessage(int httpCode) {
switch (httpCode) {
case HTTPC_ERROR_CONNECTION_REFUSED:
return "Connection refused";
case HTTPC_ERROR_SEND_HEADER_FAILED:
return "Send header failed";
case HTTPC_ERROR_SEND_PAYLOAD_FAILED:
return "Send payload failed";
case HTTPC_ERROR_NOT_CONNECTED:
return "Not connected";
case HTTPC_ERROR_CONNECTION_LOST:
return "Connection lost";
case HTTPC_ERROR_NO_STREAM:
return "No stream";
case HTTPC_ERROR_NO_HTTP_SERVER:
return "No HTTP server";
case HTTPC_ERROR_TOO_LESS_RAM:
return "Not enough RAM";
case HTTPC_ERROR_ENCODING:
return "Transfer encoding error";
case HTTPC_ERROR_STREAM_WRITE:
return "Stream write error";
case HTTPC_ERROR_READ_TIMEOUT:
return "Connection timeout";
default:
return "Unknown error: " + String(httpCode);
}
}