This repository has been archived by the owner on Nov 25, 2021. It is now read-only.
/
BlynkSimpleEsp32_WM.h
2952 lines (2354 loc) · 93.5 KB
/
BlynkSimpleEsp32_WM.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
/*******************************************************************************************************************************
BlynkSimpleEsp32_WM.h
For ESP32 boards
Blynk_WM is a library for the ESP8266/ESP32 Arduino platform (https://github.com/esp8266/Arduino) to enable easy
configuration/reconfiguration and autoconnect/autoreconnect of WiFi/Blynk
Forked from Blynk library v0.6.1 https://github.com/blynkkk/blynk-library/releases
Built by Khoi Hoang https://github.com/khoih-prog/Blynk_WM
Licensed under MIT license
Original Blynk Library author:
@file BlynkSimpleEsp8266.h
@author Volodymyr Shymanskyy
@license This project is released under the MIT License (MIT)
@copyright Copyright (c) 2015 Volodymyr Shymanskyy
@date Jan 2015
@brief
Version: 1.6.2
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 28/10/2019 Initial coding
1.0.1 K Hoang 28/10/2019 Add features
1.0.2 K Hoang 21/11/2019 Fix bug. Add features.
1.0.3 K Hoang 31/11/2019 Fix compiler errors for ESP8266 core pre-2.5.2. Add examples.
1.0.4 K Hoang 07/01/2020 Add configurable personalized RFC-952 DHCP hostname
1.0.5 K Hoang 20/01/2020 Add configurable static IP, GW, SN, DNS1, DNS2 and Config Portal static IP and Credentials
1.0.6 K Hoang 05/02/2020 Optimize, fix EEPROM size to 2K from 4K, shorten code size, add functions
1.0.7 K Hoang 18/02/2020 Add checksum, enable AutoConnect to configurable MultiWiFi and MultiBlynk Credentials
1.0.8 K Hoang 24/02/2020 Fix AP-staying-open bug. Add clearConfigData()
1.0.9 K Hoang 12/03/2020 Enhance Config Portal GUI
1.0.10 K Hoang 08/04/2020 SSID password maxlen is 63 now. Permit special chars # and % in input data.
1.0.11 K Hoang 09/04/2020 Enable adding dynamic custom parameters from sketch
1.0.12 K Hoang 13/04/2020 Fix MultiWiFi/Blynk bug introduced in broken v1.0.11
1.0.13 K Hoang 25/04/2020 Add Configurable Config Portal Title, Default Config Data and DRD. Update examples.
1.0.14 K Hoang 03/05/2020 Fix bug and change feature in dynamicParams.
1.0.15 K Hoang 12/05/2020 Fix bug and Update to use LittleFS for ESP8266 core 2.7.1+. Add example.
1.0.16 K Hoang 25/06/2020 Fix bug and logic of USE_DEFAULT_CONFIG_DATA. Auto format SPIFFS/LittleFS.
1.1.0 K Hoang 01/01/2021 Add support to ESP32 LittleFS. Remove possible compiler warnings. Update examples. Add MRD
1.1.1 K Hoang 16/01/2021 Add functions to control Config Portal from software or Virtual Switches
1.1.2 K Hoang 28/01/2021 Fix Config Portal and Dynamic Params bugs
1.1.3 K Hoang 31/01/2021 To permit autoreset after timeout if DRD/MRD or non-persistent forced-CP
1.2.0 K Hoang 24/02/2021 Add customs HTML header feature and support to ESP32-S2.
1.3.0 K Hoang 19/04/2021 Add LittleFS and SPIFFS support to ESP32-S2. Add support to ESP32-C3 without LittleFS
Fix SSL issue with Blynk Cloud Server
1.3.1 K Hoang 24/04/2021 Fix issue of custom Blynk port (different from 8080 or 9443) not working on ESP32
1.4.0 K Hoang 24/04/2021 Enable scan of WiFi networks for selection in Configuration Portal
1.5.0 K Hoang 25/04/2021 Fix bug. Optimize and sync with Blynk_Async_WM library v1.5.0
1.6.0 K Hoang 19/05/2021 Fix AP connect and SSL issues caused by breaking ESP8266 core v3.0.0
1.6.1 K Hoang 29/06/2021 Fix issue with ESP8266 core v3.0.1
1.6.2 K Hoang 10/10/2021 Update `platform.ini` and `library.json`
********************************************************************************************************************************/
#ifndef BlynkSimpleEsp32_WM_h
#define BlynkSimpleEsp32_WM_h
#ifndef ESP32
#error This code is intended to run on the ESP32 platform! Please check your Tools->Board setting.
#endif
#define BLYNK_WM_VERSION "Blynk_WM for ESP32 v1.6.2"
//////////////////////////////////////////////
// From v1.6.0 to display correct BLYNK_INFO_DEVICE
#define BLYNK_USE_128_VPINS
#if defined(BLYNK_INFO_DEVICE)
#undef BLYNK_INFO_DEVICE
#endif
#define BLYNK_BUFFERS_SIZE 4096
#if defined(BLYNK_INFO_DEVICE)
#undef BLYNK_INFO_DEVICE
#endif
#if defined(ARDUINO_BOARD)
#define BLYNK_INFO_DEVICE ARDUINO_BOARD
#elif defined(BOARD_NAME)
#define BLYNK_INFO_DEVICE BOARD_NAME
#elif defined(BOARD_TYPE)
#define BLYNK_INFO_DEVICE BOARD_TYPE
#else
#define BLYNK_INFO_DEVICE "ESP32"
#endif
/////////////////////////////////////////////
#define BLYNK_SEND_ATOMIC
#include <BlynkApiArduino.h>
#include <Blynk/BlynkProtocol.h>
#include <Adapters/BlynkArduinoClient.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <WebServer.h>
// LittleFS has higher priority than SPIFFS.
// But if not specified any, use SPIFFS to not forcing user to install LITTLEFS library
#if ! (defined(USE_LITTLEFS) || defined(USE_SPIFFS) )
#define USE_SPIFFS true
#endif
#if USE_LITTLEFS
// Use LittleFS
#include "FS.h"
// The library has been merged into Arduino esp32 core release v1.0.6
#include <LITTLEFS.h> // https://github.com/lorol/LITTLEFS
FS* filesystem = &LITTLEFS;
#define FileFS LITTLEFS
#warning Using LittleFS in BlynkSimpleESP32_WM.h
#elif USE_SPIFFS
#include "FS.h"
#include <SPIFFS.h>
FS* filesystem = &SPIFFS;
#define FileFS SPIFFS
#warning Using SPIFFS in BlynkSimpleESP32_WM.h
#else
#include <EEPROM.h>
#warning Using EEPROM in BlynkSimpleESP32_WM.h
#endif
//////////////////////////////////////////////
// New from v1.4.0
// KH, Some minor simplification
#if !defined(SCAN_WIFI_NETWORKS)
#define SCAN_WIFI_NETWORKS true //false
#endif
#if SCAN_WIFI_NETWORKS
#warning Using 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 /////////////
#if !defined(USING_MRD)
#define USING_MRD false
#endif
#if USING_MRD
///////// NEW for MRD /////////////
// These defines must be put before #include <ESP_DoubleResetDetector.h>
// to select where to store DoubleResetDetector's variable.
// For ESP32, You must select one to be true (EEPROM or SPIFFS/LittleFS)
// For ESP8266, You must select one to be true (RTC, EEPROM or SPIFFS/LittleFS)
// Otherwise, library will use default EEPROM storage
#define ESP8266_MRD_USE_RTC false //true
#if USE_LITTLEFS
#define ESP_MRD_USE_LITTLEFS true
#define ESP_MRD_USE_SPIFFS false
#define ESP_MRD_USE_EEPROM false
#elif USE_SPIFFS
#define ESP_MRD_USE_LITTLEFS false
#define ESP_MRD_USE_SPIFFS true
#define ESP_MRD_USE_EEPROM false
#else
#define ESP_MRD_USE_LITTLEFS false
#define ESP_MRD_USE_SPIFFS false
#define ESP_MRD_USE_EEPROM true
#endif
#ifndef MULTIRESETDETECTOR_DEBUG
#define MULTIRESETDETECTOR_DEBUG false
#endif
// These definitions must be placed before #include <ESP_MultiResetDetector.h> to be used
// Otherwise, default values (MRD_TIMES = 3, MRD_TIMEOUT = 10 seconds and MRD_ADDRESS = 0) will be used
// Number of subsequent resets during MRD_TIMEOUT to activate
#ifndef MRD_TIMES
#define MRD_TIMES 3
#endif
// Number of seconds after reset during which a
// subsequent reset will be considered a double reset.
#ifndef MRD_TIMEOUT
#define MRD_TIMEOUT 10
#endif
// EEPROM Memory Address for the MultiResetDetector to use
#ifndef MRD_TIMEOUT
#define MRD_ADDRESS 0
#endif
#include <ESP_MultiResetDetector.h> //https://github.com/khoih-prog/ESP_MultiResetDetector
//MultiResetDetector mrd(MRD_TIMEOUT, MRD_ADDRESS);
MultiResetDetector* mrd;
///////// NEW for MRD /////////////
#else
///////// NEW for DRD /////////////
// These defines must be put before #include <ESP_DoubleResetDetector.h>
// to select where to store DoubleResetDetector's variable.
// For ESP32, You must select one to be true (EEPROM or SPIFFS/LittleFS)
// For ESP8266, You must select one to be true (RTC, EEPROM or SPIFFS/LittleFS)
// Otherwise, library will use default EEPROM storage
#define ESP8266_DRD_USE_RTC false //true
#if USE_LITTLEFS
#define ESP_DRD_USE_LITTLEFS true
#define ESP_DRD_USE_SPIFFS false
#define ESP_DRD_USE_EEPROM false
#elif USE_SPIFFS
#define ESP_DRD_USE_LITTLEFS false
#define ESP_DRD_USE_SPIFFS true
#define ESP_DRD_USE_EEPROM false
#else
#define ESP_DRD_USE_LITTLEFS false
#define ESP_DRD_USE_SPIFFS false
#define ESP_DRD_USE_EEPROM true
#endif
#ifndef DOUBLERESETDETECTOR_DEBUG
#define DOUBLERESETDETECTOR_DEBUG false
#endif
// Number of seconds after reset during which a
// subsequent reset will be considered a double reset.
#define DRD_TIMEOUT 10
// RTC Memory Address for the DoubleResetDetector to use
#define DRD_ADDRESS 0
#include <ESP_DoubleResetDetector.h> //https://github.com/khoih-prog/ESP_DoubleResetDetector
//DoubleResetDetector drd(DRD_TIMEOUT, DRD_ADDRESS);
DoubleResetDetector* drd;
///////// NEW for DRD /////////////
#endif
#include <esp_wifi.h>
#define ESP_getChipId() ((uint32_t)ESP.getEfuseMac())
#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
extern uint16_t NUM_MENU_ITEMS;
extern MenuItem myMenuItems [];
bool *menuItemUpdated = NULL;
#endif
#define SSID_MAX_LEN 32
//From v1.0.10, 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 BLYNK_SERVER_MAX_LEN 32
#define BLYNK_TOKEN_MAX_LEN 36
typedef struct
{
char blynk_server[BLYNK_SERVER_MAX_LEN];
char blynk_token [BLYNK_TOKEN_MAX_LEN];
} Blynk_Credentials;
#define NUM_WIFI_CREDENTIALS 2
#define NUM_BLYNK_CREDENTIALS 2
// Configurable items besides fixed Header
#define NUM_CONFIGURABLE_ITEMS ( 2 + (2 * NUM_WIFI_CREDENTIALS) + (2 * NUM_BLYNK_CREDENTIALS) )
#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];
Blynk_Credentials Blynk_Creds [NUM_BLYNK_CREDENTIALS];
int blynk_port;
char board_name [BOARD_NAME_MAX_LEN];
int checkSum;
} Blynk_WM_Configuration;
// Currently CONFIG_DATA_SIZE = ( 48 + (96 * NUM_WIFI_CREDENTIALS) + (68 * NUM_BLYNK_CREDENTIALS) ) = 376
uint16_t CONFIG_DATA_SIZE = sizeof(Blynk_WM_Configuration);
///New from v1.0.13
extern bool LOAD_DEFAULT_CONFIG_DATA;
extern Blynk_WM_Configuration defaultConfig;
//From v1.0.10, Permit special chars such as # and %
// -- HTML page fragments
const char BLYNK_WM_HTML_HEAD_START[] /*PROGMEM*/ = "<!DOCTYPE html><html><head><title>BlynkSimpleEsp32_WM</title>";
const char BLYNK_WM_HTML_HEAD_STYLE[] /*PROGMEM*/ = "<style>div,input{padding:5px;font-size:1em;}input{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>";
const char BLYNK_WM_HTML_HEAD_END[] /*PROGMEM*/ = "</head><div style='text-align:left;display:inline-block;min-width:260px;'>\
<fieldset><div><label>*WiFi SSID</label>[[input_id]]<div></div></div>\
<div><label>*PWD (8+ chars)</label><input value='[[pw]]'id='pw'><div></div></div>\
<div><label>*WiFi SSID1</label>[[input_id1]]<div></div></div>\
<div><label>*PWD1 (8+ chars)</label><input value='[[pw1]]'id='pw1'><div></div></div></fieldset>\
<fieldset><div><label>Blynk Server</label><input value='[[sv]]'id='sv'><div></div></div>\
<div><label>Token</label><input value='[[tk]]'id='tk'><div></div></div>\
<div><label>Blynk Server1</label><input value='[[sv1]]'id='sv1'><div></div></div>\
<div><label>Token1</label><input value='[[tk1]]'id='tk1'><div></div></div>\
<div><label>Port</label><input value='[[pt]]'id='pt'><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!!!!
const char BLYNK_WM_HTML_INPUT_ID[] /*PROGMEM*/ = "<input value='[[id]]' id='id'>";
const char BLYNK_WM_HTML_INPUT_ID1[] /*PROGMEM*/ = "<input value='[[id1]]' id='id1'>";
const char BLYNK_WM_FLDSET_START[] /*PROGMEM*/ = "<fieldset>";
const char BLYNK_WM_FLDSET_END[] /*PROGMEM*/ = "</fieldset>";
const char BLYNK_WM_HTML_PARAM[] /*PROGMEM*/ = "<div><label>{b}</label><input value='[[{v}]]'id='{i}'><div></div></div>";
const char BLYNK_WM_HTML_BUTTON[] /*PROGMEM*/ = "<button onclick='sv()'>Save</button></div>";
const char BLYNK_WM_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('sv',document.getElementById('sv').value);udVal('tk',document.getElementById('tk').value);\
udVal('sv1',document.getElementById('sv1').value);udVal('tk1',document.getElementById('tk1').value);\
udVal('pt',document.getElementById('pt').value);udVal('nm',document.getElementById('nm').value);";
const char BLYNK_WM_HTML_SCRIPT_ITEM[] /*PROGMEM*/ = "udVal('{d}',document.getElementById('{d}').value);";
const char BLYNK_WM_HTML_SCRIPT_END[] /*PROGMEM*/ = "alert('Updated');}</script>";
const char BLYNK_WM_HTML_END[] /*PROGMEM*/ = "</html>";
#if SCAN_WIFI_NETWORKS
const char BLYNK_WM_SELECT_START[] /*PROGMEM*/ = "<select id=";
const char BLYNK_WM_SELECT_END[] /*PROGMEM*/ = "</select>";
const char BLYNK_WM_DATALIST_START[] /*PROGMEM*/ = "<datalist id=";
const char BLYNK_WM_DATALIST_END[] /*PROGMEM*/ = "</datalist>";
const char BLYNK_WM_OPTION_START[] /*PROGMEM*/ = "<option>";
const char BLYNK_WM_OPTION_END[] /*PROGMEM*/ = ""; // "</option>"; is not required
const char BLYNK_WM_NO_NETWORKS_FOUND[] /*PROGMEM*/ = "No suitable WiFi networks available!";
#endif
//////////////////////////////////////////
//KH Add repeatedly used const
//KH, from v1.2.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 = "*";
//////////////////////////////////////////
#define BLYNK_SERVER_HARDWARE_PORT 8080
#define BLYNK_BOARD_TYPE "ESP32"
#define NO_CONFIG "blank"
//////////////////////////////////////////////
class BlynkWifi
: public BlynkProtocol<BlynkArduinoClient>
{
typedef BlynkProtocol<BlynkArduinoClient> Base;
public:
BlynkWifi(BlynkArduinoClient& transp)
: Base(transp)
{}
//////////////////////////////////////////
void connectWiFi(const char* ssid, const char* pass)
{
BLYNK_LOG2(BLYNK_F("Con2:"), ssid);
WiFi.mode(WIFI_STA);
// New from Blynk_WM v1.0.5
if (static_IP != IPAddress(0, 0, 0, 0))
{
BLYNK_LOG1(BLYNK_F("UseStatIP"));
WiFi.config(static_IP, static_GW, static_SN, static_DNS1, static_DNS2);
}
setHostname();
if (WiFi.status() != WL_CONNECTED)
{
if (pass && strlen(pass))
{
WiFi.begin(ssid, pass);
} else
{
WiFi.begin(ssid);
}
}
while (WiFi.status() != WL_CONNECTED)
{
BlynkDelay(500);
}
BLYNK_LOG1(BLYNK_F("Conn2WiFi"));
displayWiFiData();
}
//////////////////////////////////////////
void config(const char* auth,
const char* domain = BLYNK_DEFAULT_DOMAIN,
uint16_t port = BLYNK_DEFAULT_PORT)
{
Base::begin(auth);
this->conn.begin(domain, port);
}
//////////////////////////////////////////
void config(const char* auth,
IPAddress ip,
uint16_t port = BLYNK_DEFAULT_PORT)
{
Base::begin(auth);
this->conn.begin(ip, port);
}
//////////////////////////////////////////
void begin(const char* auth,
const char* ssid,
const char* pass,
const char* domain = BLYNK_DEFAULT_DOMAIN,
uint16_t port = BLYNK_DEFAULT_PORT)
{
connectWiFi(ssid, pass);
config(auth, domain, port);
while (this->connect() != true) {}
}
//////////////////////////////////////////
void begin(const char* auth,
const char* ssid,
const char* pass,
IPAddress ip,
uint16_t port = BLYNK_DEFAULT_PORT)
{
connectWiFi(ssid, pass);
config(auth, ip, port);
while (this->connect() != true) {}
}
#ifndef LED_BUILTIN
#define LED_BUILTIN 2 // Pin D2 mapped to pin GPIO2/ADC12 of ESP32, control on-board LED
#endif
// For ESP32
#define LED_OFF LOW
#define LED_ON HIGH
// New from v1.3.0
#if !defined(REQUIRE_ONE_SET_SSID_PW)
#define REQUIRE_ONE_SET_SSID_PW false
#endif
#define PASSWORD_MIN_LEN 8
//////////////////////////////////////////////
void begin(const char *iHostname = "")
{
#define TIMEOUT_CONNECT_WIFI 30000
//Turn OFF
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LED_OFF);
#if USING_MRD
//// New MRD ////
mrd = new MultiResetDetector(MRD_TIMEOUT, MRD_ADDRESS);
bool noConfigPortal = true;
if (mrd->detectMultiReset())
#else
//// New DRD ////
drd = new DoubleResetDetector(DRD_TIMEOUT, DRD_ADDRESS);
bool noConfigPortal = true;
if (drd->detectDoubleReset())
#endif
{
#if ( BLYNK_WM_DEBUG > 1)
BLYNK_LOG1(BLYNK_F("Multi or Double Reset Detected"));
#endif
noConfigPortal = false;
}
//// New DRD/MRD ////
#if ( BLYNK_WM_DEBUG > 2)
if (LOAD_DEFAULT_CONFIG_DATA)
{
BLYNK_LOG1(BLYNK_F("======= Start Default Config Data ======="));
displayConfigData(defaultConfig);
}
#endif
WiFi.mode(WIFI_STA);
if (iHostname[0] == 0)
{
String _hostname = "ESP32-" + String((uint32_t)ESP.getEfuseMac(), HEX);
_hostname.toUpperCase();
getRFC952_hostname(_hostname.c_str());
}
else
{
// Prepare and store the hostname only not NULL
getRFC952_hostname(iHostname);
}
BLYNK_LOG2(BLYNK_F("Hostname="), RFC952_hostname);
hadConfigData = getConfigData();
isForcedConfigPortal = isForcedCP();
//// New DRD/MRD ////
// noConfigPortal when getConfigData() OK and no MRD/DRD'ed
//if (getConfigData() && noConfigPortal)
if (hadConfigData && noConfigPortal && (!isForcedConfigPortal) )
{
hadConfigData = true;
#if ( BLYNK_WM_DEBUG > 2)
BLYNK_LOG1(noConfigPortal? BLYNK_F("bg: noConfigPortal = true") : BLYNK_F("bg: noConfigPortal = false"));
#endif
for (uint16_t i = 0; i < NUM_WIFI_CREDENTIALS; i++)
{
wifiMulti.addAP(BlynkESP32_WM_config.WiFi_Creds[i].wifi_ssid, BlynkESP32_WM_config.WiFi_Creds[i].wifi_pw);
}
//Base::begin(BlynkESP32_WM_config.blynk_token);
//this->conn.begin(BlynkESP32_WM_config.blynk_server, BlynkESP32_WM_config.blynk_port);
if (connectMultiWiFi() == WL_CONNECTED)
{
BLYNK_LOG1(BLYNK_F("bg: WiFi OK. Try Blynk"));
int i = 0;
while ( (i++ < 10) && !connectMultiBlynk() )
{
}
if (connected())
{
BLYNK_LOG1(BLYNK_F("bg: WiFi+Blynk OK"));
}
else
{
BLYNK_LOG1(BLYNK_F("bg: WiFi OK, Blynk not"));
// failed to connect to Blynk server, will start configuration mode
startConfigurationMode();
}
}
else
{
BLYNK_LOG1(BLYNK_F("bg: Fail2connect WiFi+Blynk"));
// failed to connect to Blynk server, will start configuration mode
startConfigurationMode();
}
}
else
{
#if ( BLYNK_WM_DEBUG > 2)
BLYNK_LOG1(isForcedConfigPortal? BLYNK_F("bg: isForcedConfigPortal = true") : BLYNK_F("bg: isForcedConfigPortal = false"));
#endif
// If not persistent => clear the flag so that after reset. no more CP, even CP not entered and saved
if (persForcedConfigPortal)
{
BLYNK_LOG2(BLYNK_F("bg:Stay forever in CP:"), isForcedConfigPortal ? BLYNK_F("Forced-Persistent") : (noConfigPortal ? BLYNK_F("No ConfigDat") : BLYNK_F("DRD/MRD")));
}
else
{
BLYNK_LOG2(BLYNK_F("bg:Stay forever in CP:"), isForcedConfigPortal ? BLYNK_F("Forced-non-Persistent") : (noConfigPortal ? BLYNK_F("No ConfigDat") : BLYNK_F("DRD/MRD")));
clearForcedCP();
}
hadConfigData = isForcedConfigPortal ? true : (noConfigPortal ? false : true);
// failed to connect to Blynk server, will start configuration mode
startConfigurationMode();
}
}
#ifndef TIMEOUT_RECONNECT_WIFI
#define TIMEOUT_RECONNECT_WIFI 10000L
#else
// Force range of user-defined TIMEOUT_RECONNECT_WIFI between 10-60s
#if (TIMEOUT_RECONNECT_WIFI < 10000L)
#warning TIMEOUT_RECONNECT_WIFI too low. Reseting to 10000
#undef TIMEOUT_RECONNECT_WIFI
#define TIMEOUT_RECONNECT_WIFI 10000L
#elif (TIMEOUT_RECONNECT_WIFI > 60000L)
#warning TIMEOUT_RECONNECT_WIFI too high. Reseting to 60000
#undef TIMEOUT_RECONNECT_WIFI
#define TIMEOUT_RECONNECT_WIFI 60000L
#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. Reseting to 100
#undef CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET
#define CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET 100
#endif
#endif
//////////////////////////////////////////////
void run()
{
static int retryTimes = 0;
#if USING_MRD
//// New MRD ////
// Call the mulyi reset detector loop method every so often,
// so that it can recognise when the timeout expires.
// You can also call mrd.stop() when you wish to no longer
// consider the next reset as a multi reset.
mrd->loop();
//// New MRD ////
#else
//// 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 ////
#endif
// Lost connection in running. Give chance to reconfig.
if ( WiFi.status() != WL_CONNECTED || !connected() )
{
// If configTimeout but user hasn't connected to configWeb => try to reconnect WiFi / Blynk.
// 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)
{
server->handleClient();
#if ( ARDUINO_ESP32S2_DEV || ARDUINO_FEATHERS2 || ARDUINO_PROS2 || ARDUINO_MICROS2 )
// Fix ESP32-S2 issue with WebServer (https://github.com/espressif/arduino-esp32/issues/4348)
delay(1);
#endif
}
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)
{
BLYNK_LOG2(BLYNK_F("run: WiFi lost, configTimeout. Connect WiFi+Blynk. Retry#:"), retryTimes);
}
else
{
ESP.restart();
}
}
#endif
// Not in config mode, try reconnecting before force to config mode
if ( WiFi.status() != WL_CONNECTED )
{
BLYNK_LOG1(BLYNK_F("run: WiFi lost. Reconnect WiFi+Blynk"));
if (connectMultiWiFi() == WL_CONNECTED)
{
// turn the LED_BUILTIN OFF to tell us we exit configuration mode.
digitalWrite(LED_BUILTIN, LED_OFF);
BLYNK_LOG1(BLYNK_F("run: WiFi reconnected. Connect to Blynk"));
if (connectMultiBlynk())
{
BLYNK_LOG1(BLYNK_F("run: WiFi+Blynk reconnected"));
}
}
}
else
{
BLYNK_LOG1(BLYNK_F("run: Blynk lost. Connect Blynk"));
if (connectMultiBlynk())
{
// turn the LED_BUILTIN OFF to tell us we exit configuration mode.
digitalWrite(LED_BUILTIN, LED_OFF);
BLYNK_LOG1(BLYNK_F("run: Blynk reconnected"));
}
}
//BLYNK_LOG1(BLYNK_F("run: Lost connection => configMode"));
//startConfigurationMode();
}
}
else if (configuration_mode)
{
configuration_mode = false;
BLYNK_LOG1(BLYNK_F("run: got WiFi+Blynk back"));
// Turn the LED_BUILTIN OFF when out of configuration mode. ESP32 LED_BUILDIN is correct polarity, LED_OFF to turn OFF
digitalWrite(LED_BUILTIN, LED_OFF);
}
if (connected())
{
Base::run();
}
}
//////////////////////////////////////////////
void setHostname()
{
#if !( ARDUINO_ESP32S2_DEV || ARDUINO_FEATHERS2 || ARDUINO_PROS2 || ARDUINO_MICROS2 )
if (RFC952_hostname[0] != 0)
{
// See https://github.com/espressif/arduino-esp32/issues/2537
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
WiFi.setHostname(RFC952_hostname);
}
#endif
}
void setConfigPortalIP(IPAddress portalIP = IPAddress(192, 168, 4, 1))
{
portal_apIP = portalIP;
}
void setConfigPortal(String ssid = "", String pass = "")
{
portal_ssid = ssid;
portal_pass = pass;
}
#define MIN_WIFI_CHANNEL 1
#define MAX_WIFI_CHANNEL 11
int setConfigPortalChannel(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) )
WiFiAPChannel = 1;
else if ( (channel >= MIN_WIFI_CHANNEL - 1) && (channel <= MAX_WIFI_CHANNEL) )
WiFiAPChannel = channel;
return WiFiAPChannel;
}
void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn = IPAddress(255, 255, 255, 0),
IPAddress dns_address_1 = IPAddress(0, 0, 0, 0),
IPAddress dns_address_2 = IPAddress(0, 0, 0, 0))
{
static_IP = ip;
static_GW = gw;
static_SN = sn;
// Default to local GW
if (dns_address_1 == IPAddress(0, 0, 0, 0))
static_DNS1 = gw;
else
static_DNS1 = dns_address_1;
// Default to Google DNS (8, 8, 8, 8)
if (dns_address_2 == IPAddress(0, 0, 0, 0))
static_DNS2 = IPAddress(8, 8, 8, 8);
else
static_DNS2 = dns_address_2;
}
String getWiFiSSID(uint8_t index)
{
if (index >= NUM_WIFI_CREDENTIALS)
return String("");
if (!hadConfigData)
getConfigData();
return (String(BlynkESP32_WM_config.WiFi_Creds[index].wifi_ssid));
}
String getWiFiPW(uint8_t index)
{
if (index >= NUM_WIFI_CREDENTIALS)
return String("");
if (!hadConfigData)
getConfigData();
return (String(BlynkESP32_WM_config.WiFi_Creds[index].wifi_pw));
}
String getServerName(uint8_t index)
{
if (index >= NUM_BLYNK_CREDENTIALS)
return String("");
if (!hadConfigData)
getConfigData();
return (String(BlynkESP32_WM_config.Blynk_Creds[index].blynk_server));
}
String getToken(uint8_t index)
{
if (index >= NUM_BLYNK_CREDENTIALS)
return String("");
if (!hadConfigData)
getConfigData();
return (String(BlynkESP32_WM_config.Blynk_Creds[index].blynk_token));
}
String getBoardName()
{
if (!hadConfigData)
getConfigData();
return (String(BlynkESP32_WM_config.board_name));
}
int getHWPort()
{
if (!hadConfigData)
getConfigData();
return (BlynkESP32_WM_config.blynk_port);
}
Blynk_WM_Configuration* getFullConfigData(Blynk_WM_Configuration *configData)
{
if (!hadConfigData)
getConfigData();
// Check if NULL pointer
if (configData)
memcpy(configData, &BlynkESP32_WM_config, sizeof(Blynk_WM_Configuration));
return (configData);
}
void clearConfigData()
{
memset(&BlynkESP32_WM_config, 0, sizeof(BlynkESP32_WM_config));
saveConfigData();
}
// 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 ESP32 after save data
delay(1000);
ESP.restart();
}
// 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 ESP32 after save data
delay(1000);
ESP.restart();
}
//////////////////////////////////////
// Add customs headers from v1.2.0
// New from v1.2.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{padding:5px;font-size:1em;}
// input{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 = BLYNK_WM_HTML_HEAD_STYLE)
{
BLYNK_WM_HTML_HEAD_CUSTOMS_STYLE = CustomsStyle;
BLYNK_LOG2(F("Set CustomsStyle to : "), BLYNK_WM_HTML_HEAD_CUSTOMS_STYLE);
}
//////////////////////////////////////
const char* getCustomsStyle()
{
BLYNK_LOG2(F("Get CustomsStyle = "), BLYNK_WM_HTML_HEAD_CUSTOMS_STYLE);
return BLYNK_WM_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;
BLYNK_LOG2(F("Set CustomsHeadElement to : "), _CustomsHeadElement);
}
//////////////////////////////////////
const char* getCustomsHeadElement()
{
BLYNK_LOG2(F("Get CustomsHeadElement = "), _CustomsHeadElement);
return _CustomsHeadElement;
}