This repository has been archived by the owner on Jan 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
WiFiManager_NINA_Lite_SAMD.h
2202 lines (1684 loc) · 64.1 KB
/
WiFiManager_NINA_Lite_SAMD.h
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
/*********************************************************************************************************************************
WiFiManager_NINA_Lite_SAMD.h
For SAMD boards using WiFiNINA modules/shields, using much less code to support boards with smaller memory
WiFiManager_NINA_Lite is a library for the Mega, Teensy, SAM DUE, SAMD and STM32 boards
(https://github.com/khoih-prog/WiFiManager_NINA_Lite) to enable store Credentials in EEPROM/LittleFS for easy
configuration/reconfiguration and autoconnect/autoreconnect of WiFi and other services without Hardcoding.
Built by Khoi Hoang https://github.com/khoih-prog/WiFiManager_NINA_Lite
Licensed under MIT license
Version: 1.7.1
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 26/03/2020 Initial coding
...
1.6.0 K Hoang 05/01/2022 Configurable WIFI_RECON_INTERVAL. Add support to RP2040 using arduino-pico core
1.6.1 K Hoang 26/01/2022 Update to be compatible with new FlashStorage libraries. Add support to more SAMD/STM32 boards
1.6.2 K Hoang 18/02/2022 Optional Board_Name in Menu. Optimize code by using passing by reference
1.6.3 K Hoang 20/02/2022 Add optional CONFIG_MODE_LED. Add function to signal system is in Config Portal mode.
1.7.0 K Hoang 27/04/2022 Use WiFiMulti_Generic library for auto-checking / auto-reconnecting MultiWiFi
1.7.1 K Hoang 27/04/2022 Fix bug for RP2040 using arduino-pico core
**********************************************************************************************************************************/
#ifndef WiFiManager_NINA_Lite_SAMD_h
#define WiFiManager_NINA_Lite_SAMD_h
#if ( defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRWIFI1010) \
|| defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_SAMD_MKRFox1200) || defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) \
|| defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRNB1500) || defined(ARDUINO_SAMD_MKRVIDOR4000) \
|| defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD51__) || defined(__SAMD51J20A__) \
|| defined(__SAMD51J19A__) || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) \
|| defined(__SAMD21E15A__) || defined(__SAMD21E16A__) || defined(__SAMD21E17A__) || defined(__SAMD21E18A__) \
|| defined(__SAMD21G15A__) || defined(__SAMD21G16A__) || defined(__SAMD21G17A__) || defined(__SAMD21G18A__) \
|| defined(__SAMD21J15A__) || defined(__SAMD21J16A__) || defined(__SAMD21J17A__) || defined(__SAMD21J18A__) )
#if defined(WIFININA_USE_SAMD)
#undef WIFININA_USE_SAMD
#endif
#define WIFININA_USE_SAMD true
#else
#error This code is intended to run on the SAMD platform! Please check your Tools->Board setting.
#endif
#ifndef WIFIMANAGER_NINA_LITE_VERSION
#define WIFIMANAGER_NINA_LITE_VERSION "WiFiManager_NINA_Lite v1.7.1"
#define WIFIMANAGER_NINA_LITE_VERSION_MAJOR 1
#define WIFIMANAGER_NINA_LITE_VERSION_MINOR 7
#define WIFIMANAGER_NINA_LITE_VERSION_PATCH 1
#define WIFIMANAGER_NINA_LITE_VERSION_INT 1007001
#endif
#include <WiFiMulti_Generic.h>
#include <WiFiWebServer.h>
WiFiMulti_Generic wifiMulti;
// Include EEPROM-like API for FlashStorage
#include <FlashStorage_SAMD.h> //https://github.com/khoih-prog/FlashStorage_SAMD
#include <WiFiManager_NINA_Lite_Debug.h>
#ifndef USING_CUSTOMS_STYLE
#define USING_CUSTOMS_STYLE false
#endif
#ifndef USING_CUSTOMS_HEAD_ELEMENT
#define USING_CUSTOMS_HEAD_ELEMENT false
#endif
#ifndef USING_CORS_FEATURE
#define USING_CORS_FEATURE false
#endif
//////////////////////////////////////////////
// New from v1.3.0
// KH, Some minor simplification
#if !defined(SCAN_WIFI_NETWORKS)
#define SCAN_WIFI_NETWORKS true //false
#endif
#if SCAN_WIFI_NETWORKS
#if !defined(MANUAL_SSID_INPUT_ALLOWED)
#define MANUAL_SSID_INPUT_ALLOWED true
#endif
#if !defined(MAX_SSID_IN_LIST)
#define MAX_SSID_IN_LIST 10
#elif (MAX_SSID_IN_LIST < 2)
#warning Parameter MAX_SSID_IN_LIST defined must be >= 2 - Reset to 10
#undef MAX_SSID_IN_LIST
#define MAX_SSID_IN_LIST 10
#elif (MAX_SSID_IN_LIST > 15)
#warning Parameter MAX_SSID_IN_LIST defined must be <= 15 - Reset to 10
#undef MAX_SSID_IN_LIST
#define MAX_SSID_IN_LIST 10
#endif
#else
#warning SCAN_WIFI_NETWORKS disabled
#endif
///////// NEW for DRD /////////////
// These defines must be put before #include <DoubleResetDetector_Generic.h>
// to select where to store DoubleResetDetector_Generic's variable.
// Otherwise, library will use default EEPROM storage
#define DRD_FLAG_DATA_SIZE 4
#ifndef DRD_GENERIC_DEBUG
#define DRD_GENERIC_DEBUG false
#endif
#include <DoubleResetDetector_Generic.h> //https://github.com/khoih-prog/DoubleResetDetector_Generic
// Number of seconds after reset during which a
// subseqent reset will be considered a double reset.
#define DRD_TIMEOUT 10
// RTC Memory Address for the DoubleResetDetector_Generic to use
#define DRD_ADDRESS 0
DoubleResetDetector_Generic* drd;
///////// NEW for DRD /////////////
//NEW
#define MAX_ID_LEN 5
#define MAX_DISPLAY_NAME_LEN 16
typedef struct
{
char id [MAX_ID_LEN + 1];
char displayName [MAX_DISPLAY_NAME_LEN + 1];
char *pdata;
uint8_t maxlen;
} MenuItem;
//
#if USE_DYNAMIC_PARAMETERS
#warning Using Dynamic Parameters
///NEW
extern uint16_t NUM_MENU_ITEMS;
extern MenuItem myMenuItems [];
bool *menuItemUpdated = NULL;
#else
#warning Not using Dynamic Parameters
#endif
#define SSID_MAX_LEN 32
// WPA2 passwords can be up to 63 characters long.
#define PASS_MAX_LEN 64
typedef struct
{
char wifi_ssid[SSID_MAX_LEN];
char wifi_pw [PASS_MAX_LEN];
} WiFi_Credentials;
#define NUM_WIFI_CREDENTIALS 2
#if USING_BOARD_NAME
// Configurable items besides fixed Header, just add board_name
#define NUM_CONFIGURABLE_ITEMS ( ( 2 * NUM_WIFI_CREDENTIALS ) + 1 )
#else
// Configurable items besides fixed Header, just add board_name
#define NUM_CONFIGURABLE_ITEMS ( ( 2 * NUM_WIFI_CREDENTIALS ))
#endif
////////////////
#define HEADER_MAX_LEN 16
#define BOARD_NAME_MAX_LEN 24
typedef struct Configuration
{
char header [HEADER_MAX_LEN];
WiFi_Credentials WiFi_Creds [NUM_WIFI_CREDENTIALS];
char board_name [BOARD_NAME_MAX_LEN];
int checkSum;
} WiFiNINA_Configuration;
// Currently CONFIG_DATA_SIZE = 236 = (16 + 96 * 2 + 4 + 24)
uint16_t CONFIG_DATA_SIZE = sizeof(WiFiNINA_Configuration);
extern bool LOAD_DEFAULT_CONFIG_DATA;
extern WiFiNINA_Configuration defaultConfig;
// -- HTML page fragments
const char WIFININA_HTML_HEAD_START[] /*PROGMEM*/ = "<!DOCTYPE html><html><head><title>SAMD_WM_NINA_Lite</title>";
const char WIFININA_HTML_HEAD_STYLE[] /*PROGMEM*/ =
"<style>div,input,select{padding:5px;font-size:1em;}input,select{width:95%;}body{text-align:center;}button{background-color:#16A1E7;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;}fieldset{border-radius:0.3rem;margin:0px;}</style>";
#if USING_BOARD_NAME
const char WIFININA_HTML_HEAD_END[] /*PROGMEM*/ =
"</head><div style='text-align:left;display:inline-block;min-width:260px;'>\
<fieldset><div><label>*WiFi SSID</label><div>[[input_id]]</div></div>\
<div><label>*PWD (8+ chars)</label><input value='[[pw]]' id='pw'><div></div></div>\
<div><label>*WiFi SSID1</label><div>[[input_id1]]</div></div>\
<div><label>*PWD1 (8+ chars)</label><input value='[[pw1]]' id='pw1'><div></div></div></fieldset>\
<fieldset><div><label>Board Name</label><input value='[[nm]]' id='nm'><div></div></div></fieldset>"; // DO NOT CHANGE THIS STRING EVER!!!!
#else
const char WIFININA_HTML_HEAD_END[] /*PROGMEM*/ =
"</head><div style='text-align:left;display:inline-block;min-width:260px;'>\
<fieldset><div><label>*WiFi SSID</label><div>[[input_id]]</div></div>\
<div><label>*PWD (8+ chars)</label><input value='[[pw]]' id='pw'><div></div></div>\
<div><label>*WiFi SSID1</label><div>[[input_id1]]</div></div>\
<div><label>*PWD1 (8+ chars)</label><input value='[[pw1]]' id='pw1'><div></div></div></fieldset>"; // DO NOT CHANGE THIS STRING EVER!!!!
#endif
const char WIFININA_HTML_INPUT_ID[] /*PROGMEM*/ = "<input value='[[id]]' id='id'>";
const char WIFININA_HTML_INPUT_ID1[] /*PROGMEM*/ = "<input value='[[id1]]' id='id1'>";
const char WIFININA_FLDSET_START[] /*PROGMEM*/ = "<fieldset>";
const char WIFININA_FLDSET_END[] /*PROGMEM*/ = "</fieldset>";
const char WIFININA_HTML_PARAM[] /*PROGMEM*/ =
"<div><label>{b}</label><input value='[[{v}]]' id='{i}'><div></div></div>";
const char WIFININA_HTML_BUTTON[] /*PROGMEM*/ = "<button onclick='sv()'>Save</button></div>";
#if USING_BOARD_NAME
const char WIFININA_HTML_SCRIPT[] /*PROGMEM*/ = "<script id=\"jsbin-javascript\">\
function udVal(key,val){var request=new XMLHttpRequest();var url='/?key='+key+'&value='+encodeURIComponent(val);\
request.open('GET',url,false);request.send(null);}\
function sv(){udVal('id',document.getElementById('id').value);udVal('pw',document.getElementById('pw').value);\
udVal('id1',document.getElementById('id1').value);udVal('pw1',document.getElementById('pw1').value);\
udVal('nm',document.getElementById('nm').value);";
#else
const char WIFININA_HTML_SCRIPT[] /*PROGMEM*/ = "<script id=\"jsbin-javascript\">\
function udVal(key,val){var request=new XMLHttpRequest();var url='/?key='+key+'&value='+encodeURIComponent(val);\
request.open('GET',url,false);request.send(null);}\
function sv(){udVal('id',document.getElementById('id').value);udVal('pw',document.getElementById('pw').value);\
udVal('id1',document.getElementById('id1').value);udVal('pw1',document.getElementById('pw1').value);";
#endif
const char WIFININA_HTML_SCRIPT_ITEM[] /*PROGMEM*/ = "udVal('{d}',document.getElementById('{d}').value);";
const char WIFININA_HTML_SCRIPT_END[] /*PROGMEM*/ = "alert('Updated');}</script>";
const char WIFININA_HTML_END[] /*PROGMEM*/ = "</html>";
#if SCAN_WIFI_NETWORKS
const char WIFININA_SELECT_START[] /*PROGMEM*/ = "<select id=";
const char WIFININA_SELECT_END[] /*PROGMEM*/ = "</select>";
const char WIFININA_DATALIST_START[] /*PROGMEM*/ = "<datalist id=";
const char WIFININA_DATALIST_END[] /*PROGMEM*/ = "</datalist>";
const char WIFININA_OPTION_START[] /*PROGMEM*/ = "<option>";
const char WIFININA_OPTION_END[] /*PROGMEM*/ = ""; // "</option>"; is not required
const char WIFININA_NO_NETWORKS_FOUND[] /*PROGMEM*/ = "No suitable WiFi networks available!";
#endif
//////////////////////////////////////////
//KH Add repeatedly used const
//KH, from v1.1.0
const char WM_HTTP_HEAD_CL[] PROGMEM = "Content-Length";
const char WM_HTTP_HEAD_TEXT_HTML[] PROGMEM = "text/html";
const char WM_HTTP_HEAD_TEXT_PLAIN[] PROGMEM = "text/plain";
const char WM_HTTP_CACHE_CONTROL[] PROGMEM = "Cache-Control";
const char WM_HTTP_NO_STORE[] PROGMEM = "no-cache, no-store, must-revalidate";
const char WM_HTTP_PRAGMA[] PROGMEM = "Pragma";
const char WM_HTTP_NO_CACHE[] PROGMEM = "no-cache";
const char WM_HTTP_EXPIRES[] PROGMEM = "Expires";
const char WM_HTTP_CORS[] PROGMEM = "Access-Control-Allow-Origin";
const char WM_HTTP_CORS_ALLOW_ALL[] PROGMEM = "*";
//////////////////////////////////////////////
// New from v1.2.0
#if !defined(REQUIRE_ONE_SET_SSID_PW)
#define REQUIRE_ONE_SET_SSID_PW false
#endif
#define PASSWORD_MIN_LEN 8
//////////////////////////////////////////////
String IPAddressToString(const IPAddress& _address)
{
String str = String(_address[0]);
str += ".";
str += String(_address[1]);
str += ".";
str += String(_address[2]);
str += ".";
str += String(_address[3]);
return str;
}
class WiFiManager_NINA_Lite
{
public:
WiFiManager_NINA_Lite()
{
// check for the presence of the shield
#if USE_WIFI101
if (WiFi.status() == WL_NO_SHIELD)
#else
if (WiFi.status() == WL_NO_MODULE)
#endif
{
WN_LOGERROR(F("NoWiFi"));
}
}
~WiFiManager_NINA_Lite()
{
if (server)
{
delete server;
#if SCAN_WIFI_NETWORKS
if (indices)
{
free(indices); //indices array no longer required so free memory
}
#endif
}
}
bool connectWiFi(const char* ssid, const char* pass)
{
WN_LOGERROR1(F("Con2:"), ssid);
setHostname();
if ( WiFi.begin(ssid, pass) == WL_CONNECTED )
{
displayWiFiData();
}
else
{
WN_LOGERROR(F("NoW"));
return false;
}
WN_LOGERROR(F("WOK"));
wifi_connected = true;
return true;
}
void begin(const char* ssid,
const char* pass )
{
WN_LOGERROR(F("conW"));
connectWiFi(ssid, pass);
}
void begin(const char *iHostname = "")
{
#define RETRY_TIMES_CONNECT_WIFI 3
#if USING_CONFIG_MODE_LED
//Turn OFF
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LED_OFF);
#endif
if (iHostname[0] == 0)
{
String randomNum = String(random(0xFFFFFF), HEX);
randomNum.toUpperCase();
String _hostname = "SAMD-WiFiNINA-" + randomNum;
_hostname.toUpperCase();
getRFC952_hostname(_hostname.c_str());
}
else
{
// Prepare and store the hostname only not NULL
getRFC952_hostname(iHostname);
}
WN_LOGERROR1(F("Hostname="), RFC952_hostname);
//////
//// New DRD ////
drd = new DoubleResetDetector_Generic(DRD_TIMEOUT, DRD_ADDRESS);
bool noConfigPortal = true;
if (drd->detectDoubleReset())
{
WN_LOGERROR(F("Double Reset Detected"));
noConfigPortal = false;
}
//// New DRD ////
if (LOAD_DEFAULT_CONFIG_DATA)
{
WN_LOGERROR(F("======= Start Default Config Data ======="));
displayConfigData(defaultConfig);
}
hadConfigData = getConfigData();
isForcedConfigPortal = isForcedCP();
//// New DRD/MRD ////
// noConfigPortal when getConfigData() OK and no MRD/DRD'ed
if (hadConfigData && noConfigPortal && (!isForcedConfigPortal) )
{
hadConfigData = true;
wifiMulti_addAP();
if (connectMultiWiFi(RETRY_TIMES_CONNECT_WIFI))
{
WN_LOGERROR(F("b:WOK"));
}
else
{
WN_LOGERROR(F("b:NoW"));
// failed to connect to WiFi, will start configuration mode
startConfigurationMode();
}
}
else
{
WN_LOGERROR(isForcedConfigPortal ? F("bg: isForcedConfigPortal = true") : F("bg: isForcedConfigPortal = false"));
// If not persistent => clear the flag so that after reset. no more CP, even CP not entered and saved
if (persForcedConfigPortal)
{
WN_LOGERROR1(F("bg:Stay forever in CP:"),
isForcedConfigPortal ? F("Forced-Persistent") : (noConfigPortal ? F("No ConfigDat") : F("DRD/MRD")));
}
else
{
WN_LOGERROR1(F("bg:Stay forever in CP:"),
isForcedConfigPortal ? F("Forced-non-Persistent") : (noConfigPortal ? F("No ConfigDat") : F("DRD/MRD")));
clearForcedCP();
}
//To permit autoreset after timeout if DRD/MRD or non-persistent forced-CP
hadConfigData = isForcedConfigPortal ? true : (noConfigPortal ? false : true);
// failed to connect to WiFi, will start configuration mode
startConfigurationMode();
}
}
#ifndef RETRY_TIMES_RECONNECT_WIFI
#define RETRY_TIMES_RECONNECT_WIFI 2
#else
// Force range of user-defined RETRY_TIMES_RECONNECT_WIFI between 2-5 times
#if (RETRY_TIMES_RECONNECT_WIFI < 2)
#warning RETRY_TIMES_RECONNECT_WIFI too low. Reseting to 2
#undef RETRY_TIMES_RECONNECT_WIFI
#define RETRY_TIMES_RECONNECT_WIFI 2
#elif (RETRY_TIMES_RECONNECT_WIFI > 5)
#warning RETRY_TIMES_RECONNECT_WIFI too high. Reseting to 5
#undef RETRY_TIMES_RECONNECT_WIFI
#define RETRY_TIMES_RECONNECT_WIFI 5
#endif
#endif
#ifndef RESET_IF_CONFIG_TIMEOUT
#define RESET_IF_CONFIG_TIMEOUT true
#endif
#ifndef CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET
#define CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET 10
#else
// Force range of user-defined TIMES_BEFORE_RESET between 2-100
#if (CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET < 2)
#warning CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET too low. Reseting to 2
#undef CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET
#define CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET 2
#elif (CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET > 100)
#warning CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET too high. Resetting to 100
#undef CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET
#define CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET 100
#endif
#endif
#if !defined(WIFI_RECON_INTERVAL)
#define WIFI_RECON_INTERVAL 0 // default 0s between reconnecting WiFi
#else
#if (WIFI_RECON_INTERVAL < 0)
#define WIFI_RECON_INTERVAL 0
#elif (WIFI_RECON_INTERVAL > 600000)
#define WIFI_RECON_INTERVAL 600000 // Max 10min
#endif
#endif
void run()
{
static int retryTimes = 0;
static bool wifiDisconnectedOnce = false;
// Lost connection in running. Give chance to reconfig.
// Check WiFi status every 5s and update status
// Check twice to be sure wifi disconnected is real
static unsigned long checkstatus_timeout = 0;
#define WIFI_STATUS_CHECK_INTERVAL 5000L
static uint32_t curMillis;
curMillis = millis();
//// New DRD ////
// Call the double reset detector loop method every so often,
// so that it can recognise when the timeout expires.
// You can also call drd.stop() when you wish to no longer
// consider the next reset as a double reset.
drd->loop();
//// New DRD ////
if ( !configuration_mode && (curMillis > checkstatus_timeout) )
{
if (WiFi.status() == WL_CONNECTED)
{
wifi_connected = true;
#if USING_CONFIG_MODE_LED
// turn the LED_BUILTIN OFF to tell us we exit configuration mode.
digitalWrite(CONFIG_MODE_LED, LED_OFF);
#endif
}
else
{
if (wifiDisconnectedOnce)
{
wifiDisconnectedOnce = false;
wifi_connected = false;
WN_LOGERROR(F("r:Check&WLost"));
}
else
{
wifiDisconnectedOnce = true;
}
}
checkstatus_timeout = curMillis + WIFI_STATUS_CHECK_INTERVAL;
}
// Lost connection in running. Give chance to reconfig.
if ( !wifi_connected )
{
// If configTimeout but user hasn't connected to configWeb => try to reconnect WiFi
// But if user has connected to configWeb, stay there until done, then reset hardware
if ( configuration_mode && ( configTimeout == 0 || millis() < configTimeout ) )
{
retryTimes = 0;
if (server)
{
//WN_LOGDEBUG(F("r:handleClient"));
server->handleClient();
}
return;
}
else
{
#if RESET_IF_CONFIG_TIMEOUT
// If we're here but still in configuration_mode, permit running TIMES_BEFORE_RESET times before reset hardware
// to permit user another chance to config.
if ( configuration_mode && (configTimeout != 0) )
{
if (++retryTimes <= CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET)
{
WN_LOGERROR1(F("r:WLost&TOut.ConW.Retry#"), retryTimes);
}
else
{
resetFunc(); //call reset
}
}
#endif
// Not in config mode, try reconnecting before forcing to config mode
if ( !wifi_connected )
{
#if (WIFI_RECON_INTERVAL > 0)
static uint32_t lastMillis = 0;
if ( (lastMillis == 0) || (curMillis - lastMillis) > WIFI_RECON_INTERVAL )
{
lastMillis = curMillis;
WN_LOGERROR(F("r:WLost.ReconW"));
if (connectMultiWiFi(RETRY_TIMES_RECONNECT_WIFI))
{
WN_LOGERROR(F("r:WOK"));
}
}
#else
WN_LOGERROR(F("r:WLost.ReconW"));
if (connectMultiWiFi(RETRY_TIMES_RECONNECT_WIFI))
{
WN_LOGERROR(F("r:WOK"));
}
#endif
}
}
}
else if (configuration_mode)
{
configuration_mode = false;
WN_LOGERROR(F("r:gotWBack"));
#if USING_CONFIG_MODE_LED
// turn the LED_BUILTIN OFF to tell us we exit configuration mode.
digitalWrite(CONFIG_MODE_LED, LED_OFF);
#endif
}
}
//////////////////////////////////////////////
void setHostname()
{
if (RFC952_hostname[0] != 0)
{
#if USE_WIFI101
WiFi.hostname(RFC952_hostname);
#elif USE_WIFI_NINA
WiFi.setHostname(RFC952_hostname);
#endif
}
}
//////////////////////////////////////////////
void setConfigPortalIP(const IPAddress& portalIP = IPAddress(192, 168, 4, 1))
{
portal_apIP = portalIP;
}
//////////////////////////////////////////////
#define MIN_WIFI_CHANNEL 1
#define MAX_WIFI_CHANNEL 11 // Channel 13 is flaky, because of bad number 13 ;-)
int setConfigPortalChannel(const int& channel = 1)
{
// If channel < MIN_WIFI_CHANNEL - 1 or channel > MAX_WIFI_CHANNEL => channel = 1
// If channel == 0 => will use random channel from MIN_WIFI_CHANNEL to MAX_WIFI_CHANNEL
// If (MIN_WIFI_CHANNEL <= channel <= MAX_WIFI_CHANNEL) => use it
if ( (channel < MIN_WIFI_CHANNEL - 1) || (channel > MAX_WIFI_CHANNEL) )
AP_channel = 1;
else if ( (channel >= MIN_WIFI_CHANNEL - 1) && (channel <= MAX_WIFI_CHANNEL) )
AP_channel = channel;
return AP_channel;
}
//////////////////////////////////////////////
void setConfigPortal(const String& ssid = "", const String& pass = "")
{
portal_ssid = ssid;
portal_pass = pass;
}
//////////////////////////////////////////////
void setSTAStaticIPConfig(const IPAddress& ip)
{
static_IP = ip;
}
//////////////////////////////////////////////
String getWiFiSSID(const uint8_t& index)
{
if (index >= NUM_WIFI_CREDENTIALS)
return String("");
if (!hadConfigData)
getConfigData();
return (String(WIFININA_config.WiFi_Creds[index].wifi_ssid));
}
//////////////////////////////////////////////
String getWiFiPW(const uint8_t& index)
{
if (index >= NUM_WIFI_CREDENTIALS)
return String("");
if (!hadConfigData)
getConfigData();
return (String(WIFININA_config.WiFi_Creds[index].wifi_pw));
}
//////////////////////////////////////////////
bool getWiFiStatus()
{
return wifi_connected;
}
//////////////////////////////////////////////
WiFiNINA_Configuration* getFullConfigData(WiFiNINA_Configuration *configData)
{
if (!hadConfigData)
getConfigData();
// Check if NULL pointer
if (configData)
memcpy(configData, &WIFININA_config, sizeof(WiFiNINA_Configuration));
return (configData);
}
//////////////////////////////////////////////
String localIP()
{
ipAddress = IPAddressToString(WiFi.localIP());
return ipAddress;
}
//////////////////////////////////////////////
void clearConfigData()
{
memset(&WIFININA_config, 0, sizeof(WIFININA_config));
#if USE_DYNAMIC_PARAMETERS
for (uint16_t i = 0; i < NUM_MENU_ITEMS; i++)
{
// Actual size of pdata is [maxlen + 1]
memset(myMenuItems[i].pdata, 0, myMenuItems[i].maxlen + 1);
}
#endif
saveConfigData();
}
//////////////////////////////////////////////
bool isConfigDataValid()
{
return hadConfigData;
}
//////////////////////////////////////////////
bool isConfigMode()
{
return configuration_mode;
}
//////////////////////////////////////////////
// Forced CP => Flag = 0xBEEFBEEF. Else => No forced CP
// Flag to be stored at (EEPROM_START + DRD_FLAG_DATA_SIZE + CONFIG_DATA_SIZE)
// to avoid corruption to current data
//#define FORCED_CONFIG_PORTAL_FLAG_DATA ( (uint32_t) 0xDEADBEEF)
//#define FORCED_PERS_CONFIG_PORTAL_FLAG_DATA ( (uint32_t) 0xBEEFDEAD)
const uint32_t FORCED_CONFIG_PORTAL_FLAG_DATA = 0xDEADBEEF;
const uint32_t FORCED_PERS_CONFIG_PORTAL_FLAG_DATA = 0xBEEFDEAD;
#define FORCED_CONFIG_PORTAL_FLAG_DATA_SIZE 4
void resetAndEnterConfigPortal()
{
persForcedConfigPortal = false;
setForcedCP(false);
// Delay then reset the ESP8266 after save data
delay(1000);
resetFunc();
}
//////////////////////////////////////////////
// This will keep CP forever, until you successfully enter CP, and Save data to clear the flag.
void resetAndEnterConfigPortalPersistent()
{
persForcedConfigPortal = true;
setForcedCP(true);
// Delay then reset the ESP8266 after save data
delay(1000);
resetFunc();
}
//////////////////////////////////////////////
void resetFunc()
{
// Best one. Possibly don't need the WDT
NVIC_SystemReset();
#if ( defined(__SAMD51__) || defined(__SAMD51J20A__) || defined(__SAMD51J19A__) || defined(__SAMD51G19A__) )
// For SAMD51
// see Table 17-5 Timeout Period (valid values 0-11)
WDT->CONFIG.reg = 5;
WDT->CTRLA.reg = WDT_CTRLA_ENABLE;
// To check if OK or bit.ENABLE/CLEAR
while (WDT->SYNCBUSY.bit.WEN == 1);
// use the WDT watchdog timer to force a system reset.
WDT->CLEAR.reg = 0x00;
// To check if OK or bit.ENABLE/CLEAR
while (WDT->SYNCBUSY.bit.WEN == 1);
#else
// For SAMD21, etc
// see Table 17-5 Timeout Period (valid values 0-11)
WDT->CONFIG.reg = 5;
WDT->CTRL.reg = WDT_CTRL_ENABLE;
while (WDT->STATUS.bit.SYNCBUSY == 1);
// use the WDT watchdog timer to force a system reset.
WDT->CLEAR.reg = 0x00;
while (WDT->STATUS.bit.SYNCBUSY == 1);
#endif
}
//////////////////////////////////////
// Add customs headers from v1.1.0
// New from v1.1.0, for configure CORS Header, default to WM_HTTP_CORS_ALLOW_ALL = "*"
#if USING_CUSTOMS_STYLE
//sets a custom style, such as color
// "<style>div,input,select{padding:5px;font-size:1em;}
// input,select{width:95%;}body{text-align: center;}
// button{background-color:#16A1E7;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;}
// fieldset{border-radius:0.3rem;margin:0px;}</style>";
void setCustomsStyle(const char* CustomsStyle = WIFININA_HTML_HEAD_STYLE)
{
WIFININA_HTML_HEAD_CUSTOMS_STYLE = CustomsStyle;
WN_LOGDEBUG1(F("Set CustomsStyle to : "), WIFININA_HTML_HEAD_CUSTOMS_STYLE);
}
const char* getCustomsStyle()
{
WN_LOGDEBUG1(F("Get CustomsStyle = "), WIFININA_HTML_HEAD_CUSTOMS_STYLE);
return WIFININA_HTML_HEAD_CUSTOMS_STYLE;
}
#endif
#if USING_CUSTOMS_HEAD_ELEMENT
//sets a custom element to add to head, like a new style tag
void setCustomsHeadElement(const char* CustomsHeadElement = NULL)
{
_CustomsHeadElement = CustomsHeadElement;
WN_LOGDEBUG1(F("Set CustomsHeadElement to : "), _CustomsHeadElement);
}
const char* getCustomsHeadElement()
{
WN_LOGDEBUG1(F("Get CustomsHeadElement = "), _CustomsHeadElement);
return _CustomsHeadElement;
}
#endif
#if USING_CORS_FEATURE
void setCORSHeader(const char* CORSHeaders = NULL)
{
_CORS_Header = CORSHeaders;
WN_LOGDEBUG1(F("Set CORS Header to : "), _CORS_Header);
}
const char* getCORSHeader()
{
WN_LOGDEBUG1(F("Get CORS Header = "), _CORS_Header);
return _CORS_Header;
}
#endif
//////////////////////////////////////
private:
String ipAddress = "0.0.0.0";
WiFiWebServer* server = NULL;
bool configuration_mode = false;
unsigned long configTimeout;
bool hadConfigData = false;
bool isForcedConfigPortal = false;
bool persForcedConfigPortal = false;
WiFiNINA_Configuration WIFININA_config;
uint16_t totalDataSize = 0;
String macAddress = "";
bool wifi_connected = false;
IPAddress portal_apIP = IPAddress(192, 168, 4, 1);
int AP_channel = 10;
String portal_ssid = "";
String portal_pass = "";
IPAddress static_IP = IPAddress(0, 0, 0, 0);
/////////////////////////////////////
// Add customs headers from v1.1.0
#if USING_CUSTOMS_STYLE
const char* WIFININA_HTML_HEAD_CUSTOMS_STYLE = NULL;
#endif
#if USING_CUSTOMS_HEAD_ELEMENT
const char* _CustomsHeadElement = NULL;
#endif
#if USING_CORS_FEATURE
const char* _CORS_Header = WM_HTTP_CORS_ALLOW_ALL; //"*";
#endif
/////////////////////////////////////
// Add WiFi Scan from v1.3.0
#if SCAN_WIFI_NETWORKS
int WiFiNetworksFound = 0; // Number of SSIDs found by WiFi scan, including low quality and duplicates
int *indices; // WiFi network data, filled by scan (SSID, BSSID)
String ListOfSSIDs = ""; // List of SSIDs found by scan, in HTML <option> format
#endif
//////////////////////////////////////
#define RFC952_HOSTNAME_MAXLEN 24
char RFC952_hostname[RFC952_HOSTNAME_MAXLEN + 1];
char* getRFC952_hostname(const char* iHostname)
{
memset(RFC952_hostname, 0, sizeof(RFC952_hostname));
size_t len = ( RFC952_HOSTNAME_MAXLEN < strlen(iHostname) ) ? RFC952_HOSTNAME_MAXLEN : strlen(iHostname);
size_t j = 0;
for (size_t i = 0; i < len - 1; i++)
{
if ( isalnum(iHostname[i]) || iHostname[i] == '-' )
{
RFC952_hostname[j] = iHostname[i];
j++;
}
}
// no '-' as last char
if ( isalnum(iHostname[len - 1]) || (iHostname[len - 1] != '-') )
RFC952_hostname[j] = iHostname[len - 1];
return RFC952_hostname;
}
void displayConfigData(const WiFiNINA_Configuration& configData)
{
WN_LOGERROR1(F("Hdr="), configData.header);
for (uint16_t i = 0; i < NUM_WIFI_CREDENTIALS; i++)
{
WN_LOGERROR5(F("Credentials Set #"), i, F(": SSID="), configData.WiFi_Creds[i].wifi_ssid, F(", PW="),
configData.WiFi_Creds[i].wifi_pw);
}
WN_LOGERROR1(F("BName="), configData.board_name);