/
Web.cpp
1656 lines (1465 loc) · 58.1 KB
/
Web.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
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <Arduino.h>
#include <WiFi.h>
#include <Update.h>
#include <nvsDump.h>
#include <esp_task_wdt.h>
#include "soc/timer_group_struct.h"
#include "soc/timer_group_reg.h"
#include "freertos/ringbuf.h"
#include "ESPAsyncWebServer.h"
#include "AsyncJson.h"
#include "ArduinoJson.h"
#include "settings.h"
#include "AudioPlayer.h"
#include "Battery.h"
#include "Cmd.h"
#include "Common.h"
#include "Ftp.h"
#include "Led.h"
#include "Log.h"
#include "MemX.h"
#include "Mqtt.h"
#include "Rfid.h"
#include "SdCard.h"
#include "System.h"
#include "Web.h"
#include "Wlan.h"
#include "revision.h"
#include "Rfid.h"
#include "HallEffectSensor.h"
#include "HTMLaccesspoint.h"
#include "HTMLmanagement.h"
#include "HTMLbinary.h"
typedef struct {
char nvsKey[13];
char nvsEntry[275];
} nvs_t;
AsyncWebServer wServer(80);
AsyncWebSocket ws("/ws");
AsyncEventSource events("/events");
static bool webserverStarted = false;
static const uint32_t chunk_size = 16384; // bigger chunks increase write-performance to SD-Card
static const uint32_t nr_of_buffers = 2; // at least two buffers. No speed improvement yet with more than two.
uint8_t buffer[nr_of_buffers][chunk_size];
volatile uint32_t size_in_buffer[nr_of_buffers];
volatile bool buffer_full[nr_of_buffers];
uint32_t index_buffer_write = 0;
uint32_t index_buffer_read = 0;
static QueueHandle_t explorerFileUploadStatusQueue;
static TaskHandle_t fileStorageTaskHandle;
void Web_DumpSdToNvs(const char *_filename);
static void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final);
static void explorerHandleFileUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final);
static void explorerHandleFileStorageTask(void *parameter);
static void explorerHandleListRequest(AsyncWebServerRequest *request);
static void explorerHandleDownloadRequest(AsyncWebServerRequest *request);
static void explorerHandleDeleteRequest(AsyncWebServerRequest *request);
static void explorerHandleCreateRequest(AsyncWebServerRequest *request);
static void explorerHandleRenameRequest(AsyncWebServerRequest *request);
static void explorerHandleAudioRequest(AsyncWebServerRequest *request);
static void handleGetSavedSSIDs(AsyncWebServerRequest *request);
static void handlePostSavedSSIDs(AsyncWebServerRequest *request, JsonVariant &json);
static void handleDeleteSavedSSIDs(AsyncWebServerRequest *request);
static void handleGetActiveSSID(AsyncWebServerRequest *request);
static void handleGetWiFiConfig(AsyncWebServerRequest *request);
static void handlePostWiFiConfig(AsyncWebServerRequest *request, JsonVariant &json);
static void handleCoverImageRequest(AsyncWebServerRequest *request);
static void handleWiFiScanRequest(AsyncWebServerRequest *request);
static bool Web_DumpNvsToSd(const char *_namespace, const char *_destFile);
static void onWebsocketEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len);
static String templateProcessor(const String &templ);
static void webserverStart(void);
// If PSRAM is available use it allocate memory for JSON-objects
struct SpiRamAllocator {
void* allocate(size_t size) {
return ps_malloc(size);
}
void deallocate(void* pointer) {
free(pointer);
}
};
using SpiRamJsonDocument = BasicJsonDocument<SpiRamAllocator>;
static void serveProgmemFiles(const String& uri, const String& contentType, const uint8_t *content, size_t len) {
wServer.on(uri.c_str(), HTTP_GET, [contentType, content, len](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response;
// const bool etag = request->hasHeader("if-None-Match") && request->getHeader("if-None-Match")->value().equals(gitRevShort);
const bool etag = false;
if (etag)
response = request->beginResponse(304);
else {
response = request->beginResponse_P(200, contentType, content, len);
response->addHeader("Content-Encoding", "gzip");
}
// response->addHeader("Cache-Control", "public, max-age=31536000, immutable");
// response->addHeader("ETag", gitRevShort); // use git revision as digest
request->send(response);
});
}
class OneParamRewrite : public AsyncWebRewrite
{
protected:
String _urlPrefix;
int _paramIndex;
String _paramsBackup;
public:
OneParamRewrite(const char* from, const char* to)
: AsyncWebRewrite(from, to) {
_paramIndex = _from.indexOf('{');
if( _paramIndex >=0 && _from.endsWith("}")) {
_urlPrefix = _from.substring(0, _paramIndex);
int index = _params.indexOf('{');
if(index >= 0) {
_params = _params.substring(0, index);
}
} else {
_urlPrefix = _from;
}
_paramsBackup = _params;
}
bool match(AsyncWebServerRequest *request) override {
if(request->url().startsWith(_urlPrefix)) {
if(_paramIndex >= 0) {
_params = _paramsBackup + request->url().substring(_paramIndex);
} else {
_params = _paramsBackup;
}
return true;
} else {
return false;
}
}
};
// First request will return 0 results unless you start scan from somewhere else (loop/setup)
// Do not request more often than 3-5 seconds
static void handleWiFiScanRequest(AsyncWebServerRequest *request) {
String json = "[";
int n = WiFi.scanComplete();
if (n == -2) {
// -2 if scan not triggered
WiFi.scanNetworks(true, false, true, 120);
} else if(n) {
for (int i = 0; i < n; ++i) {
if (i > 9) {
break;
}
// calculate RSSI as quality in percent
int quality;
if (WiFi.RSSI(i) <= -100) {
quality = 0;
} else if (WiFi.RSSI(i) >= -50) {
quality = 100;
} else {
quality = 2 * (WiFi.RSSI(i) + 100);
}
if (i) json += ",";
json += "{";
json += "\"ssid\":\"" + WiFi.SSID(i) + "\"";
json += ",\"bssid\":\"" + WiFi.BSSIDstr(i) + "\"";
json += ",\"rssi\":" + String(WiFi.RSSI(i));
json += ",\"channel\":" + String(WiFi.channel(i));
json += ",\"secure\":" + String(WiFi.encryptionType(i));
json += ",\"quality\":"+ String(quality); // WiFi strength in percent
json += ",\"wico\":\"w" + String(int(round(map(quality, 0, 100, 1, 4)))) + "\""; // WiFi strength icon ("w1"-"w4")
json += ",\"pico\":\"" + String((WIFI_AUTH_OPEN == WiFi.encryptionType(i)) ? "" : "pw") + "\""; // auth icon ("p1" for secured)
json += "}";
}
WiFi.scanDelete();
if(WiFi.scanComplete() == -2) {
WiFi.scanNetworks(true, false, true, 120);
}
}
json += "]";
request->send(200, "application/json", json);
json = String();
}
void Web_Init(void) {
wServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response;
// const bool etag = request->hasHeader("if-None-Match") && request->getHeader("if-None-Match")->value().equals(gitRevShort);
const bool etag = false;
if (etag)
response = request->beginResponse(304);
else
response = request->beginResponse_P(200, "text/html", accesspoint_HTML);
// response->addHeader("Cache-Control", "public, max-age=31536000, immutable");
// response->addHeader("ETag", gitRevShort); // use git revision as digest
request->send(response);
});
wServer.onNotFound([](AsyncWebServerRequest *request) {
request->redirect("/");
});
WWWData::registerRoutes(serveProgmemFiles);
wServer.addHandler(new AsyncCallbackJsonWebHandler("/savedSSIDs", handlePostSavedSSIDs));
wServer.on("/wificonfig", HTTP_GET, handleGetWiFiConfig);
wServer.addHandler(new AsyncCallbackJsonWebHandler("/wificonfig", handlePostWiFiConfig));
wServer.on("/restart", HTTP_GET, [](AsyncWebServerRequest *request) {
String url = "http://" + Wlan_GetHostname() + ".local";
String html = "<!DOCTYPE html>";
#if (LANGUAGE == DE)
html += "Der ESPuino wird neu gestartet...<br>Management Website: ";
#else
html += "ESPuino is being restarted...<br>Management website: ";
#endif
html += "<a href=\"" + url + "\">" + url + "</a>";
html += "<script>async function tryRedirect() {try {var url = \"" + url + "\";const response = await fetch(url);window.location.href = url;} catch (error) {console.log(error);setTimeout(tryRedirect, 2000);}}tryRedirect();</script>";
request->send(200, "text/html", html);
Serial.flush();
ESP.restart();
});
wServer.on("/shutdown", HTTP_GET, [](AsyncWebServerRequest *request) {
#if (LANGUAGE == DE)
request->send(200, "text/html", "ESPuino wird ausgeschaltet...");
#else
request->send(200, "text/html", "ESPuino is being shutdown...");
#endif
System_RequestSleep();
});
wServer.on("/wifiscan", HTTP_GET, handleWiFiScanRequest);
// start a first WiFi scan (to get a WiFi list more quickly in webview)
WiFi.scanNetworks(true, false, true, 120);
// allow cors for local debug (https://github.com/me-no-dev/ESPAsyncWebServer/issues/1080)
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "Accept, Content-Type, Authorization");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
wServer.begin();
Log_Println(httpReady, LOGLEVEL_NOTICE);
}
void Web_Cyclic(void) {
webserverStart();
ws.cleanupClients();
}
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
}
void webserverStart(void) {
if (Wlan_IsConnected() && !webserverStarted) {
// attach AsyncWebSocket for Mgmt-Interface
ws.onEvent(onWebsocketEvent);
wServer.addHandler(&ws);
// attach AsyncEventSource
wServer.addHandler(&events);
// Default
wServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
AsyncWebServerResponse *response;
// const bool etag = request->hasHeader("if-None-Match") && request->getHeader("if-None-Match")->value().equals(gitRevShort);
const bool etag = false;
if (etag)
response = request->beginResponse(304);
else {
if (gFSystem.exists("/.html/index.htm"))
response = request->beginResponse(gFSystem, "/.html/index.htm", String(), false, templateProcessor);
else
response = request->beginResponse_P(200, "text/html", management_HTML, templateProcessor);
}
// response->addHeader("Cache-Control", "public, max-age=31536000, immutable");
// response->addHeader("ETag", gitRevShort); // use git revision as digest
request->send(response);
});
WWWData::registerRoutes(serveProgmemFiles);
// Log
wServer.on("/log", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(200, "text/plain; charset=utf-8", Log_GetRingBuffer());
});
// software/wifi/heap/psram-info
wServer.on(
"/info", HTTP_GET, [](AsyncWebServerRequest *request) {
char buffer[128];
String info = "ESPuino " + (String) softwareRevision;
info += "\nESPuino " + (String) gitRevision;
info += "\nArduino version: " + String(ESP_ARDUINO_VERSION_MAJOR) + '.' + String(ESP_ARDUINO_VERSION_MINOR) + '.' + String(ESP_ARDUINO_VERSION_PATCH);
info += "\nESP-IDF version: " + String(ESP.getSdkVersion());
#if (LANGUAGE == DE)
info += "\nFreier Heap: " + String(ESP.getFreeHeap()) + " Bytes";
info += "\nGroesster freier Heap-Block: " + String((uint32_t)heap_caps_get_largest_free_block(MALLOC_CAP_8BIT)) + " Bytes";
info += "\nFreier PSRAM: ";
info += (!psramInit()) ? "nicht verfuegbar" : String(ESP.getFreePsram());
if (Wlan_IsConnected()) {
IPAddress myIP = WiFi.localIP();
info += "\nAktuelle IP: " + String(myIP[0]) + '.' + String(myIP[1]) + '.' + String(myIP[2]) + '.' + String(myIP[3]);
info += "\nWLAN-Signalstaerke: " + String((int8_t)Wlan_GetRssi()) + " dBm";
}
#else
info += "\nFree heap: " + String(ESP.getFreeHeap()) + " bytes";
info += "\nLargest free heap-block: " + String((uint32_t)heap_caps_get_largest_free_block(MALLOC_CAP_8BIT)) + " bytes";
info += "\nFree PSRAM: ";
info += (!psramInit()) ? "not available" : String(ESP.getFreePsram());
if (Wlan_IsConnected()) {
IPAddress myIP = WiFi.localIP();
info += "\nCurrent IP: " + String(myIP[0]) + '.' + String(myIP[1]) + '.' + String(myIP[2]) + '.' + String(myIP[3]);
info += "\nWiFi signal-strength: " + String((int8_t)Wlan_GetRssi()) + " dBm";
}
#endif
#ifdef BATTERY_MEASURE_ENABLE
snprintf(buffer, sizeof(buffer), currentVoltageMsg, Battery_GetVoltage());
info += "\n" + String(buffer);
snprintf(buffer, sizeof(buffer), currentChargeMsg, Battery_EstimateLevel() * 100);
info += "\n" + String(buffer);
#endif
#ifdef HALLEFFECT_SENSOR_ENABLE
uint16_t sva = gHallEffectSensor.readSensorValueAverage(true);
int diff = sva-gHallEffectSensor.NullFieldValue();
snprintf(buffer, sizeof(buffer), "\nHallEffectSensor NullFieldValue:%d, actual:%d, diff:%d, LastWaitFor_State:%d (waited:%d ms)", gHallEffectSensor.NullFieldValue(), sva, diff, gHallEffectSensor.LastWaitForState(), gHallEffectSensor.LastWaitForStateMS());
info += buffer;
#endif
request->send_P(200, "text/plain", info.c_str());
});
// NVS-backup-upload
wServer.on(
"/upload", HTTP_POST, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/html", backupRecoveryWebsite);
},
handleUpload);
// OTA-upload
wServer.on(
"/update", HTTP_POST, [](AsyncWebServerRequest *request) {
#ifdef BOARD_HAS_16MB_FLASH_AND_OTA_SUPPORT
if (Update.hasError()) {
request->send(500, "text/plain", Update.errorString());
} else {
request->send(200, "text/html", restartWebsite);
}
#else
request->send(500, "text/html", otaNotSupportedWebsite);
#endif
}, [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
#ifndef BOARD_HAS_16MB_FLASH_AND_OTA_SUPPORT
Log_Println(otaNotSupported, LOGLEVEL_NOTICE);
return;
#endif
if (!index) {
// pause some tasks to get more free CPU time for the upload
vTaskSuspend(AudioTaskHandle);
Led_TaskPause();
Rfid_TaskPause();
Update.begin();
Log_Println(fwStart, LOGLEVEL_NOTICE);
}
Update.write(data, len);
Log_Print(".", LOGLEVEL_NOTICE, false);
if (final) {
Update.end(true);
// resume the paused tasks
Led_TaskResume();
vTaskResume(AudioTaskHandle);
Rfid_TaskResume();
Log_Println(fwEnd, LOGLEVEL_NOTICE);
if (Update.hasError()) {
Log_Println(Update.errorString(), LOGLEVEL_ERROR);
}
Serial.flush();
//ESP.restart(); // restart is done via webpage javascript
}
});
// ESP-restart
wServer.on("/restart", HTTP_POST, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/html", restartWebsite);
Serial.flush();
ESP.restart();
});
// ESP-shutdown
wServer.on("/shutdown", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/html", shutdownWebsite);
System_RequestSleep();
});
// ESP-shutdown
wServer.on("/rfidnvserase", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/html", eraseRfidNvsWeb);
Log_Println(eraseRfidNvs, LOGLEVEL_NOTICE);
gPrefsRfid.clear();
Web_DumpNvsToSd("rfidTags", backupFile);
});
// WiFi scan
wServer.on("/wifiscan", HTTP_GET, handleWiFiScanRequest);
// Fileexplorer (realtime)
wServer.on("/explorer", HTTP_GET, explorerHandleListRequest);
wServer.on(
"/explorer", HTTP_POST, [](AsyncWebServerRequest *request) {
request->send(200);
},
explorerHandleFileUpload);
wServer.on("/explorerdownload", HTTP_GET, explorerHandleDownloadRequest);
wServer.on("/explorer", HTTP_DELETE, explorerHandleDeleteRequest);
wServer.on("/explorer", HTTP_PUT, explorerHandleCreateRequest);
wServer.on("/explorer", HTTP_PATCH, explorerHandleRenameRequest);
wServer.on("/exploreraudio", HTTP_POST, explorerHandleAudioRequest);
wServer.on("/savedSSIDs", HTTP_GET, handleGetSavedSSIDs);
wServer.addHandler(new AsyncCallbackJsonWebHandler("/savedSSIDs", handlePostSavedSSIDs));
wServer.addRewrite(new OneParamRewrite("/savedSSIDs/{ssid}", "/savedSSIDs?ssid={ssid}") );
wServer.on("/savedSSIDs", HTTP_DELETE, handleDeleteSavedSSIDs);
wServer.on("/activeSSID", HTTP_GET, handleGetActiveSSID);
wServer.on("/wificonfig", HTTP_GET, handleGetWiFiConfig);
wServer.addHandler(new AsyncCallbackJsonWebHandler("/wificonfig", handlePostWiFiConfig));
// current cover image
wServer.on("/cover", HTTP_GET, handleCoverImageRequest);
// ESPuino logo
wServer.on("/logo", HTTP_GET, [](AsyncWebServerRequest *request) {
Log_Println("logo request", LOGLEVEL_DEBUG);
if (gFSystem.exists("/.html/logo.png")) {
request->send(gFSystem, "/.html/logo.png", "image/png");
return;
};
if (gFSystem.exists("/.html/logo.svg")) {
request->send(gFSystem, "/.html/logo.svg", "image/svg+xml");
return;
};
request->redirect("https://www.espuino.de/espuino/Espuino32.png");
});
// ESPuino favicon
wServer.on("/favicon", HTTP_GET, [](AsyncWebServerRequest *request) {
Log_Println("favicon request", LOGLEVEL_DEBUG);
if (gFSystem.exists("/.html/favicon.ico")) {
request->send(gFSystem, "/.html/favicon.png", "image/x-icon");
return;
};
request->redirect("https://espuino.de/espuino/favicon.ico");
});
// Init HallEffectSensor Value
#ifdef HALLEFFECT_SENSOR_ENABLE
wServer.on("/inithalleffectsensor", HTTP_GET, [](AsyncWebServerRequest *request) {
bool bres = gHallEffectSensor.saveActualFieldValue2NVS();
char buffer[128];
snprintf(buffer, sizeof(buffer), "WebRequest>HallEffectSensor FieldValue: %d => NVS, Status: %s", gHallEffectSensor.NullFieldValue(), bres ? "OK" : "ERROR");
Log_Println(buffer, LOGLEVEL_INFO);
request->send(200, "text/html", buffer);
});
#endif
wServer.onNotFound(notFound);
// allow cors for local debug
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
wServer.begin();
webserverStarted = true;
}
}
// Used for substitution of some variables/templates of html-files. Is called by webserver's template-engine
String templateProcessor(const String &templ) {
if (templ == "FTP_USER") {
return gPrefsSettings.getString("ftpuser", "-1");
} else if (templ == "FTP_PWD") {
return gPrefsSettings.getString("ftppassword", "-1");
} else if (templ == "FTP_USER_LENGTH") {
return String(ftpUserLength - 1);
} else if (templ == "FTP_PWD_LENGTH") {
return String(ftpPasswordLength - 1);
} else if (templ == "SHOW_FTP_TAB") { // Only show FTP-tab if FTP-support was compiled
#ifdef FTP_ENABLE
return "true";
#else
return "false";
#endif
} else if (templ == "SHOW_BLUETOOTH_TAB") { // Only show Bluetooth-tab if Bluetooth-support was compiled
#ifdef BLUETOOTH_ENABLE
return "true";
#else
return "false";
#endif
} else if (templ == "INIT_LED_BRIGHTNESS") {
return String(gPrefsSettings.getUChar("iLedBrightness", 0));
} else if (templ == "NIGHT_LED_BRIGHTNESS") {
return String(gPrefsSettings.getUChar("nLedBrightness", 0));
} else if (templ == "MAX_INACTIVITY") {
return String(gPrefsSettings.getUInt("mInactiviyT", 0));
} else if (templ == "INIT_VOLUME") {
return String(gPrefsSettings.getUInt("initVolume", 0));
} else if (templ == "CURRENT_VOLUME") {
return String(AudioPlayer_GetCurrentVolume());
} else if (templ == "MAX_VOLUME_SPEAKER") {
return String(gPrefsSettings.getUInt("maxVolumeSp", 0));
} else if (templ == "MAX_VOLUME_HEADPHONE") {
return String(gPrefsSettings.getUInt("maxVolumeHp", 0));
#ifdef BATTERY_MEASURE_ENABLE
#ifdef MEASURE_BATTERY_VOLTAGE
} else if (templ == "WARNING_LOW_VOLTAGE") {
return String(gPrefsSettings.getFloat("wLowVoltage", warningLowVoltage));
} else if (templ == "VOLTAGE_INDICATOR_LOW") {
return String(gPrefsSettings.getFloat("vIndicatorLow", voltageIndicatorLow));
} else if (templ == "VOLTAGE_INDICATOR_HIGH") {
return String(gPrefsSettings.getFloat("vIndicatorHigh", voltageIndicatorHigh));
#endif
#ifdef MEASURE_BATTERY_OTHER // placeholder
} else if (templ == "todo") {
return "todo";
#endif
} else if (templ == "BATTERY_CHECK_INTERVAL") {
return String(gPrefsSettings.getUInt("vCheckIntv", batteryCheckInterval));
#else
// TODO: hide battery config
#endif
} else if (templ == "MQTT_CLIENTID") {
if (gPrefsSettings.isKey("mqttClientId")) {
return gPrefsSettings.getString("mqttClientId", "-1");
} else {
return "-1";
}
} else if (templ == "MQTT_SERVER") {
if (gPrefsSettings.isKey("mqttServer")) {
return gPrefsSettings.getString("mqttServer", "-1");
} else {
return "-1";
}
} else if (templ == "SHOW_MQTT_TAB") { // Only show MQTT-tab if MQTT-support was compiled
#ifdef MQTT_ENABLE
return "true";
#else
return "false";
#endif
} else if (templ == "MQTT_ENABLE") {
if (Mqtt_IsEnabled()) {
return "checked=\"checked\"";
} else {
return String();
}
} else if (templ == "MQTT_USER") {
if (gPrefsSettings.isKey("mqttUser")) {
return gPrefsSettings.getString("mqttUser", "-1");
} else {
return "-1";
}
} else if (templ == "MQTT_PWD") {
if (gPrefsSettings.isKey("mqttPassword")) {
return gPrefsSettings.getString("mqttPassword", "-1");
} else {
return "-1";
}
} else if (templ == "MQTT_USER_LENGTH") {
return String(mqttUserLength - 1);
} else if (templ == "MQTT_PWD_LENGTH") {
return String(mqttPasswordLength - 1);
} else if (templ == "MQTT_CLIENTID_LENGTH") {
return String(mqttClientIdLength - 1);
} else if (templ == "MQTT_SERVER_LENGTH") {
return String(mqttServerLength - 1);
} else if (templ == "MQTT_PORT") {
#ifdef MQTT_ENABLE
return String(gMqttPort);
#endif
} else if (templ == "BT_DEVICE_NAME") {
if (gPrefsSettings.isKey("btDeviceName")) {
return gPrefsSettings.getString("btDeviceName", "");
}
} else if (templ == "BT_PIN_CODE") {
if (gPrefsSettings.isKey("btPinCode")) {
return gPrefsSettings.getString("btPinCode", "");
}
} else if (templ == "IPv4") {
return WiFi.localIP().toString();
} else if (templ == "RFID_TAG_ID") {
return String(gCurrentRfidTagId);
} else if (templ == "HOSTNAME") {
return Wlan_GetHostname();
}
return String();
}
// Takes inputs from webgui, parses JSON and saves values in NVS
// If operation was successful (NVS-write is verified) true is returned
bool processJsonRequest(char *_serialJson) {
if (!_serialJson) {
return false;
}
#ifdef BOARD_HAS_PSRAM
SpiRamJsonDocument doc(1000);
#else
StaticJsonDocument<1000> doc;
#endif
DeserializationError error = deserializeJson(doc, _serialJson);
if (error) {
Log_Printf(LOGLEVEL_ERROR, jsonErrorMsg, error.c_str());
return false;
}
JsonObject object = doc.as<JsonObject>();
if (doc.containsKey("general")) {
uint8_t iVol = doc["general"]["iVol"].as<uint8_t>();
uint8_t mVolSpeaker = doc["general"]["mVolSpeaker"].as<uint8_t>();
uint8_t mVolHeadphone = doc["general"]["mVolHeadphone"].as<uint8_t>();
uint8_t iBright = doc["general"]["iBright"].as<uint8_t>();
uint8_t nBright = doc["general"]["nBright"].as<uint8_t>();
uint8_t iTime = doc["general"]["iTime"].as<uint8_t>();
float vWarning = doc["general"]["vWarning"].as<float>();
float vIndLow = doc["general"]["vIndLow"].as<float>();
float vIndHi = doc["general"]["vIndHi"].as<float>();
uint8_t vInt = doc["general"]["vInt"].as<uint8_t>();
gPrefsSettings.putUInt("initVolume", iVol);
gPrefsSettings.putUInt("maxVolumeSp", mVolSpeaker);
gPrefsSettings.putUInt("maxVolumeHp", mVolHeadphone);
gPrefsSettings.putUChar("iLedBrightness", iBright);
gPrefsSettings.putUChar("nLedBrightness", nBright);
gPrefsSettings.putUInt("mInactiviyT", iTime);
gPrefsSettings.putFloat("wLowVoltage", vWarning);
gPrefsSettings.putFloat("vIndicatorLow", vIndLow);
gPrefsSettings.putFloat("vIndicatorHigh", vIndHi);
gPrefsSettings.putUInt("vCheckIntv", vInt);
// Check if settings were written successfully
if (gPrefsSettings.getUInt("initVolume", 0) != iVol ||
gPrefsSettings.getUInt("maxVolumeSp", 0) != mVolSpeaker ||
gPrefsSettings.getUInt("maxVolumeHp", 0) != mVolHeadphone ||
gPrefsSettings.getUChar("iLedBrightness", 0) != iBright ||
gPrefsSettings.getUChar("nLedBrightness", 0) != nBright ||
gPrefsSettings.getUInt("mInactiviyT", 0) != iTime ||
gPrefsSettings.getFloat("wLowVoltage", 999.99) != vWarning ||
gPrefsSettings.getFloat("vIndicatorLow", 999.99) != vIndLow ||
gPrefsSettings.getFloat("vIndicatorHigh", 999.99) != vIndHi ||
gPrefsSettings.getUInt("vCheckIntv", 17777) != vInt) {
return false;
}
Battery_Init();
} else if (doc.containsKey("ftp")) {
const char *_ftpUser = doc["ftp"]["ftpUser"];
const char *_ftpPwd = doc["ftp"]["ftpPwd"];
gPrefsSettings.putString("ftpuser", (String)_ftpUser);
gPrefsSettings.putString("ftppassword", (String)_ftpPwd);
if (!(String(_ftpUser).equals(gPrefsSettings.getString("ftpuser", "-1")) ||
String(_ftpPwd).equals(gPrefsSettings.getString("ftppassword", "-1")))) {
return false;
}
} else if (doc.containsKey("ftpStatus")) {
uint8_t _ftpStart = doc["ftpStatus"]["start"].as<uint8_t>();
if (_ftpStart == 1) { // ifdef FTP_ENABLE is checked in Ftp_EnableServer()
Ftp_EnableServer();
}
} else if (doc.containsKey("mqtt")) {
uint8_t _mqttEnable = doc["mqtt"]["mqttEnable"].as<uint8_t>();
const char *_mqttClientId = object["mqtt"]["mqttClientId"];
const char *_mqttServer = object["mqtt"]["mqttServer"];
const char *_mqttUser = doc["mqtt"]["mqttUser"];
const char *_mqttPwd = doc["mqtt"]["mqttPwd"];
uint16_t _mqttPort = doc["mqtt"]["mqttPort"].as<uint16_t>();
gPrefsSettings.putUChar("enableMQTT", _mqttEnable);
gPrefsSettings.putString("mqttClientId", (String)_mqttClientId);
gPrefsSettings.putString("mqttServer", (String)_mqttServer);
gPrefsSettings.putString("mqttUser", (String)_mqttUser);
gPrefsSettings.putString("mqttPassword", (String)_mqttPwd);
gPrefsSettings.putUInt("mqttPort", _mqttPort);
if ((gPrefsSettings.getUChar("enableMQTT", 99) != _mqttEnable) ||
(!String(_mqttServer).equals(gPrefsSettings.getString("mqttServer", "-1")))) {
return false;
}
} else if (doc.containsKey("bluetooth")) {
// bluetooth settings
const char *_btDeviceName = doc["bluetooth"]["deviceName"];
gPrefsSettings.putString("btDeviceName", (String)_btDeviceName);
const char *btPinCode = doc["bluetooth"]["pinCode"];
gPrefsSettings.putString("btPinCode", (String)btPinCode);
} else if (doc.containsKey("rfidMod")) {
const char *_rfidIdModId = object["rfidMod"]["rfidIdMod"];
uint8_t _modId = object["rfidMod"]["modId"];
char rfidString[12];
if (_modId <= 0) {
gPrefsRfid.remove(_rfidIdModId);
} else {
snprintf(rfidString, sizeof(rfidString) / sizeof(rfidString[0]), "%s0%s0%s%u%s0", stringDelimiter, stringDelimiter, stringDelimiter, _modId, stringDelimiter);
gPrefsRfid.putString(_rfidIdModId, rfidString);
String s = gPrefsRfid.getString(_rfidIdModId, "-1");
if (s.compareTo(rfidString)) {
return false;
}
}
Web_DumpNvsToSd("rfidTags", backupFile); // Store backup-file every time when a new rfid-tag is programmed
} else if (doc.containsKey("rfidAssign")) {
const char *_rfidIdAssinId = object["rfidAssign"]["rfidIdMusic"];
char _fileOrUrlAscii[MAX_FILEPATH_LENTGH];
convertFilenameToAscii(object["rfidAssign"]["fileOrUrl"], _fileOrUrlAscii);
uint8_t _playMode = object["rfidAssign"]["playMode"];
char rfidString[275];
snprintf(rfidString, sizeof(rfidString) / sizeof(rfidString[0]), "%s%s%s0%s%u%s0", stringDelimiter, _fileOrUrlAscii, stringDelimiter, stringDelimiter, _playMode, stringDelimiter);
gPrefsRfid.putString(_rfidIdAssinId, rfidString);
#ifdef DONT_ACCEPT_SAME_RFID_TWICE_ENABLE
strncpy(gOldRfidTagId, "X", cardIdStringSize-1); // Set old rfid-id to crap in order to allow to re-apply a new assigned rfid-tag exactly once
#endif
String s = gPrefsRfid.getString(_rfidIdAssinId, "-1");
if (s.compareTo(rfidString)) {
return false;
}
Web_DumpNvsToSd("rfidTags", backupFile); // Store backup-file every time when a new rfid-tag is programmed
} else if (doc.containsKey("ping")) {
Web_SendWebsocketData(0, 20);
return false;
} else if (doc.containsKey("controls")) {
if (object["controls"].containsKey("set_volume")) {
uint8_t new_vol = doc["controls"]["set_volume"].as<uint8_t>();
AudioPlayer_VolumeToQueueSender(new_vol, true);
} if (object["controls"].containsKey("action")) {
uint8_t cmd = doc["controls"]["action"].as<uint8_t>();
Cmd_Action(cmd);
}
} else if (doc.containsKey("trackinfo")) {
Web_SendWebsocketData(0, 30);
} else if (doc.containsKey("coverimg")) {
Web_SendWebsocketData(0, 40);
} else if (doc.containsKey("volume")) {
Web_SendWebsocketData(0, 50);
}
return true;
}
// Sends JSON-answers via websocket
void Web_SendWebsocketData(uint32_t client, uint8_t code) {
if (!webserverStarted)
return;
char *jBuf = (char *) x_calloc(255, sizeof(char));
const size_t CAPACITY = JSON_OBJECT_SIZE(1) + 200;
StaticJsonDocument<CAPACITY> doc;
JsonObject object = doc.to<JsonObject>();
if (code == 1) {
object["status"] = "ok";
} else if (code == 2) {
object["status"] = "error";
} else if (code == 10) {
object["rfidId"] = gCurrentRfidTagId;
} else if (code == 20) {
object["pong"] = "pong";
object["rssi"] = Wlan_GetRssi();
// todo: battery percent + loading status +++
//object["battery"] = Battery_GetVoltage();
} else if (code == 30) {
JsonObject entry = object.createNestedObject("trackinfo");
entry["pausePlay"] = gPlayProperties.pausePlay;
entry["currentTrackNumber"] = gPlayProperties.currentTrackNumber + 1;
entry["numberOfTracks"] = gPlayProperties.numberOfTracks;
entry["volume"] = AudioPlayer_GetCurrentVolume();
entry["name"] = gPlayProperties.title;
} else if (code == 40) {
object["coverimg"] = "coverimg";
} else if (code == 50) {
object["volume"] = AudioPlayer_GetCurrentVolume();
};
serializeJson(doc, jBuf, 255);
if (client == 0) {
ws.printfAll(jBuf);
} else {
ws.printf(client, jBuf);
}
free(jBuf);
}
// Processes websocket-requests
void onWebsocketEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
if (type == WS_EVT_CONNECT) {
//client connected
Log_Printf(LOGLEVEL_DEBUG, "ws[%s][%u] connect", server->url(), client->id());
//client->printf("Hello Client %u :)", client->id());
//client->ping();
} else if (type == WS_EVT_DISCONNECT) {
//client disconnected
Log_Printf(LOGLEVEL_DEBUG, "ws[%s][%u] disconnect", server->url(), client->id());
} else if (type == WS_EVT_ERROR) {
//error was received from the other end
Log_Printf(LOGLEVEL_DEBUG, "ws[%s][%u] error(%u): %s", server->url(), client->id(), *((uint16_t *)arg), (char *)data);
} else if (type == WS_EVT_PONG) {
//pong message was received (in response to a ping request maybe)
Log_Printf(LOGLEVEL_DEBUG, "ws[%s][%u] pong[%u]: %s", server->url(), client->id(), len, (len) ? (char *)data : "");
} else if (type == WS_EVT_DATA) {
//data packet
AwsFrameInfo *info = (AwsFrameInfo *)arg;
if (info && info->final && info->index == 0 && info->len == len && client && len > 0) {
//the whole message is in a single frame and we got all of it's data
//Serial.printf("ws[%s][%u] %s-message[%llu]: ", server->url(), client->id(), (info->opcode == WS_TEXT) ? "text" : "binary", info->len);
if (processJsonRequest((char *)data)) {
if (data && (strncmp((char *)data, "getTrack", 8))) { // Don't send back ok-feedback if track's name is requested in background
Web_SendWebsocketData(client->id(), 1);
}
}
if (info->opcode == WS_TEXT) {
data[len] = 0;
//Serial.printf("%s\n", (char *)data);
} else {
for (size_t i = 0; i < info->len; i++) {
Serial.printf("%02x ", data[i]);
}
//Serial.printf("\n");
}
}
}
}
void explorerCreateParentDirectories(const char* filePath) {
char tmpPath[MAX_FILEPATH_LENTGH];
char *rest;
rest = strchr(filePath, '/');
while (rest) {
if (rest-filePath != 0){
memcpy(tmpPath, filePath, rest-filePath);
tmpPath[rest-filePath] = '\0';
Log_Printf(LOGLEVEL_DEBUG, "creating dir \"%s\"\n", tmpPath);
gFSystem.mkdir(tmpPath);
}
rest = strchr(rest+1, '/');
}
}
// Handles file upload request from the explorer
// requires a GET parameter path, as directory path to the file
void explorerHandleFileUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
System_UpdateActivityTimer();
// New File
if (!index) {
String utf8Folder = "/";
String utf8FilePath;
static char filePath[MAX_FILEPATH_LENTGH];
if (request->hasParam("path")) {
AsyncWebParameter *param = request->getParam("path");
utf8Folder = param->value() + "/";
}
utf8FilePath = utf8Folder + filename;
convertFilenameToAscii(utf8FilePath, filePath);
Log_Printf(LOGLEVEL_INFO, writingFile, utf8FilePath.c_str());
// Create Parent directories
explorerCreateParentDirectories(filePath);
// Create Queue for receiving a signal from the store task as synchronisation
if (explorerFileUploadStatusQueue == NULL) {
explorerFileUploadStatusQueue = xQueueCreate(1, sizeof(uint8_t));
}
// reset buffers
index_buffer_write = 0;
index_buffer_read = 0;
for (uint32_t i = 0; i < nr_of_buffers; i++){
size_in_buffer[i] = 0;
buffer_full[i] = false;
}
// Create Task for handling the storage of the data
xTaskCreatePinnedToCore(
explorerHandleFileStorageTask, /* Function to implement the task */
"fileStorageTask", /* Name of the task */
4000, /* Stack size in words */
filePath, /* Task input parameter */
2 | portPRIVILEGE_BIT, /* Priority of the task */
&fileStorageTaskHandle, /* Task handle. */
1 /* Core where the task should run */
);
}
if (len) {
// wait till buffer is ready
while (buffer_full[index_buffer_write]){
vTaskDelay(2u);
}
size_t len_to_write = len;
size_t space_left = chunk_size - size_in_buffer[index_buffer_write];
if (space_left < len_to_write){
len_to_write = space_left;
}
// write content to buffer
memcpy(buffer[index_buffer_write]+size_in_buffer[index_buffer_write], data, len_to_write);
size_in_buffer[index_buffer_write] += len_to_write;
// check if buffer is filled. If full, signal that ready and change buffers
if (size_in_buffer[index_buffer_write] == chunk_size){
// signal, that buffer is ready. Increment index
buffer_full[index_buffer_write] = true;
index_buffer_write = (index_buffer_write + 1) % nr_of_buffers;
// if still content left, put it into next buffer
if (len_to_write < len) {
// wait till new buffer is ready
while (buffer_full[index_buffer_write]){
vTaskDelay(2u);
}
size_t len_left_to_write = len-len_to_write;
memcpy(buffer[index_buffer_write], data + len_to_write, len_left_to_write);
size_in_buffer[index_buffer_write] = len_left_to_write;
}
}
}
if (final) {
// if file not completely done yet, signal that buffer is filled
if (size_in_buffer[index_buffer_write] > 0) {
buffer_full[index_buffer_write] = true;
}
// notify storage task that last data was stored on the ring buffer
xTaskNotify(fileStorageTaskHandle, 1u, eNoAction);
// watit until the storage task is sending the signal to finish
uint8_t signal;
xQueueReceive(explorerFileUploadStatusQueue, &signal, portMAX_DELAY);
}
}
// feed the watchdog timer without delay
void feedTheDog(void) {
#if defined(SD_MMC_1BIT_MODE) && defined(CONFIG_IDF_TARGET_ESP32)
// feed dog 0
TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE; // write enable
TIMERG0.wdt_feed=1; // feed dog
TIMERG0.wdt_wprotect=0; // write protect
// feed dog 1
TIMERG1.wdt_wprotect=TIMG_WDT_WKEY_VALUE; // write enable
TIMERG1.wdt_feed=1; // feed dog
TIMERG1.wdt_wprotect=0; // write protect
#else
// Without delay upload-feature is broken for SD via SPI (for whatever reason...)
vTaskDelay(portTICK_PERIOD_MS * 11);
#endif
}
void explorerHandleFileStorageTask(void *parameter) {
File uploadFile;
size_t bytesOk = 0;
size_t bytesNok = 0;
uint32_t chunkCount = 0;
uint32_t transferStartTimestamp = millis();
uint8_t value = 0;