-
Notifications
You must be signed in to change notification settings - Fork 2k
/
WiFiManager.cpp
4016 lines (3573 loc) · 119 KB
/
WiFiManager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* WiFiManager.cpp
*
* WiFiManager, a library for the ESP8266/Arduino platform
* for configuration of WiFi credentials using a Captive Portal
*
* @author Creator tzapu
* @author tablatronix
* @version 0.0.0
* @license MIT
*/
#include "WiFiManager.h"
#if defined(ESP8266) || defined(ESP32)
#ifdef ESP32
uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS;
#endif
/**
* --------------------------------------------------------------------------------
* WiFiManagerParameter
* --------------------------------------------------------------------------------
**/
WiFiManagerParameter::WiFiManagerParameter() {
WiFiManagerParameter("");
}
WiFiManagerParameter::WiFiManagerParameter(const char *custom) {
_id = NULL;
_label = NULL;
_length = 0;
_value = nullptr;
_labelPlacement = WFM_LABEL_DEFAULT;
_customHTML = custom;
}
WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label) {
init(id, label, "", 0, "", WFM_LABEL_DEFAULT);
}
WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length) {
init(id, label, defaultValue, length, "", WFM_LABEL_DEFAULT);
}
WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom) {
init(id, label, defaultValue, length, custom, WFM_LABEL_DEFAULT);
}
WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) {
init(id, label, defaultValue, length, custom, labelPlacement);
}
void WiFiManagerParameter::init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) {
_id = id;
_label = label;
_labelPlacement = labelPlacement;
_customHTML = custom;
_length = 0;
_value = nullptr;
setValue(defaultValue,length);
}
WiFiManagerParameter::~WiFiManagerParameter() {
if (_value != NULL) {
delete[] _value;
}
_length=0; // setting length 0, ideally the entire parameter should be removed, or added to wifimanager scope so it follows
}
// WiFiManagerParameter& WiFiManagerParameter::operator=(const WiFiManagerParameter& rhs){
// Serial.println("copy assignment op called");
// (*this->_value) = (*rhs._value);
// return *this;
// }
// @note debug is not available in wmparameter class
void WiFiManagerParameter::setValue(const char *defaultValue, int length) {
if(!_id){
// Serial.println("cannot set value of this parameter");
return;
}
// if(strlen(defaultValue) > length){
// // Serial.println("defaultValue length mismatch");
// // return false; //@todo bail
// }
if(_length != length || _value == nullptr){
_length = length;
if( _value != nullptr){
delete[] _value;
}
_value = new char[_length + 1];
}
memset(_value, 0, _length + 1); // explicit null
if (defaultValue != NULL) {
strncpy(_value, defaultValue, _length);
}
}
const char* WiFiManagerParameter::getValue() const {
// Serial.println(printf("Address of _value is %p\n", (void *)_value));
return _value;
}
const char* WiFiManagerParameter::getID() const {
return _id;
}
const char* WiFiManagerParameter::getPlaceholder() const {
return _label;
}
const char* WiFiManagerParameter::getLabel() const {
return _label;
}
int WiFiManagerParameter::getValueLength() const {
return _length;
}
int WiFiManagerParameter::getLabelPlacement() const {
return _labelPlacement;
}
const char* WiFiManagerParameter::getCustomHTML() const {
return _customHTML;
}
/**
* [addParameter description]
* @access public
* @param {[type]} WiFiManagerParameter *p [description]
*/
bool WiFiManager::addParameter(WiFiManagerParameter *p) {
// check param id is valid, unless null
if(p->getID()){
for (size_t i = 0; i < strlen(p->getID()); i++){
if(!(isAlphaNumeric(p->getID()[i])) && !(p->getID()[i]=='_')){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] parameter IDs can only contain alpha numeric chars"));
#endif
return false;
}
}
}
// init params if never malloc
if(_params == NULL){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_DEV,F("allocating params bytes:"),_max_params * sizeof(WiFiManagerParameter*));
#endif
_params = (WiFiManagerParameter**)malloc(_max_params * sizeof(WiFiManagerParameter*));
}
// resize the params array by increment of WIFI_MANAGER_MAX_PARAMS
if(_paramsCount == _max_params){
_max_params += WIFI_MANAGER_MAX_PARAMS;
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_DEV,F("Updated _max_params:"),_max_params);
DEBUG_WM(WM_DEBUG_DEV,F("re-allocating params bytes:"),_max_params * sizeof(WiFiManagerParameter*));
#endif
WiFiManagerParameter** new_params = (WiFiManagerParameter**)realloc(_params, _max_params * sizeof(WiFiManagerParameter*));
#ifdef WM_DEBUG_LEVEL
// DEBUG_WM(WIFI_MANAGER_MAX_PARAMS);
// DEBUG_WM(_paramsCount);
// DEBUG_WM(_max_params);
#endif
if (new_params != NULL) {
_params = new_params;
} else {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] failed to realloc params, size not increased!"));
#endif
return false;
}
}
_params[_paramsCount] = p;
_paramsCount++;
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Added Parameter:"),p->getID());
#endif
return true;
}
/**
* [getParameters description]
* @access public
*/
WiFiManagerParameter** WiFiManager::getParameters() {
return _params;
}
/**
* [getParametersCount description]
* @access public
*/
int WiFiManager::getParametersCount() {
return _paramsCount;
}
/**
* --------------------------------------------------------------------------------
* WiFiManager
* --------------------------------------------------------------------------------
**/
// constructors
WiFiManager::WiFiManager(Print& consolePort):_debugPort(consolePort){
WiFiManagerInit();
}
WiFiManager::WiFiManager() {
WiFiManagerInit();
}
void WiFiManager::WiFiManagerInit(){
setMenu(_menuIdsDefault);
if(_debug && _debugLevel >= WM_DEBUG_DEV) debugPlatformInfo();
_max_params = WIFI_MANAGER_MAX_PARAMS;
}
// destructor
WiFiManager::~WiFiManager() {
_end();
// parameters
// @todo below belongs to wifimanagerparameter
if (_params != NULL){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_DEV,F("freeing allocated params!"));
#endif
free(_params);
_params = NULL;
}
// remove event
// WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2));
#ifdef ESP32
WiFi.removeEvent(wm_event_id);
#endif
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_DEV,F("unloading"));
#endif
}
void WiFiManager::_begin(){
if(_hasBegun) return;
_hasBegun = true;
// _usermode = WiFi.getMode();
#ifndef ESP32
WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites
#endif
}
void WiFiManager::_end(){
_hasBegun = false;
if(_userpersistent) WiFi.persistent(true); // reenable persistent, there is no getter we rely on _userpersistent
// if(_usermode != WIFI_OFF) WiFi.mode(_usermode);
}
// AUTOCONNECT
boolean WiFiManager::autoConnect() {
String ssid = getDefaultAPName();
return autoConnect(ssid.c_str(), NULL);
}
/**
* [autoConnect description]
* @access public
* @param {[type]} char const *apName [description]
* @param {[type]} char const *apPassword [description]
* @return {[type]} [description]
*/
boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(F("AutoConnect"));
#endif
// bool wifiIsSaved = getWiFiIsSaved();
bool wifiIsSaved = true; // workaround until I can check esp32 wifiisinit and has nvs
#ifdef ESP32
setupHostname(true);
if(_hostname != ""){
// disable wifi if already on
if(WiFi.getMode() & WIFI_STA){
WiFi.mode(WIFI_OFF);
int timeout = millis()+1200;
// async loop for mode change
while(WiFi.getMode()!= WIFI_OFF && millis()<timeout){
delay(0);
}
}
}
#endif
// check if wifi is saved, (has autoconnect) to speed up cp start
// NOT wifi init safe
if(wifiIsSaved){
_startconn = millis();
_begin();
// attempt to connect using saved settings, on fail fallback to AP config portal
if(!WiFi.enableSTA(true)){
// handle failure mode Brownout detector etc.
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_ERROR,F("[FATAL] Unable to enable wifi!"));
#endif
return false;
}
WiFiSetCountry();
#ifdef ESP32
if(esp32persistent) WiFi.persistent(false); // disable persistent for esp32 after esp_wifi_start or else saves wont work
#endif
_usermode = WIFI_STA; // When using autoconnect , assume the user wants sta mode on permanently.
// no getter for autoreconnectpolicy before this
// https://github.com/esp8266/Arduino/pull/4359
// so we must force it on else, if not connectimeout then waitforconnectionresult gets stuck endless loop
WiFi_autoReconnect();
#ifdef ESP8266
if(_hostname != ""){
setupHostname(true);
}
#endif
// if already connected, or try stored connect
// @note @todo ESP32 has no autoconnect, so connectwifi will always be called unless user called begin etc before
// @todo check if correct ssid == saved ssid when already connected
bool connected = false;
if (WiFi.status() == WL_CONNECTED){
connected = true;
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(F("AutoConnect: ESP Already Connected"));
#endif
setSTAConfig();
// @todo not sure if this is safe, causes dup setSTAConfig in connectwifi,
// and we have no idea WHAT we are connected to
}
if(connected || connectWifi(_defaultssid, _defaultpass) == WL_CONNECTED){
//connected
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(F("AutoConnect: SUCCESS"));
DEBUG_WM(WM_DEBUG_VERBOSE,F("Connected in"),(String)((millis()-_startconn)) + " ms");
DEBUG_WM(F("STA IP Address:"),WiFi.localIP());
#endif
// Serial.println("Connected in " + (String)((millis()-_startconn)) + " ms");
_lastconxresult = WL_CONNECTED;
if(_hostname != ""){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_DEV,F("hostname: STA: "),getWiFiHostname());
#endif
}
return true; // connected success
}
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(F("AutoConnect: FAILED for "),(String)((millis()-_startconn)) + " ms");
#endif
}
else {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(F("No Credentials are Saved, skipping connect"));
#endif
}
// possibly skip the config portal
if (!_enableConfigPortal) {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("enableConfigPortal: FALSE, skipping "));
#endif
return false; // not connected and not cp
}
// not connected start configportal
bool res = startConfigPortal(apName, apPassword);
return res;
}
bool WiFiManager::setupHostname(bool restart){
if(_hostname == "") {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_DEV,F("No Hostname to set"));
#endif
return false;
}
else {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Setting Hostnames: "),_hostname);
#endif
}
bool res = true;
#ifdef ESP8266
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Setting WiFi hostname"));
#endif
res = WiFi.hostname(_hostname.c_str());
// #ifdef ESP8266MDNS_H
#ifdef WM_MDNS
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Setting MDNS hostname, tcp 80"));
#endif
if(MDNS.begin(_hostname.c_str())){
MDNS.addService("http", "tcp", 80);
}
#endif
#elif defined(ESP32)
// @note hostname must be set after STA_START
// @note, this may have changed at some point, now it wont work, I have to set it before.
// same for S2, must set it before mode(STA) now
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Setting WiFi hostname"));
#endif
res = WiFi.setHostname(_hostname.c_str());
// esp_err_t err;
// // err = set_esp_interface_hostname(ESP_IF_WIFI_STA, "TEST_HOSTNAME");
// err = esp_netif_set_hostname(esp_netifs[ESP_IF_WIFI_STA], "TEST_HOSTNAME");
// if(err){
// log_e("Could not set hostname! %d", err);
// return false;
// }
// #ifdef ESP32MDNS_H
#ifdef WM_MDNS
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Setting MDNS hostname, tcp 80"));
#endif
if(MDNS.begin(_hostname.c_str())){
MDNS.addService("http", "tcp", 80);
}
#endif
#endif
#ifdef WM_DEBUG_LEVEL
if(!res)DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] hostname: set failed!"));
#endif
if(restart && (WiFi.status() == WL_CONNECTED)){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("reconnecting to set new hostname"));
#endif
// WiFi.reconnect(); // This does not reset dhcp
WiFi_Disconnect();
delay(200); // do not remove, need a delay for disconnect to change status()
}
return res;
}
// CONFIG PORTAL
bool WiFiManager::startAP(){
bool ret = true;
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(F("StartAP with SSID: "),_apName);
#endif
#ifdef ESP8266
// @bug workaround for bug #4372 https://github.com/esp8266/Arduino/issues/4372
if(!WiFi.enableAP(true)) {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] enableAP failed!"));
#endif
return false;
}
delay(500); // workaround delay
#endif
// setup optional soft AP static ip config
if (_ap_static_ip) {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(F("Custom AP IP/GW/Subnet:"));
#endif
if(!WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn)){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] softAPConfig failed!"));
#endif
}
}
//@todo add callback here if needed to modify ap but cannot use setAPStaticIPConfig
//@todo rework wifi channelsync as it will work unpredictably when not connected in sta
int32_t channel = 0;
if(_channelSync) channel = WiFi.channel();
else channel = _apChannel;
if(channel>0){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Starting AP on channel:"),channel);
#endif
}
// start soft AP with password or anonymous
// default channel is 1 here and in esplib, @todo just change to default remove conditionals
if (_apPassword != "") {
if(channel>0){
ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),channel,_apHidden);
}
else{
ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),1,_apHidden);//password option
}
} else {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("AP has anonymous access!"));
#endif
if(channel>0){
ret = WiFi.softAP(_apName.c_str(),"",channel,_apHidden);
}
else{
ret = WiFi.softAP(_apName.c_str(),"",1,_apHidden);
}
}
if(_debugLevel >= WM_DEBUG_DEV) debugSoftAPConfig();
// @todo add softAP retry here to dela with unknown failures
delay(500); // slight delay to make sure we get an AP IP
#ifdef WM_DEBUG_LEVEL
if(!ret) DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] There was a problem starting the AP"));
DEBUG_WM(F("AP IP address:"),WiFi.softAPIP());
#endif
// set ap hostname
#ifdef ESP32
if(ret && _hostname != ""){
bool res = WiFi.softAPsetHostname(_hostname.c_str());
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("setting softAP Hostname:"),_hostname);
if(!res)DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] hostname: AP set failed!"));
DEBUG_WM(WM_DEBUG_DEV,F("hostname: AP: "),WiFi.softAPgetHostname());
#endif
}
#endif
return ret;
}
/**
* [startWebPortal description]
* @access public
* @return {[type]} [description]
*/
void WiFiManager::startWebPortal() {
if(configPortalActive || webPortalActive) return;
connect = abort = false;
setupConfigPortal();
webPortalActive = true;
}
/**
* [stopWebPortal description]
* @access public
* @return {[type]} [description]
*/
void WiFiManager::stopWebPortal() {
if(!configPortalActive && !webPortalActive) return;
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Stopping Web Portal"));
#endif
webPortalActive = false;
shutdownConfigPortal();
}
boolean WiFiManager::configPortalHasTimeout(){
if(!configPortalActive) return false;
uint16_t logintvl = 30000; // how often to emit timeing out counter logging
// handle timeout portal client check
if(_configPortalTimeout == 0 || (_apClientCheck && (WiFi_softap_num_stations() > 0))){
// debug num clients every 30s
if(millis() - timer > logintvl){
timer = millis();
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("NUM CLIENTS: "),(String)WiFi_softap_num_stations());
#endif
}
_configPortalStart = millis(); // kludge, bump configportal start time to skew timeouts
return false;
}
// handle timeout webclient check
if(_webClientCheck && (_webPortalAccessed>_configPortalStart)>0) _configPortalStart = _webPortalAccessed;
// handle timed out
if(millis() > _configPortalStart + _configPortalTimeout){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(F("config portal has timed out"));
#endif
return true; // timeout bail, else do debug logging
}
else if(_debug && _debugLevel > 0) {
// log timeout time remaining every 30s
if((millis() - timer) > logintvl){
timer = millis();
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal Timeout In"),(String)((_configPortalStart + _configPortalTimeout-millis())/1000) + (String)F(" seconds"));
#endif
}
}
return false;
}
void WiFiManager::setupHTTPServer(){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(F("Starting Web Portal"));
#endif
if(_httpPort != 80) {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("http server started with custom port: "),_httpPort); // @todo not showing ip
#endif
}
server.reset(new WM_WebServer(_httpPort));
// This is not the safest way to reset the webserver, it can cause crashes on callbacks initilized before this and since its a shared pointer...
if ( _webservercallback != NULL) {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] _webservercallback calling"));
#endif
_webservercallback(); // @CALLBACK
}
// @todo add a new callback maybe, after webserver started, callback cannot override handlers, but can grab them first
/* Setup httpd callbacks, web pages: root, wifi config pages, SO captive portal detectors and not found. */
// G macro workaround for Uri() bug https://github.com/esp8266/Arduino/issues/7102
server->on(WM_G(R_root), std::bind(&WiFiManager::handleRoot, this));
server->on(WM_G(R_wifi), std::bind(&WiFiManager::handleWifi, this, true));
server->on(WM_G(R_wifinoscan), std::bind(&WiFiManager::handleWifi, this, false));
server->on(WM_G(R_wifisave), std::bind(&WiFiManager::handleWifiSave, this));
server->on(WM_G(R_info), std::bind(&WiFiManager::handleInfo, this));
server->on(WM_G(R_param), std::bind(&WiFiManager::handleParam, this));
server->on(WM_G(R_paramsave), std::bind(&WiFiManager::handleParamSave, this));
server->on(WM_G(R_restart), std::bind(&WiFiManager::handleReset, this));
server->on(WM_G(R_exit), std::bind(&WiFiManager::handleExit, this));
server->on(WM_G(R_close), std::bind(&WiFiManager::handleClose, this));
server->on(WM_G(R_erase), std::bind(&WiFiManager::handleErase, this, false));
server->on(WM_G(R_status), std::bind(&WiFiManager::handleWiFiStatus, this));
server->onNotFound (std::bind(&WiFiManager::handleNotFound, this));
server->on(WM_G(R_update), std::bind(&WiFiManager::handleUpdate, this));
server->on(WM_G(R_updatedone), HTTP_POST, std::bind(&WiFiManager::handleUpdateDone, this), std::bind(&WiFiManager::handleUpdating, this));
server->begin(); // Web server start
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("HTTP server started"));
#endif
}
void WiFiManager::setupDNSD(){
dnsServer.reset(new DNSServer());
/* Setup the DNS server redirecting all the domains to the apIP */
dnsServer->setErrorReplyCode(DNSReplyCode::NoError);
#ifdef WM_DEBUG_LEVEL
// DEBUG_WM("dns server started port: ",DNS_PORT);
DEBUG_WM(WM_DEBUG_DEV,F("dns server started with ip: "),WiFi.softAPIP()); // @todo not showing ip
#endif
dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP());
}
void WiFiManager::setupConfigPortal() {
setupHTTPServer();
_lastscan = 0; // reset network scan cache
if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan , async
}
boolean WiFiManager::startConfigPortal() {
String ssid = getDefaultAPName();
return startConfigPortal(ssid.c_str(), NULL);
}
/**
* [startConfigPortal description]
* @access public
* @param {[type]} char const *apName [description]
* @param {[type]} char const *apPassword [description]
* @return {[type]} [description]
*/
boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) {
_begin();
if(configPortalActive){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Starting Config Portal FAILED, is already running"));
#endif
return false;
}
//setup AP
_apName = apName; // @todo check valid apname ?
_apPassword = apPassword;
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Starting Config Portal"));
#endif
if(_apName == "") _apName = getDefaultAPName();
if(!validApPassword()) return false;
// HANDLE issues with STA connections, shutdown sta if not connected, or else this will hang channel scanning and softap will not respond
if(_disableSTA || (!WiFi.isConnected() && _disableSTAConn)){
// this fixes most ap problems, however, simply doing mode(WIFI_AP) does not work if sta connection is hanging, must `wifi_station_disconnect`
#ifdef WM_DISCONWORKAROUND
WiFi.mode(WIFI_AP_STA);
#endif
WiFi_Disconnect();
WiFi_enableSTA(false);
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Disabling STA"));
#endif
}
else {
// WiFi_enableSTA(true);
}
// init configportal globals to known states
configPortalActive = true;
bool result = connect = abort = false; // loop flags, connect true success, abort true break
uint8_t state;
_configPortalStart = millis();
// start access point
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Enabling AP"));
#endif
startAP();
WiFiSetCountry();
// do AP callback if set
if ( _apcallback != NULL) {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] _apcallback calling"));
#endif
_apcallback(this);
}
// init configportal
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_DEV,F("setupConfigPortal"));
#endif
setupConfigPortal();
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_DEV,F("setupDNSD"));
#endif
setupDNSD();
if(!_configPortalIsBlocking){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Config Portal Running, non blocking (processing)"));
if(_configPortalTimeout > 0) DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal Timeout In"),(String)(_configPortalTimeout/1000) + (String)F(" seconds"));
#endif
return result; // skip blocking loop
}
// enter blocking loop, waiting for config
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Config Portal Running, blocking, waiting for clients..."));
if(_configPortalTimeout > 0) DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal Timeout In"),(String)(_configPortalTimeout/1000) + (String)F(" seconds"));
#endif
while(1){
// if timed out or abort, break
if(configPortalHasTimeout() || abort){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_DEV,F("configportal loop abort"));
#endif
shutdownConfigPortal();
result = abort ? portalAbortResult : portalTimeoutResult; // false, false
if (_configportaltimeoutcallback != NULL) {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] config portal timeout callback"));
#endif
_configportaltimeoutcallback(); // @CALLBACK
}
break;
}
state = processConfigPortal();
// status change, break
// @todo what is this for, should be moved inside the processor
// I think.. this is to detect autoconnect by esp in background, there are also many open issues about autoreconnect not working
if(state != WL_IDLE_STATUS){
result = (state == WL_CONNECTED); // true if connected
DEBUG_WM(WM_DEBUG_DEV,F("configportal loop break"));
break;
}
if(!configPortalActive) break;
yield(); // watchdog
}
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_NOTIFY,F("config portal exiting"));
#endif
return result;
}
/**
* [process description]
* @access public
* @return bool connected
*/
boolean WiFiManager::process(){
// process mdns, esp32 not required
#if defined(WM_MDNS) && defined(ESP8266)
MDNS.update();
#endif
if(webPortalActive || (configPortalActive && !_configPortalIsBlocking)){
// if timed out or abort, break
if(_allowExit && (configPortalHasTimeout() || abort)){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_DEV,F("process loop abort"));
#endif
webPortalActive = false;
shutdownConfigPortal();
if (_configportaltimeoutcallback != NULL) {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] config portal timeout callback"));
#endif
_configportaltimeoutcallback(); // @CALLBACK
}
return false;
}
uint8_t state = processConfigPortal(); // state is WL_IDLE or WL_CONNECTED/FAILED
return state == WL_CONNECTED;
}
return false;
}
/**
* [processConfigPortal description]
* using esp wl_status enums as returns for now, should be fine
* returns WL_IDLE_STATUS or WL_CONNECTED/WL_CONNECT_FAILED upon connect/save flag
*
* @return {[type]} [description]
*/
uint8_t WiFiManager::processConfigPortal(){
if(configPortalActive){
//DNS handler
dnsServer->processNextRequest();
}
//HTTP handler
server->handleClient();
// Waiting for save...
if(connect) {
connect = false;
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("processing save"));
#endif
if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast.
// skip wifi if no ssid
if(_ssid == ""){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("No ssid, skipping wifi save"));
#endif
}
else{
// attempt sta connection to submitted _ssid, _pass
uint8_t res = connectWifi(_ssid, _pass, _connectonsave) == WL_CONNECTED;
if (res || (!_connectonsave)) {
#ifdef WM_DEBUG_LEVEL
if(!_connectonsave){
DEBUG_WM(F("SAVED with no connect to new AP"));
} else {
DEBUG_WM(F("Connect to new AP [SUCCESS]"));
DEBUG_WM(F("Got IP Address:"));
DEBUG_WM(WiFi.localIP());
}
#endif
if ( _savewificallback != NULL) {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] _savewificallback calling"));
#endif
_savewificallback(); // @CALLBACK
}
if(!_connectonsave) return WL_IDLE_STATUS;
if(_disableConfigPortal) shutdownConfigPortal();
return WL_CONNECTED; // CONNECT SUCCESS
}
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] Connect to new AP Failed"));
#endif
}
if (_shouldBreakAfterConfig) {
// do save callback
// @todo this is more of an exiting callback than a save, clarify when this should actually occur
// confirm or verify data was saved to make this more accurate callback
if ( _savewificallback != NULL) {
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("[CB] WiFi/Param save callback"));
#endif
_savewificallback(); // @CALLBACK
}
if(_disableConfigPortal) shutdownConfigPortal();
return WL_CONNECT_FAILED; // CONNECT FAIL
}
else if(_configPortalIsBlocking){
// clear save strings
_ssid = "";
_pass = "";
// if connect fails, turn sta off to stabilize AP
WiFi_Disconnect();
WiFi_enableSTA(false);
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Processing - Disabling STA"));
#endif
}
else{
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("Portal is non blocking - remaining open"));
#endif
}
}
return WL_IDLE_STATUS;
}
/**
* [shutdownConfigPortal description]
* @access public
* @return bool success (softapdisconnect)
*/
bool WiFiManager::shutdownConfigPortal(){
#ifdef WM_DEBUG_LEVEL
DEBUG_WM(WM_DEBUG_VERBOSE,F("shutdownConfigPortal"));
#endif
if(webPortalActive) return false;
if(configPortalActive){
//DNS handler
dnsServer->processNextRequest();
}
//HTTP handler
server->handleClient();
// @todo what is the proper way to shutdown and free the server up
// debug - many open issues aobut port not clearing for use with other servers
server->stop();
server.reset();
WiFi.scanDelete(); // free wifi scan results
if(!configPortalActive) return false;
dnsServer->stop(); // free heap ?
dnsServer.reset();
// turn off AP
// @todo bug workaround
// https://github.com/esp8266/Arduino/issues/3793
// [APdisconnect] set_config failed! *WM: disconnect configportal - softAPdisconnect failed
// still no way to reproduce reliably
bool ret = false;
ret = WiFi.softAPdisconnect(false);
#ifdef WM_DEBUG_LEVEL
if(!ret)DEBUG_WM(WM_DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED"));
DEBUG_WM(WM_DEBUG_VERBOSE,F("restoring usermode"),getModeString(_usermode));
#endif
delay(1000);
WiFi_Mode(_usermode); // restore users wifi mode, BUG https://github.com/esp8266/Arduino/issues/4372
if(WiFi.status()==WL_IDLE_STATUS){
WiFi.reconnect(); // restart wifi since we disconnected it in startconfigportal