-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathutils.cpp
More file actions
1223 lines (1116 loc) · 44.1 KB
/
Copy pathutils.cpp
File metadata and controls
1223 lines (1116 loc) · 44.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
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
// General utilities not specific to this app to support:
// - wifi / ethernet
// - NTP
// - base64 encoding
// - device startup & sleep
//
// s60sc 2021, 2023, 2025, 2026
// some functions based on code contributed by gemi254
#include "appGlobals.h"
bool timeSynchronized = false;
bool monitorOpen = true;
bool dataFilesChecked = false;
size_t alertBufferSize = 0;
size_t maxAlertBuffSize = 32 * 1024;
byte* alertBuffer = NULL; // buffer for telegram / smtp alert image
int wakePin = -1; // if wakeUse is true
int wakeLevel; // if wakeUse is true
bool wakeUse = false; // true to allow app to sleep and wake
char* jsonBuff = NULL;
char portFwd[6] = "";
UBaseType_t STACK_MEM; // allow some task stacks to use psram if available
float latLon[2] = {0};
RTC_DATA_ATTR uint32_t remainingSeconds = 0;
uint32_t deepSleepTimer = 0;
bool appSetupDone = false;
#define xstr(s) str(s)
#define str(s) #s
const char* storageType = xstr(STORAGE);
/************************** Network (WiFi/Ethernet) **************************/
#include <esp_task_wdt.h>
/** Do not hard code anything below here unless you know what you are doing **/
/** Use the web interface to configure wifi settings **/
char hostName[MAX_HOST_LEN] = ""; // Default Host name
char ST_SSID[MAX_HOST_LEN] = ""; //Default router ssid
char ST_Pass[MAX_PWD_LEN] = ""; //Default router passd
// leave following blank for dhcp
char ST_ip[MAX_IP_LEN] = ""; // Static IP
char ST_sn[MAX_IP_LEN] = ""; // subnet normally 255.255.255.0
char ST_gw[MAX_IP_LEN] = ""; // gateway to internet, normally router IP
char ST_ns1[MAX_IP_LEN] = ""; // DNS Server, can be router IP (needed for SNTP)
char ST_ns2[MAX_IP_LEN] = ""; // alternative DNS Server, can be blank
// Access point Config Portal SSID and Pass
char AP_SSID[MAX_HOST_LEN] = "";
char AP_Pass[MAX_PWD_LEN] = "";
char AP_ip[MAX_IP_LEN] = ""; // Leave blank to use 192.168.4.1
char AP_sn[MAX_IP_LEN] = "";
char AP_gw[MAX_IP_LEN] = "";
// SPI pins for Ethernet
int ethCS = -1; // W5500 chip select / LAN8720 MDC
int ethInt = -1; // W5500 interrupt / LAN8720 MDIO
int ethRst = -1; // W5500 reset / LAN8720 POWER
int ethSclk = -1; // W5500 SPI clock / LAN8720 CLOCK
int ethMiso = -1; // W5500 SPI data pin
int ethMosi = -1; // W5500 SPI data pin
// basic HTTP Authentication access to web page
char Auth_Name[MAX_HOST_LEN] = "";
char Auth_Pass[MAX_PWD_LEN] = "";
int responseTimeoutSecs = 10; // time to wait for FTP or SMTP response
bool allowAP = true; // set to true to allow AP to startup if cannot connect to STA (router)
uint32_t wifiTimeoutSecs = 30; // how often to check wifi status
static bool APstarted = false;
esp_ping_handle_t pingHandle = NULL;
bool usePing = true;
TaskHandle_t statusCheckHandle = NULL;
static inline void runStatusCheck();
static bool startPing();
static bool waitForNTPsync(int maxRetries = 5, uint32_t perTryTimeoutMs = 2000);
char timezone[FILE_NAME_LEN] = "GMT0";
char ntpServer[MAX_HOST_LEN] = "pool.ntp.org";
int netMode = 0; // 0=WiFi only, 1=Ethernet only, 2=Ethernet+AP
// LAN8720
#define ETH_PHY_ADDR 0
#define ETH_CLK_MODE ETH_CLOCK_GPIO0_IN // external clock from crystal oscillator
static const char* wifiModes[] = {"NULL", "STA", "AP", "STA+AP", "NAN"};
static wifi_mode_t getWifiMode() {
wifi_mode_t wifiMode = WiFi.getMode();
LOG_INF("WiFi Mode: %s", wifiModes[wifiMode]);
return wifiMode;
}
static void setupMdnsHost() {
// set up MDNS service
char mdnsName[MAX_IP_LEN]; // max mdns host name length
snprintf(mdnsName, MAX_IP_LEN, "%.*s", MAX_IP_LEN - 1, hostName);
MDNS.end();
if (MDNS.begin(mdnsName)) {
// Add service to MDNS
useHttps ? MDNS.addService("https", "tcp", HTTPS_PORT) : MDNS.addService("http", "tcp", HTTP_PORT);
MDNS.addService("ws", "udp", 83);
MDNS.addService("ftp", "tcp", 21);
LOG_INF("mDNS service: http%s://%s.local", useHttps ? "s" : "", mdnsName);
} else LOG_WRN("mDNS host: %s Failed", mdnsName);
debugMemory("setupMdnsHost");
}
static const char* wifiStatusStr(wl_status_t wlStat) {
switch (wlStat) {
case WL_NO_SHIELD: return "wifi not initialised";
case WL_IDLE_STATUS: return "WL_IDLE_STATUS";
case WL_NO_SSID_AVAIL: return "not available, use AP";
case WL_SCAN_COMPLETED: return "WL_SCAN_COMPLETED";
case WL_CONNECTED: return "WL_CONNECTED";
case WL_CONNECT_FAILED: return "WL_CONNECT_FAILED";
case WL_CONNECTION_LOST: return "WL_CONNECTION_LOST";
case WL_DISCONNECTED: return "unable to connect";
case WL_STOPPED: return "wifi stopped";
default: return "Invalid WiFi.status";
}
}
const char* getEncType(int ssidIndex) {
switch (WiFi.encryptionType(ssidIndex)) {
case (WIFI_AUTH_OPEN): return "Open";
case (WIFI_AUTH_WEP): return "WEP";
case (WIFI_AUTH_WPA_PSK): return "WPA_PSK";
case (WIFI_AUTH_WPA2_PSK): return "WPA2_PSK";
case (WIFI_AUTH_WPA_WPA2_PSK): return "WPA_WPA2_PSK";
case (WIFI_AUTH_WPA2_ENTERPRISE): return "WPA2_ENTERPRISE";
case (WIFI_AUTH_MAX): return "AUTH_MAX";
default: return "Not listed";
}
}
static void onNetEvent(arduino_event_id_t event, arduino_event_info_t info) {
// callback to report on network events
switch (event) {
case ARDUINO_EVENT_WIFI_READY: break;
case ARDUINO_EVENT_WIFI_SCAN_DONE: break;
case ARDUINO_EVENT_WIFI_STA_START: LOG_INF("Wifi Station started, connecting to: %s", ST_SSID); break;
case ARDUINO_EVENT_WIFI_STA_STOP: LOG_INF("Wifi Station stopped %s", ST_SSID); break;
case ARDUINO_EVENT_WIFI_AP_START: {
if (WiFi.AP.SSID().length() > 0 && WiFi.AP.SSID() == AP_SSID) {
LOG_INF("Wifi AP SSID: %s started, use 'http%s://%s' to connect", WiFi.AP.SSID().c_str(), useHttps ? "s" : "", formatIPstr(true));
APstarted = true;
}
break;
}
case ARDUINO_EVENT_WIFI_AP_STOP: {
if (WiFi.AP.SSID() == AP_SSID) {
LOG_INF("Wifi AP stopped: %s", AP_SSID);
APstarted = false;
}
break;
}
case ARDUINO_EVENT_WIFI_STA_GOT_IP: LOG_INF("Wifi Station IP, use '%s://%s' to connect", useHttps ? "https" : "http", formatIPstr()); break;
case ARDUINO_EVENT_WIFI_STA_LOST_IP: LOG_INF("Wifi Station lost IP"); break;
case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED: break;
case ARDUINO_EVENT_WIFI_STA_CONNECTED: LOG_INF("WiFi Station connection to %s, using hostname: %s", ST_SSID, hostName); break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: LOG_INF("WiFi Station disconnected"); break;
case ARDUINO_EVENT_WIFI_AP_STACONNECTED: LOG_INF("WiFi AP client connection"); break;
case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED: LOG_INF("WiFi AP client disconnection"); break;
case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED: break;
case ARDUINO_EVENT_WIFI_AP_GOT_IP6: LOG_INF("AP interface V6 IP addr is preferred"); break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP6: LOG_INF("Station interface V6 IP addr is preferred"); break;
case ARDUINO_EVENT_WIFI_OFF: LOG_INF("WiFi Off"); break;
case ARDUINO_EVENT_ETH_START: LOG_INF("Ethernet started, speed %uMHz", ETH.linkSpeed()); break;
case ARDUINO_EVENT_ETH_CONNECTED: LOG_INF("Ethernet connected, MAC: %s", ETH.macAddress().c_str()); break;
case ARDUINO_EVENT_ETH_STOP: LOG_INF("Ethernet Stopped"); break;
case ARDUINO_EVENT_ETH_GOT_IP: {
LOG_INF("Ethernet IP, use '%s://%s' to connect", useHttps ? "https" : "http", formatIPstr());
if (netMode == 2) WiFi.AP.enableNAPT(true);
break;
}
case ARDUINO_EVENT_ETH_DISCONNECTED: {
LOG_INF("Ethernet disconnected");
if (netMode == 2) WiFi.AP.enableNAPT(false);
break;
}
case ARDUINO_EVENT_ETH_LOST_IP: {
LOG_INF("Ethernet lost IP");
if (netMode == 2) WiFi.AP.enableNAPT(false);
break;
}
default: LOG_WRN("Unhandled network event %d", event); break;
}
}
static void setWifiAP() {
if (!APstarted) {
delay(100);
WiFi.AP.begin();
// Set access point with static ip if provided
if (strlen(AP_ip) > 1) {
LOG_INF("Set AP static IP :%s, %s, %s", AP_ip, AP_gw, AP_sn);
IPAddress _ip, _gw, _sn, _ns1, _ns2;
_ip.fromString(AP_ip);
_gw.fromString(AP_gw);
_sn.fromString(AP_sn);
// set static ip
WiFi.AP.config(_ip, _gw, _sn);
}
WiFi.AP.create(AP_SSID, AP_Pass);
// allow AP time to start
uint32_t t0 = millis();
while (!APstarted && millis() - t0 < 2000) delay(50);
debugMemory("setWifiAP");
}
}
static void setWifiSTA() {
// set station with static ip if provided
if (strlen(ST_ip) > 1) {
IPAddress _ip, _gw, _sn, _ns1, _ns2;
if (!_ip.fromString(ST_ip)) LOG_WRN("Failed to parse IP: %s", ST_ip);
else {
_ip.fromString(ST_ip);
_gw.fromString(ST_gw);
_sn.fromString(ST_sn);
_ns1.fromString(ST_ns1);
_ns2.fromString(ST_ns2);
// set static ip
WiFi.STA.config(_ip, _gw, _sn, _ns1); // need DNS for SNTP
LOG_INF("Wifi Station set static IP");
}
} else LOG_INF("Wifi Station IP from DHCP");
WiFi.STA.enableIPv6(USE_IP6);
WiFi.STA.begin();
WiFi.STA.connect(ST_SSID, ST_Pass);
debugMemory("setWifiSTA");
}
static void predefEthPins() {
// set board specific pins if defined
#if defined(ETH_CS)
char ethPin[3];
sprintf(ethPin, "%d", ETH_CS);
updateStatus("ethCS", ethPin);
sprintf(ethPin, "%d", ETH_INT);
updateStatus("ethInt", ethPin);
sprintf(ethPin, "%d", ETH_RST);
updateStatus("ethRst", ethPin);
sprintf(ethPin, "%d", ETH_SCLK);
updateStatus("ethSclk", ethPin);
sprintf(ethPin, "%d", ETH_MISO);
updateStatus("ethMiso", ethPin);
sprintf(ethPin, "%d", ETH_MOSI);
updateStatus("ethMosi", ethPin);
#endif
}
static bool startEth(bool firstcall) {
// Initialize Ethernet (W5500) via SPI, only viable on ESP32-S3 board
// Internal on ESP32-S3-ETH board, or use separate external board
if (ethCS != -1) {
if (!firstcall) {
// reset after ping failure
ETH.end();
// Give PHY time to fully de-assert
unsigned long phySettle = millis() + 5000; // 5 secs
while (millis() < phySettle) yield();
}
#if CONFIG_IDF_TARGET_ESP32S3
if (!ETH.begin(ETH_PHY_W5500,
ETH_PHY_ADDR_AUTO,
ethCS,
ethInt,
ethRst,
SPI2_HOST,
ethSclk,
ethMiso,
ethMosi,
ETH_PHY_SPI_FREQ_MHZ)) {
LOG_WRN("Ethernet W5500 init failed");
return false;
}
#endif
#if CONFIG_IDF_TARGET_ESP32
#ifdef ISCAM
LOG_WRN("Insufficient pins for Ethernet on ESP32");
netMode = 0;
return false;
#else
// RMII uses predefined pins 19, 21, 22, 25, 26, 27
if (!ETH.begin(ETH_PHY_LAN8720,
ETH_PHY_ADDR,
ethCS, // LAN8720 MDC
ethInt, // LAN8720 MDIO
ethRst, // LAN8720 POWER
ETH_CLK_MODE)) {
LOG_WRN("Ethernet LAN8720 init failed");
return false;
}
#endif
#endif
// Apply static IP to Ethernet if configured in existing fields
if (strlen(ST_ip) > 1) {
IPAddress _ip, _gw, _sn, _ns1, _ns2;
if (_ip.fromString(ST_ip)) {
_gw.fromString(ST_gw);
_sn.fromString(ST_sn);
_ns1.fromString(ST_ns1);
_ns2.fromString(ST_ns2);
ETH.config(_ip, _gw, _sn, _ns1, _ns2);
LOG_INF("Ethernet set static IP");
} else LOG_WRN("Failed to parse Ethernet static IP: %s", ST_ip);
}
} else {
LOG_WRN("Ethernet pins not defined");
return false;
}
// wait for link and DHCP or static assignment
uint32_t startAttemptTime = millis();
while (!ETH.linkUp() && millis() - startAttemptTime < 8000) delay(100);
if (!ETH.linkUp()) LOG_WRN("Ethernet link not up");
startAttemptTime = millis();
while (!ETH.localIP() && millis() - startAttemptTime < 8000) delay(100);
if (!ETH.localIP()) LOG_WRN("Ethernet no IP yet");
setupMdnsHost();
if (pingHandle == NULL) startPing();
return ETH.linkUp();
}
static bool startWifi(bool firstcall = true) {
// start wifi station (and wifi AP if allowed or station not defined)
if (firstcall) {
#ifdef NO_WIFI_SLEEP
WiFi.setSleep(false); // Disable Power Saving depending on app
#endif
WiFi.persistent(false); // prevent the flash storage WiFi credentials
WiFi.AP.clear();
WiFi.AP.end(); // kill rogue AP on startup
WiFi.mode(WIFI_AP_STA);
WiFi.STA.setAutoReconnect(false); // Set whether module will attempt to reconnect to an access point in case it is disconnected
WiFi.STA.setHostname(hostName);
delay(100);
}
wl_status_t wlStat = WL_NO_SSID_AVAIL;
if (netMode == 0) {
// connect to Wifi station
setWifiSTA();
uint32_t startAttemptTime = millis();
// Stop trying on failure timeout, will try to reconnect later by ping
wlStat = WL_NO_SSID_AVAIL;
if (strlen(ST_SSID)) {
while (wlStat = WiFi.STA.status(), wlStat != WL_CONNECTED && millis() - startAttemptTime < 5000) {
LOG_SEND(".");
delay(500);
}
}
// show stats of requested SSID if present
int numNetworks = strlen(ST_SSID) ? WiFi.scanNetworks() : 0;
for (int i=0; i < numNetworks; i++) {
if (WiFi.SSID(i) == ST_SSID)
LOG_INF("Wifi stats for %s - signal strength: %ld dBm; Encryption: %s; channel: %ld", ST_SSID, WiFi.RSSI(i), getEncType(i), WiFi.channel(i));
}
if (wlStat != WL_CONNECTED) LOG_WRN("SSID %s not connected %s", ST_SSID, wifiStatusStr(wlStat));
}
if (wlStat == WL_NO_SSID_AVAIL || allowAP) setWifiAP(); // AP allowed if no Station SSID eg on first time use
#if CONFIG_IDF_TARGET_ESP32S3
if (netMode == 0) setupMdnsHost(); // not on ESP32 as uses 6k of heap
#endif
if (pingHandle == NULL) startPing();
getWifiMode();
return wlStat == WL_CONNECTED ? true : false;
}
bool startNetwork(bool firstcall) {
// start WiFi, Ethernet, Eth+AP by config
bool res = false;
if (firstcall) Network.onEvent(onNetEvent);
predefEthPins();
if (netMode > 0) {
// Ethernet or Eth+AP
if (startEth(firstcall)) {
if (netMode == 1) {
// Quiet mode: stop WiFi/BLE radios for RF silence
WiFi.mode(WIFI_OFF);
#ifdef APP_BT_ENABLED
if (btStarted()) btStop();
#endif
res = true;
}
} else {
LOG_WRN("Ethernet start failed, falling back to WiFi");
ETH.end();
WiFi.AP.enableNAPT(false);
netMode = 0;
}
}
// Wifi only / Eth fail / Eth + AP
if (netMode == 2) {
WiFi.AP.enableNAPT(true);
allowAP = true;
}
// connect wifi STA, or AP if router details not available
if (!res) startWifi(firstcall);
res = startWebServer();
#ifdef DEV_ONLY
devCheck();
#endif
if (res) runStatusCheck();
else {
snprintf(startupFailure, SF_LEN, STARTUP_FAIL "Failed to complete network setup");
LOG_WRN("%s", startupFailure);
}
if (res) getExtIP();
if (res) while(!dataFilesChecked) delay (1000);
return res;
}
static IPAddress netLocalIP() { return (netMode > 0) ? ETH.localIP() : WiFi.STA.localIP(); }
static IPAddress netGatewayIP() { return (netMode > 0) ? ETH.gatewayIP() : WiFi.STA.gatewayIP(); }
String netMacAddress() { return (netMode > 0) ? ETH.macAddress() : WiFi.STA.macAddress(); }
int netRSSI() { return (netMode == 1) ? 0 : WiFi.STA.RSSI(); }
bool netIsConnected() { return (netMode > 0) ? (ETH.linkUp() && ETH.localIP()) : (WiFi.STA.status() == WL_CONNECTED); }
const char* formatIPstr(bool getAP) {
static char localIP[16] = "";
IPAddress ipLocal = getAP ? WiFi.AP.localIP() : netLocalIP();
sprintf(localIP, "%u.%u.%u.%u", ipLocal[0], ipLocal[1], ipLocal[2], ipLocal[3]);
return localIP;
}
void resetWatchDog(int wdIndex, uint32_t wdTimeout) {
// customised watchdogs for particular tasks
// ping task (0) used as watchdog in case of esp freeze
static bool watchDogStarted[4] = {false, false, false, false};
if (watchDogStarted[wdIndex]) esp_task_wdt_reset();
else {
// setup watchdog on first call
esp_task_wdt_deinit();
esp_task_wdt_config_t twdt_config = {
.timeout_ms = wdTimeout,
.idle_core_mask = (1 << portNUM_PROCESSORS) - 1,
.trigger_panic = true, // panic abort on watchdog alert (contains wdt_isr)
};
esp_task_wdt_init(&twdt_config);
esp_task_wdt_add(NULL);
if (esp_task_wdt_status(NULL) == ESP_OK) {
watchDogStarted[wdIndex] = true;
esp_task_wdt_reset();
LOG_INF("WatchDog started for task: %s", pcTaskGetName(NULL));
} else LOG_ERR("WatchDog failed to start for task: %s ", pcTaskGetName(NULL));
}
}
static void pingSuccess(esp_ping_handle_t hdl, void *args) {
//uint32_t elapsed_time;
//esp_ping_get_profile(hdl, ESP_PING_PROF_TIMEGAP, &elapsed_time, sizeof(elapsed_time));
if (DEBUG_MEM) {
static uint32_t minStack = UINT32_MAX;
uint32_t freeStack = (uint32_t)uxTaskGetStackHighWaterMark(NULL);
if (freeStack < minStack) {
minStack = freeStack;
if (freeStack < MIN_STACK_FREE) LOG_WRN("Task ping stack space only: %lu", freeStack);
else LOG_INF("Task ping stack space reduced to: %lu", freeStack);
}
}
resetWatchDog(0, wifiTimeoutSecs * 1000 * 2);
if (dataFilesChecked) resetCrashLoop();
runStatusCheck();
}
static void pingTimeout(esp_ping_handle_t hdl, void *args) {
// a ping check is used because esp may maintain a connection to gateway which may be unuseable, which is detected by ping failure
// but some routers may not respond to ping - https://github.com/s60sc/ESP32-CAM_MJPEG2SD/issues/221
// so setting usePing to false ignores ping failure if connection still present
resetWatchDog(0, wifiTimeoutSecs * 1000 * 2);
if (netMode > 0) {
if (usePing) {
LOG_WRN("Failed to ping gateway, restart ethernet ...");
startNetwork(false);
} else {
if (netIsConnected()) runStatusCheck();
else {
LOG_WRN("Disconnected, restart ethernet ...");
startNetwork(false);
}
}
} else {
if (strlen(ST_SSID)) {
wl_status_t wStat = WiFi.STA.status();
if (wStat != WL_NO_SSID_AVAIL && wStat != WL_NO_SHIELD) {
if (usePing) {
LOG_WRN("Failed to ping gateway, restart wifi ...");
startWifi(false);
} else {
if (wStat == WL_CONNECTED) runStatusCheck();
else {
LOG_WRN("Disconnected, restart wifi ...");
startWifi(false);
}
}
}
}
}
}
static bool startPing() {
IPAddress ipAddr = netGatewayIP();
if (!ipAddr) return false; // don't start ping until gateway is known
ip_addr_t pingDest;
IP_ADDR4(&pingDest, ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);
esp_ping_config_t pingConfig = ESP_PING_DEFAULT_CONFIG();
pingConfig.target_addr = pingDest;
pingConfig.count = ESP_PING_COUNT_INFINITE;
pingConfig.interval_ms = wifiTimeoutSecs * 1000;
pingConfig.timeout_ms = 5000;
pingConfig.task_stack_size = PING_STACK_SIZE;
pingConfig.task_prio = 1;
// set ping task callback functions
esp_ping_callbacks_t cbs;
cbs.on_ping_success = pingSuccess;
cbs.on_ping_timeout = pingTimeout;
cbs.on_ping_end = NULL;
cbs.cb_args = NULL;
esp_ping_new_session(&pingConfig, &cbs, &pingHandle);
esp_ping_start(pingHandle);
LOG_INF("Started ping monitoring - %s", usePing ? "On" : "Off");
debugMemory("startPing");
return true;
}
void stopPing() {
if (pingHandle != NULL) {
esp_ping_stop(pingHandle);
esp_ping_delete_session(pingHandle);
pingHandle = NULL;
}
}
#define EXT_IP_HOST "ipwhois.app"
#define EXT_IP_PATH "/json"
char extIP[MAX_IP_LEN] = "Not assigned"; // router external IP
bool doGetExtIP = true;
void getExtIP() {
// Get external IP address
if (doGetExtIP) {
NetworkClient hclient;
if (remoteServerConnect(hclient, EXT_IP_HOST, HTTP_PORT, GETEXTIP)) {
HTTPClient http;
int httpCode = HTTP_CODE_NOT_FOUND;
if (http.begin(hclient, EXT_IP_HOST, HTTP_PORT, EXT_IP_PATH)) {
httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
char jsonVal[FILE_NAME_LEN] = "";
if (getJsonValue(payload.c_str(), "ip", jsonVal)) {
if (strcmp(jsonVal, extIP)) {
// external IP changed
strncpy(extIP, jsonVal, sizeof(extIP) - 1);
updateStatus("extIP", extIP);
updateStatus("save", "0");
externalAlert("External IP changed", extIP);
} else LOG_INF("External IP: %s", extIP);
} else LOG_WRN("'ip' field not present");
if (getJsonValue(payload.c_str(), "latitude", jsonVal)) latLon[0] = atof(jsonVal);
else LOG_WRN("'latitude' field not present");
if (getJsonValue(payload.c_str(), "longitude", jsonVal)) latLon[1] = atof(jsonVal);
else LOG_WRN("'longitude' field not present");
} else LOG_WRN("External IP request failed, error: %s", http.errorToString(httpCode).c_str());
if (httpCode != HTTP_CODE_OK) doGetExtIP = false;
http.end();
}
remoteServerClose(hclient);
}
}
}
/************** generic NetworkClientSecure functions ******************/
#include <esp_crt_bundle.h>
extern const uint8_t x509_certificate_bundle_start[] __asm__("_binary_x509_crt_bundle_start");
extern const uint8_t x509_certificate_bundle_end[] __asm__("_binary_x509_crt_bundle_end");
static uint8_t failCounts[REMFAILCNT] = {0};
void remoteServerClose(Client& client) {
uint32_t startAttempt = millis();
while (client.available() > 0 && (millis() - startAttempt < 1000)) client.read();
if (client.connected()) client.stop();
}
static bool checkFailureThreshold(const char* host, uint8_t idx) {
// Check failure threshold
if (failCounts[idx] >= MAX_FAIL) {
if (failCounts[idx] == MAX_FAIL) {
LOG_ERR("Abandon %s connection attempt until next rollover", host);
failCounts[idx] = MAX_FAIL + 1;
}
return false;
}
return true;
}
bool remoteServerConnect(Client& client, const char* host, uint16_t port, uint8_t idx) {
if (client.connected()) return true;
// first check remote server exists / is available
NetworkClient tcp;
bool ok = tcp.connect(host, port);
tcp.stop();
if (!ok) {
LOG_WRN("Server %s not reachable", host);
return false;
}
if (checkFailureThreshold(host, idx)) {
// Connection loop
uint32_t start = millis();
while (!client.connected()) {
if (client.connect(host, port)) break;
if (millis() - start > (uint32_t)responseTimeoutSecs * 1000) break;
delay(500);
}
// Final status & error reporting
if (client.connected()) {
failCounts[idx] = 0;
return true;
}
failCounts[idx]++;
LOG_WRN("Failed to connect to %s", host);
}
return false;
}
static bool remoteServerConnectSec(NetworkClientSecure& client, const char* host, uint16_t port, uint8_t idx) {
if (checkFailureThreshold(host, idx)) {
// Additional operations for secure client
waitForNTPsync();
if (timeSynchronized || !useSecure) {
if (ESP.getFreeHeap() <= TLS_HEAP) {
LOG_WRN("Insufficient heap %s for %s TLS session", fmtSize(ESP.getFreeHeap()), host);
failCounts[idx]++;
return false;
}
if (remoteServerConnect(static_cast<Client&>(client), host, port, idx)) return true;
else {
// failed to connect in allocated time
// 'Memory allocation failed' indicates lack of heap space
// 'Generic error' can indicate DNS failure
char buf[100];
int err = client.lastError(buf, sizeof(buf));
LOG_WRN("Failed to %s connect to %s: Err %d: %s", useSecure ? "securely" : "insecurely", host, err, buf);
return false;
}
} else LOG_WRN("Remote server certificate checks require a valid device datetime");
}
return false;
}
bool remoteServerConnect(NetworkClientSecure& client, const char* host, uint16_t port, const char* cert, uint8_t idx) {
// Configure security using own public certs
if (useSecure) client.setCACert(cert);
else client.setInsecure();
return remoteServerConnectSec(client, host, port, idx);
}
bool remoteServerConnect(NetworkClientSecure& client, const char* host, uint16_t port, uint8_t idx) {
// Configure security using certs from IDF ESP x509 Certificate Bundle
if (useSecure) client.setCACertBundle(x509_certificate_bundle_start, (size_t)(x509_certificate_bundle_end - x509_certificate_bundle_start));
else client.setInsecure();
return remoteServerConnectSec(client, host, port, idx);
}
void remoteServerReset() {
// reset fail counts
for (uint8_t i = 0; i < REMFAILCNT; i++) failCounts[i] = 0;
}
/************************** NTP **************************/
// Needs to be a time zone string from: https://raw.githubusercontent.com/nayarsystems/posix_tz_db/master/zones.csv
uint8_t alarmHour = 1;
time_t getEpoch() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
void dateFormat(char* inBuff, size_t inBuffLen, bool isFolder) {
// construct filename from date/time
time_t currEpoch = getEpoch();
if (isFolder) strftime(inBuff, inBuffLen, "/%Y%m%d", localtime(&currEpoch));
else strftime(inBuff, inBuffLen, "/%Y%m%d/%Y%m%d_%H%M%S", localtime(&currEpoch));
}
static void showLocalTime(const char* timeSrc) {
time_t currEpoch = getEpoch();
char timeFormat[20];
strftime(timeFormat, sizeof(timeFormat), "%d/%m/%Y %H:%M:%S", localtime(&currEpoch));
LOG_INF("Got current time from %s: %s with tz: %s", timeSrc, timeFormat, timezone);
}
static bool waitForNTPsync(int maxRetries, uint32_t perTryTimeoutMs) {
// wait for local time to sync with NTP server
if (!timeSynchronized) {
struct tm timeinfo;
int retry = 0;
while (!getLocalTime(&timeinfo, perTryTimeoutMs) && retry < maxRetries) retry++;
if (retry >= maxRetries) {
LOG_WRN("Time sync with NTP failed, retry");
return false;
}
LOG_INF("Time synced with NTP: %s, using timezone: %s", ntpServer, timezone);
timeSynchronized = true;
}
return true;
}
void syncToBrowser(uint32_t browserUTC) {
// Synchronize to browser clock if out of sync
if (!timeSynchronized) {
struct timeval tv;
tv.tv_sec = browserUTC;
settimeofday(&tv, NULL);
setenv("TZ", timezone, 1);
tzset();
showLocalTime("browser");
}
}
void formatElapsedTime(char* timeStr, uint32_t timeVal, bool noDays) {
// elapsed time that app has been running
uint32_t secs = timeVal / 1000; //convert milliseconds to seconds
uint32_t mins = secs / 60; //convert seconds to minutes
uint32_t hours = mins / 60; //convert minutes to hours
uint32_t days = hours / 24; //convert hours to days
secs = secs - (mins * 60); //subtract the converted seconds to minutes in order to display 59 secs max
mins = mins - (hours * 60); //subtract the converted minutes to hours in order to display 59 minutes max
hours = hours - (days * 24); //subtract the converted hours to days in order to display 23 hours max
if (noDays) sprintf(timeStr, "%02lu:%02lu:%02lu", hours, mins, secs);
else sprintf(timeStr, "%lu-%02lu:%02lu:%02lu", days, hours, mins, secs);
}
static time_t setAlarm(uint8_t alarmHour) {
// calculate future alarm datetime based on current datetime
// ensure relevant timezone identified (default GMT0)
time_t currEpoch = getEpoch();
struct tm* timeinfo = localtime(&currEpoch);
// set alarm date & time for next given hour
int nextDay = 0; // try same day then next day
do {
timeinfo->tm_mday += nextDay;
timeinfo->tm_hour = alarmHour;
timeinfo->tm_min = 0;
timeinfo->tm_sec = 0;
nextDay = 1;
} while (mktime(timeinfo) < currEpoch);
char inBuff[30];
strftime(inBuff, sizeof(inBuff), "%d/%m/%Y %H:%M:%S", timeinfo);
LOG_INF("Alarm scheduled at %s", inBuff);
// return future alarm time as epoch seconds
return mktime(timeinfo);
}
bool checkAlarm() {
// call from appPing() to check if daily alarm time at given hour has occurred
static time_t rolloverEpoch = 0;
if (timeSynchronized && getEpoch() >= rolloverEpoch) {
// alarm time reached, unless first call
bool notInit = (rolloverEpoch == 0) ? false : true;
rolloverEpoch = setAlarm(alarmHour); // set next alarm time
return notInit;
}
return false;
}
/****************** weekly scheduled restart ******************/
// restart c. 02:00 every Tuesday (local time per 'timezone' setting), to clear any
// long term memory fragmentation. If NTP time is never obtained, falls back to a
// restart 7 days after boot, based on millis() uptime.
#define RESTART_WDAY 2 // struct tm tm_wday: 0=Sun, 1=Mon, 2=Tue, ...
#define RESTART_HOUR 2 // 02:00
#define MIN_RESTART_GAP_SECS (24UL * 60 * 60) // ignore a scheduled restart if the last one was more recent than this
#define FALLBACK_UPTIME_MS (7UL * 24 * 60 * 60 * 1000UL) // 7 days, compared against millis() (wraps safely after c. 49.7 days)
// last scheduled restart time (epoch secs), guarding against a runaway restart loop caused
// eg by a miscalculated next-restart time. RTC_DATA_ATTR is reinitialised on ESP.restart()
// (it only survives deep sleep wake), so RTC_NOINIT_ATTR + a magic number validity flag is
// used instead, matching the messageLog/crashLoop pattern in utilsLog.cpp - this does mean it
// contains random data on a genuine power up, which lastScheduledRestartValid guards against
RTC_NOINIT_ATTR time_t lastScheduledRestartEpoch;
RTC_NOINIT_ATTR uint32_t lastScheduledRestartValid;
static time_t nextWeeklyRestartEpoch(time_t fromEpoch) {
// next occurrence of RESTART_WDAY at RESTART_HOUR:00:00, strictly after fromEpoch
struct tm timeinfo = *localtime(&fromEpoch);
int daysAhead = (RESTART_WDAY - timeinfo.tm_wday + 7) % 7;
timeinfo.tm_mday += daysAhead;
timeinfo.tm_hour = RESTART_HOUR;
timeinfo.tm_min = 0;
timeinfo.tm_sec = 0;
timeinfo.tm_isdst = -1;
time_t nextEpoch = mktime(&timeinfo);
if (nextEpoch <= fromEpoch) nextEpoch += 7UL * 24 * 60 * 60; // today is restart day but time already passed
return nextEpoch;
}
static void checkScheduledRestart() {
// call regularly (from statusCheckTask()) to trigger the weekly restart, or the NTP-unavailable fallback
static time_t nextRestartEpoch = 0;
static bool fallbackArmed = true;
if (timeSynchronized) {
time_t nowEpoch = getEpoch();
if (!nextRestartEpoch) {
nextRestartEpoch = nextWeeklyRestartEpoch(nowEpoch);
char inBuff[30];
strftime(inBuff, sizeof(inBuff), "%d/%m/%Y %H:%M:%S", localtime(&nextRestartEpoch));
LOG_INF("Next scheduled weekly restart due: %s", inBuff);
}
if (nowEpoch >= nextRestartEpoch) {
bool noPriorRestart = (lastScheduledRestartValid != MAGIC_NUM);
if (noPriorRestart || (nowEpoch - lastScheduledRestartEpoch) >= (time_t)MIN_RESTART_GAP_SECS) {
lastScheduledRestartEpoch = nowEpoch;
lastScheduledRestartValid = MAGIC_NUM;
LOG_ALT("Weekly scheduled restart due (Tuesday %02u:00 %s)", RESTART_HOUR, timezone);
doRestart("weekly scheduled restart");
} else {
LOG_WRN("Weekly scheduled restart due, but skipped as last restart was under 24 hrs ago");
nextRestartEpoch = nextWeeklyRestartEpoch(nowEpoch); // reschedule so this isn't retried every cycle
}
}
} else if (fallbackArmed && millis() >= FALLBACK_UPTIME_MS) {
// NTP time never obtained - fallback to uptime based restart
fallbackArmed = false; // guard re-entry until actual reboot occurs
LOG_ALT("Weekly scheduled restart fallback: 7 days uptime reached without NTP sync");
doRestart("uptime fallback restart (no NTP sync)");
}
}
static void statusCheckTask(void* parameter) {
while (true) {
// regular status checks
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
if (!dataFilesChecked) checkDataFiles();
if (!timeSynchronized) waitForNTPsync();
if (appSetupDone) doAppPing(timeSynchronized);
checkScheduledRestart();
#if INCLUDE_MQTT
if (mqtt_active) startMqttClient();
#endif
}
}
static inline void runStatusCheck() {
if (statusCheckHandle) xTaskNotifyGive(statusCheckHandle);
}
/********************** misc functions ************************/
bool changeExtension(char* fileName, const char* newExt) {
// replace original file extension with supplied extension (buffer must be large enough)
size_t inNamePtr = strlen(fileName);
// find '.' before extension text
while (inNamePtr > 0 && fileName[inNamePtr] != '.') inNamePtr--;
inNamePtr++;
size_t extLen = strlen(newExt);
memcpy(fileName + inNamePtr, newExt, extLen);
fileName[inNamePtr + extLen] = 0;
return (inNamePtr > 1) ? true : false;
}
void showProgress(const char* marker) {
// show progess as dots or supplied marker
static uint8_t dotCnt = 0;
LOG_SEND("%s", marker); // progress marker
if (++dotCnt >= DOT_MAX) {
dotCnt = 0;
LOG_SEND("\n");
}
}
bool calcProgress(int progressVal, int totalVal, int percentReport, uint8_t &pcProgress) {
// calculate percentage progress, only report back on percentReport boundary
uint8_t percentage = (progressVal * 100) / totalVal;
if (percentage >= pcProgress + percentReport) {
pcProgress = percentage;
return true;
} else return false;
}
bool urlEncode(const char* inVal, char* encoded, size_t maxSize) {
int encodedLen = 0;
char hexTable[] = "0123456789ABCDEF";
while (*inVal) {
if (isalnum(*inVal) || strchr("$-_.+!*'(),:@~#", *inVal)) {
*encoded++ = *inVal;
encodedLen++;
} else {
encodedLen += 3;
*encoded++ = '%';
*encoded++ = hexTable[(*inVal) >> 4];
*encoded++ = hexTable[*inVal & 0xf];
}
if (encodedLen >= maxSize) return false; // Buffer overflow
inVal++;
}
*encoded = 0;
return true;
}
void urlDecode(char* inVal) {
// replace url encoded characters in-place
// decoded output is always equal or shorter than input
char* src = inVal;
char* dst = inVal;
while (*src) {
if (*src == '%' && isxdigit((unsigned char)*(src+1)) && isxdigit((unsigned char)*(src+2))) {
// decode %XX hex sequence
char hex[3] = {*(src+1), *(src+2), 0};
*dst++ = (char)strtoul(hex, nullptr, 16);
src += 3;
} else if (*src == '+') {
// + is encoded space in form data
*dst++ = ' ';
src++;
} else {
*dst++ = *src++;
}
}
*dst = 0; // NUL terminate
}
void listBuff (const uint8_t* b, size_t len) {
// output buffer content as hex, 16 bytes per line
if (!len || !b) LOG_WRN("Nothing to print");
else {
for (size_t i = 0; i < len; i += 16) {
int linelen = (len - i) < 16 ? (len - i) : 16;
for (size_t k = 0; k < linelen; k++) LOG_SEND(" %02x", b[i+k]);
puts(" ");
}
}
}
size_t isSubArray(uint8_t* haystack, uint8_t* needle, size_t hSize, size_t nSize) {
// find a subarray (needle) in another array (haystack)
size_t h = 0, n = 0; // Two pointers to traverse the arrays
// Traverse both arrays simultaneously
while (h < hSize && n < nSize) {
// If element matches, increment both pointers
if (haystack[h] == needle[n]) {
h++;
n++;
// If needle is completely traversed
if (n == nSize) return h; // position of end of needle
} else {
// if not, increment h and reset n
h = h - n + 1;
n = 0;
}
}
return 0; // not found
}
void removeChar(char* s, char c) {
// remove specified character from string
int writer = 0, reader = 0;
while (s[reader]) {
if (s[reader] != c) s[writer++] = s[reader];
reader++;
}
s[writer] = 0;
}
void replaceChar(char* s, char c, char r) {
// replace specified character in string
int reader = 0;
while (s[reader]) {
if (s[reader] == c) s[reader] = r;
reader++;
}
}
char* fmtSize (uint64_t sizeVal) {
// format size according to magnitude
// only one call per format string
static char returnStr[20];
if (sizeVal < 50 * 1024) sprintf(returnStr, "%llu bytes", sizeVal);
else if (sizeVal < ONEMEG) sprintf(returnStr, "%lluKB", sizeVal / 1024);