-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathWeb.cpp
1364 lines (1221 loc) · 49.5 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 "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"
#if (LANGUAGE == DE)
#include "HTMLaccesspoint_DE.h"
#include "HTMLmanagement_DE.h"
#endif
#if (LANGUAGE == EN)
#include "HTMLaccesspoint_EN.h"
#include "HTMLmanagement_EN.h"
#endif
typedef struct {
char nvsKey[13];
char nvsEntry[275];
} nvs_t;
const char mqttTab[] PROGMEM = "<a class=\"nav-item nav-link\" id=\"nav-mqtt-tab\" data-toggle=\"tab\" href=\"#nav-mqtt\" role=\"tab\" aria-controls=\"nav-mqtt\" aria-selected=\"false\"><i class=\"fas fa-network-wired\"></i> MQTT</a>";
const char ftpTab[] PROGMEM = "<a class=\"nav-item nav-link\" id=\"nav-ftp-tab\" data-toggle=\"tab\" href=\"#nav-ftp\" role=\"tab\" aria-controls=\"nav-ftp\" aria-selected=\"false\"><i class=\"fas fa-folder\"></i> FTP</a>";
AsyncWebServer wServer(80);
AsyncWebSocket ws("/ws");
AsyncEventSource events("/events");
static bool webserverStarted = false;
static RingbufHandle_t explorerFileUploadRingBuffer;
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 handleCoverImageRequest(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);
void Web_DeleteCachefile(const char *fileOrDirectory);
// 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>;
void Web_Init(void) {
wServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/html", accesspoint_HTML);
});
wServer.on("/init", HTTP_POST, [](AsyncWebServerRequest *request) {
if (request->hasParam("ssid", true) && request->hasParam("pwd", true) && request->hasParam("hostname", true)) {
gPrefsSettings.putString("SSID", request->getParam("ssid", true)->value());
gPrefsSettings.putString("Password", request->getParam("pwd", true)->value());
gPrefsSettings.putString("Hostname", request->getParam("hostname", true)->value());
}
request->send_P(200, "text/html", accesspoint_HTML);
});
wServer.on("/restart", HTTP_GET, [](AsyncWebServerRequest *request) {
#if (LANGUAGE == DE)
request->send(200, "text/html", (char *) F("ESPuino wird neu gestartet..."));
#else
request->send(200, "text/html", (char *) F("ESPuino is being restarted..."));
#endif
Serial.flush();
ESP.restart();
});
wServer.on("/shutdown", HTTP_GET, [](AsyncWebServerRequest *request) {
#if (LANGUAGE == DE)
request->send(200, "text/html", (char *) F("ESPuino wird ausgeschaltet..."));
#else
request->send(200, "text/html", (char *) F("ESPuino is being shutdown..."));
#endif
System_RequestSleep();
});
// 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((char *) FPSTR(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) {
if (gFSystem.exists("/.html/index.htm")) {
// serve webpage from SD card
request->send(gFSystem, "/.html/index.htm", String(), false, templateProcessor);
} else {
// serve webpage from PROGMEM
request->send_P(200, "text/html", management_HTML, templateProcessor);
}
});
// 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) {
String info = "ESPuino " + (String) softwareRevision;
info += "\nESPuino " + (String) gitRevision;
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(Log_Buffer, Log_BufferLength, "\n%s: %.2f V", (char *) FPSTR(currentVoltageMsg), Battery_GetVoltage());
info += (String) Log_Buffer;
snprintf(Log_Buffer, Log_BufferLength, "\n%s: %.2f %%", (char *)FPSTR(currentChargeMsg), Battery_EstimateLevel() * 100);
info += (String) Log_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
request->send(200, "text/html", restartWebsite); },
#else
request->send(200, "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((char *) FPSTR(otaNotSupported), LOGLEVEL_NOTICE);
return;
#endif
if (!index) {
if (!gPlayProperties.pausePlay) { // Pause playback as it sounds ugly when OTA starts
Cmd_Action(CMD_PLAYPAUSE); // Pause first to possibly to save last playposition (if necessary)
Cmd_Action(CMD_STOP);
}
Update.begin();
Log_Println((char *) FPSTR(fwStart), LOGLEVEL_NOTICE);
}
Update.write(data, len);
Log_Print(".", LOGLEVEL_NOTICE, false);
if (final) {
Update.end(true);
Log_Println((char *) FPSTR(fwEnd), LOGLEVEL_NOTICE);
Serial.flush();
ESP.restart();
}
});
// ESP-restart
wServer.on("/restart", HTTP_GET, [](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((char *) FPSTR(eraseRfidNvs), LOGLEVEL_NOTICE);
gPrefsRfid.clear();
Web_DumpNvsToSd("rfidTags", (const char*) FPSTR(backupFile));
});
// 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);
// current cover image
wServer.on("/cover", HTTP_GET, handleCoverImageRequest);
// ESPuino logo
wServer.on("/logo", HTTP_GET, [](AsyncWebServerRequest *request) {
Log_Println((char *) F("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((char *) F("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");
});
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 (String) FPSTR(ftpTab);
#else
return String();
#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") {
return gPrefsSettings.getString("mqttClientId", "-1");
} else if (templ == "MQTT_SERVER") {
return gPrefsSettings.getString("mqttServer", "-1");
} else if (templ == "SHOW_MQTT_TAB") { // Only show MQTT-tab if MQTT-support was compiled
#ifdef MQTT_ENABLE
return (String) FPSTR(mqttTab);
#else
return String();
#endif
} else if (templ == "MQTT_ENABLE") {
if (Mqtt_IsEnabled()) {
return String("checked=\"checked\"");
} else {
return String();
}
} else if (templ == "MQTT_USER") {
return gPrefsSettings.getString("mqttUser", "-1");
} else if (templ == "MQTT_PWD") {
return gPrefsSettings.getString("mqttPassword", "-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_SOURCE_NAME") {
return gPrefsSettings.getString("btDeviceName", "");
} else if (templ == "IPv4") {
IPAddress myIP = WiFi.localIP();
snprintf(Log_Buffer, Log_BufferLength, "%d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
return String(Log_Buffer);
} else if (templ == "RFID_TAG_ID") {
return String(gCurrentRfidTagId);
} else if (templ == "HOSTNAME") {
return gPrefsSettings.getString("Hostname", "-1");
}
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) {
#if (LANGUAGE == DE)
snprintf(Log_Buffer, Log_BufferLength, "%s", (char *) F("deserializeJson() fehlgeschlagen: "));
#else
nprintf(Log_Buffer, Log_BufferLength, "%s", (char *) F("deserializeJson() failed: "));
#endif
Log_Print(Log_Buffer, LOGLEVEL_ERROR, true);
snprintf(Log_Buffer, Log_BufferLength, "%s\n", error.c_str());
Log_Print(Log_Buffer, LOGLEVEL_ERROR, true);
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("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", (const char*) FPSTR(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];
convertUtf8ToAscii(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", (const char*) FPSTR(backupFile)); // Store backup-file every time when a new rfid-tag is programmed
} else if (doc.containsKey("wifiConfig")) {
const char *_ssid = object["wifiConfig"]["ssid"];
const char *_pwd = object["wifiConfig"]["pwd"];
const char *_hostname = object["wifiConfig"]["hostname"];
gPrefsSettings.putString("SSID", _ssid);
gPrefsSettings.putString("Password", _pwd);
gPrefsSettings.putString("Hostname", (String)_hostname);
String sSsid = gPrefsSettings.getString("SSID", "-1");
String sPwd = gPrefsSettings.getString("Password", "-1");
String sHostname = gPrefsSettings.getString("Hostname", "-1");
if (sSsid.compareTo(_ssid) || sPwd.compareTo(_pwd)) {
return false;
}
}
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
snprintf(Log_Buffer, Log_BufferLength, "ws[%s][%u] connect", server->url(), client->id());
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
//client->printf("Hello Client %u :)", client->id());
//client->ping();
} else if (type == WS_EVT_DISCONNECT) {
//client disconnected
snprintf(Log_Buffer, Log_BufferLength, "ws[%s][%u] disconnect", server->url(), client->id());
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
} else if (type == WS_EVT_ERROR) {
//error was received from the other end
snprintf(Log_Buffer, Log_BufferLength, "ws[%s][%u] error(%u): %s", server->url(), client->id(), *((uint16_t *)arg), (char *)data);
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
} else if (type == WS_EVT_PONG) {
//pong message was received (in response to a ping request maybe)
snprintf(Log_Buffer, Log_BufferLength, "ws[%s][%u] pong[%u]: %s", server->url(), client->id(), len, (len) ? (char *)data : "");
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
} 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';
printf("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 utf8FilePath;
static char filePath[MAX_FILEPATH_LENTGH];
if (request->hasParam("path")) {
AsyncWebParameter *param = request->getParam("path");
utf8FilePath = param->value() + "/" + filename;
} else {
utf8FilePath = "/" + filename;
}
convertUtf8ToAscii(utf8FilePath, filePath);
snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *)FPSTR (writingFile), utf8FilePath.c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
Web_DeleteCachefile(utf8FilePath.c_str());
// Create Parent directories
explorerCreateParentDirectories(filePath);
// Create Ringbuffer for upload
if (explorerFileUploadRingBuffer == NULL) {
explorerFileUploadRingBuffer = xRingbufferCreate(8192, RINGBUF_TYPE_BYTEBUF);
}
// Create Queue for receiving a signal from the store task as synchronisation
if (explorerFileUploadStatusQueue == NULL) {
explorerFileUploadStatusQueue = xQueueCreate(1, sizeof(uint8_t));
}
// 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) {
// stream the incoming chunk to the ringbuffer
xRingbufferSend(explorerFileUploadRingBuffer, data, len, portTICK_PERIOD_MS * 1000);
}
if (final) {
// 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);
// delete task
vTaskDelete(fileStorageTaskHandle);
}
}
// feed the watchdog timer without delay
void feedTheDog(void) {
#ifdef SD_MMC_1BIT_MODE
// 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 item_size;
size_t bytesOk = 0;
size_t bytesNok = 0;
uint32_t chunkCount = 0;
uint32_t transferStartTimestamp = millis();
uint8_t *item;
uint8_t value = 0;
uint32_t lastUpdateTimestamp = millis();
uint32_t maxUploadDelay = 20; // After this delay (in seconds) task will be deleted as transfer is considered to be finally broken
BaseType_t uploadFileNotification;
uint32_t uploadFileNotificationValue;
uploadFile = gFSystem.open((char *)parameter, "w");
size_t maxItems = xRingbufferGetMaxItemSize(explorerFileUploadRingBuffer);
for (;;) {
// check buffer is filled with enough data
size_t itemsFree = xRingbufferGetCurFreeSize(explorerFileUploadRingBuffer);
item_size = maxItems - itemsFree;
if (item_size < (maxItems / 2)) {
// not enough data in the buffer, check if all data arrived for the file
uploadFileNotification = xTaskNotifyWait(0, 0, &uploadFileNotificationValue, 0);
if (uploadFileNotification == pdPASS) {
item = (uint8_t *)xRingbufferReceive(explorerFileUploadRingBuffer, &item_size, portTICK_PERIOD_MS * 100);
if (item != NULL) {
chunkCount++;
if (!uploadFile.write(item, item_size)) {
bytesNok += item_size;
} else {
bytesOk += item_size;
}
vRingbufferReturnItem(explorerFileUploadRingBuffer, (void *)item);
vTaskDelay(portTICK_PERIOD_MS * 20);
}
uploadFile.close();
snprintf(Log_Buffer, Log_BufferLength, "%s: %s => %zu bytes in %lu ms (%lu kiB/s)", (char *)FPSTR (fileWritten), (char *)parameter, bytesNok+bytesOk, (millis() - transferStartTimestamp), (bytesNok+bytesOk)/(millis() - transferStartTimestamp));
Log_Println(Log_Buffer, LOGLEVEL_INFO);
snprintf(Log_Buffer, Log_BufferLength, "Bytes [ok] %zu / [not ok] %zu, Chunks: %zu\n", bytesOk, bytesNok, chunkCount);
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
// done exit loop to terminate
break;
}
if (lastUpdateTimestamp + maxUploadDelay * 1000 < millis()) {
snprintf(Log_Buffer, Log_BufferLength, (char *) FPSTR(webTxCanceled));
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
vTaskDelete(NULL);
return;
}
vTaskDelay(portTICK_PERIOD_MS * 5);
continue;
}
item = (uint8_t *)xRingbufferReceive(explorerFileUploadRingBuffer, &item_size, portTICK_PERIOD_MS * 100);
if (item != NULL) {
chunkCount++;
if (!uploadFile.write(item, item_size)) {
bytesNok += item_size;
feedTheDog();
} else {
bytesOk += item_size;
}
vRingbufferReturnItem(explorerFileUploadRingBuffer, (void *)item);
feedTheDog();
lastUpdateTimestamp = millis();
}
}
// send signal to upload function to terminate
xQueueSend(explorerFileUploadStatusQueue, &value, 0);
vTaskDelete(NULL);
}
// Sends a list of the content of a directory as JSON file
// requires a GET parameter path for the directory
void explorerHandleListRequest(AsyncWebServerRequest *request) {
uint32_t listStartTimestamp = millis();
//DynamicJsonDocument jsonBuffer(8192);
#ifdef BOARD_HAS_PSRAM
SpiRamJsonDocument jsonBuffer(65636);
#else
StaticJsonDocument<8192> jsonBuffer;
#endif
String serializedJsonString;
AsyncWebParameter *param;
char filePath[MAX_FILEPATH_LENTGH];
JsonArray obj = jsonBuffer.createNestedArray();
File root;
if (request->hasParam("path")) {
param = request->getParam("path");
convertUtf8ToAscii(param->value(), filePath);
root = gFSystem.open(filePath);
} else {
root = gFSystem.open("/");
}
if (!root) {
snprintf(Log_Buffer, Log_BufferLength, (char *) FPSTR(failedToOpenDirectory));
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
return;
}
if (!root.isDirectory()) {
snprintf(Log_Buffer, Log_BufferLength, (char *) FPSTR(notADirectory));
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
return;
}
File file = root.openNextFile();
while (file) {
// ignore hidden folders, e.g. MacOS spotlight files
#if ESP_ARDUINO_VERSION_MAJOR >= 2
if (!startsWith( file.path() , (char *)"/.")) {
#else
if (!startsWith( file.name() , (char *)"/.")) {
#endif
JsonObject entry = obj.createNestedObject();
#if ESP_ARDUINO_VERSION_MAJOR >= 2
convertAsciiToUtf8(file.path(), filePath);
#else
convertAsciiToUtf8(file.name(), filePath);
#endif
std::string path = filePath;
std::string fileName = path.substr(path.find_last_of("/") + 1);
entry["name"] = fileName;
entry["dir"].set(file.isDirectory());
}
file.close();
file = root.openNextFile();
if (!gPlayProperties.pausePlay) {
// time critical, avoid delay with many files on SD-card!
feedTheDog();
} else {
// If playback is active this can (at least sometimes) prevent scattering
vTaskDelay(portTICK_PERIOD_MS * 5);
}
}
root.close();
serializeJson(obj, serializedJsonString);
snprintf(Log_Buffer, Log_BufferLength, "build filelist finished: %lu ms", (millis() - listStartTimestamp));
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
request->send(200, (char *) F("application/json; charset=utf-8"), serializedJsonString);
}
bool explorerDeleteDirectory(File dir) {
File file = dir.openNextFile();
while (file) {
if (file.isDirectory()) {
explorerDeleteDirectory(file);
} else {
#if ESP_ARDUINO_VERSION_MAJOR >= 2
gFSystem.remove(file.path());
#else
gFSystem.remove(file.name());
#endif
}
file = dir.openNextFile();
esp_task_wdt_reset();
}
#if ESP_ARDUINO_VERSION_MAJOR >= 2
return gFSystem.rmdir(dir.path());
#else
return gFSystem.rmdir(dir.name());
#endif
}
// Handles delete-requests for cachefiles.
// This is necessary to avoid outdated cachefiles if content of a directory changes (create, rename, delete).
void Web_DeleteCachefile(const char *fileOrDirectory) {
char cacheFile[MAX_FILEPATH_LENTGH];
const char s = '/';
char *last = strrchr(fileOrDirectory, s);
char *first = strchr(fileOrDirectory, s);
unsigned long substr = last - first + 1;
snprintf(cacheFile, substr+1, "%s", fileOrDirectory);
strcat(cacheFile, playlistCacheFile);
if (gFSystem.exists(cacheFile)) {
if (gFSystem.remove(cacheFile)) {
snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(erasePlaylistCachefile), cacheFile);
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
}
}
}
// Handles download request of a file
// requires a GET parameter path to the file
void explorerHandleDownloadRequest(AsyncWebServerRequest *request) {
File file;
AsyncWebParameter *param;
char filePath[MAX_FILEPATH_LENTGH];
// check has path param
if (!request->hasParam("path")) {
Log_Println((char *) F("DOWNLOAD: No path variable set"), LOGLEVEL_ERROR);
request->send(404);
return;
}
// check file exists on SD card
param = request->getParam("path");
convertUtf8ToAscii(param->value(), filePath);
if (!gFSystem.exists(filePath)) {
snprintf(Log_Buffer, Log_BufferLength, "DOWNLOAD: File not found on SD card: %s", param->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
request->send(404);
return;
}
// check is file and not a directory
file = gFSystem.open(filePath);
if (file.isDirectory()) {
snprintf(Log_Buffer, Log_BufferLength, "DOWNLOAD: Cannot download a directory %s", param->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
request->send(404);
file.close();
return;
}
// ready to serve the file for download.