-
Notifications
You must be signed in to change notification settings - Fork 0
/
WiFiManager.cpp
2817 lines (2484 loc) · 84.2 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 = 1;
_value = NULL;
_labelPlacement = WFM_LABEL_BEFORE;
_customHTML = custom;
}
WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label) {
init(id, label, "", 0, "", WFM_LABEL_BEFORE);
}
WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length) {
init(id, label, defaultValue, length, "", WFM_LABEL_BEFORE);
}
WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom) {
init(id, label, defaultValue, length, custom, WFM_LABEL_BEFORE);
}
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;
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
}
// @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
// }
_length = length;
_value = new char[_length + 1];
memset(_value, 0, _length + 1); // explicit null
if (defaultValue != NULL) {
strncpy(_value, defaultValue, _length);
}
}
const char* WiFiManagerParameter::getValue() {
return _value;
}
const char* WiFiManagerParameter::getID() {
return _id;
}
const char* WiFiManagerParameter::getPlaceholder() {
return _label;
}
const char* WiFiManagerParameter::getLabel() {
return _label;
}
int WiFiManagerParameter::getValueLength() {
return _length;
}
int WiFiManagerParameter::getLabelPlacement() {
return _labelPlacement;
}
const char* WiFiManagerParameter::getCustomHTML() {
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]=='_')){
DEBUG_WM(DEBUG_ERROR,"[ERROR] parameter IDs can only contain alpha numeric chars");
return false;
}
}
}
// init params if never malloc
if(_params == NULL){
DEBUG_WM(DEBUG_DEV,"allocating params bytes:",_max_params * sizeof(WiFiManagerParameter*));
_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;
DEBUG_WM(DEBUG_DEV,F("Updated _max_params:"),_max_params);
DEBUG_WM(DEBUG_DEV,"re-allocating params bytes:",_max_params * sizeof(WiFiManagerParameter*));
WiFiManagerParameter** new_params = (WiFiManagerParameter**)realloc(_params, _max_params * sizeof(WiFiManagerParameter*));
// DEBUG_WM(WIFI_MANAGER_MAX_PARAMS);
// DEBUG_WM(_paramsCount);
// DEBUG_WM(_max_params);
if (new_params != NULL) {
_params = new_params;
} else {
DEBUG_WM(DEBUG_ERROR,"[ERROR] failed to realloc params, size not increased!");
return false;
}
}
_params[_paramsCount] = p;
_paramsCount++;
DEBUG_WM(DEBUG_VERBOSE,"Added Parameter:",p->getID());
return true;
}
/**
* [getParameters description]
* @access public
*/
WiFiManagerParameter** WiFiManager::getParameters() {
return _params;
}
/**
* [getParametersCount description]
* @access public
*/
int WiFiManager::getParametersCount() {
return _paramsCount;
}
/**
* --------------------------------------------------------------------------------
* WiFiManager
* --------------------------------------------------------------------------------
**/
// constructors
WiFiManager::WiFiManager(Stream& consolePort):_debugPort(consolePort){
WiFiManagerInit();
}
WiFiManager::WiFiManager():WiFiManager(Serial) {
}
void WiFiManager::WiFiManagerInit(){
setMenu(_menuIdsDefault);
if(_debug && _debugLevel > DEBUG_DEV) debugPlatformInfo();
_max_params = WIFI_MANAGER_MAX_PARAMS;
}
// destructor
WiFiManager::~WiFiManager() {
_end();
// parameters
// @todo below belongs to wifimanagerparameter
if (_params != NULL){
DEBUG_WM(DEBUG_DEV,F("freeing allocated params!"));
free(_params);
_params = NULL;
}
// @todo remove event
// #ifdef ESP32
// WiFi.removeEvent(std::bind(&WiFiManager::WiFiEvent,this));
// #endif
DEBUG_WM(DEBUG_DEV,F("unloading"));
}
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) {
DEBUG_WM(F("AutoConnect"));
_begin();
// attempt to connect using saved settings, on fail fallback to AP config portal
if(!WiFi.enableSTA(true)){
// handle failure mode Brownout detector etc.
DEBUG_WM(DEBUG_ERROR,"[FATAL] Unable to enable wifi!");
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;
// 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();
// set hostname before stating
if((String)_hostname != ""){
DEBUG_WM(DEBUG_VERBOSE,"Setting hostname:",_hostname);
bool res = true;
#ifdef ESP8266
res = WiFi.hostname(_hostname);
#ifdef ESP8266MDNS_H
DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname");
if(MDNS.begin(_hostname)){
MDNS.addService("http", "tcp", 80);
}
#endif
#elif defined(ESP32)
// @note hostname must be set after STA_START
delay(200); // do not remove, give time for STA_START
res = WiFi.setHostname(_hostname);
#ifdef ESP32MDNS_H
DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname");
if(MDNS.begin(_hostname)){
MDNS.addService("http", "tcp", 80);
}
#endif
#endif
if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: set failed!"));
if(WiFi.status() == WL_CONNECTED){
DEBUG_WM(DEBUG_VERBOSE,F("reconnecting to set new hostname"));
// WiFi.reconnect(); // This does not reset dhcp
WiFi_Disconnect();
delay(200); // do not remove, need a delay for disconnect to change status()
}
}
// 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;
DEBUG_WM(F("AutoConnect: ESP Already Connected"));
setSTAConfig();
}
if(connected || connectWifi("", "") == WL_CONNECTED){
//connected
DEBUG_WM(F("AutoConnect: SUCCESS"));
DEBUG_WM(F("STA IP Address:"),WiFi.localIP());
_lastconxresult = WL_CONNECTED;
if((String)_hostname != ""){
#ifdef ESP8266
DEBUG_WM(DEBUG_DEV,"hostname: STA",WiFi.hostname());
#elif defined(ESP32)
DEBUG_WM(DEBUG_DEV,"hostname: STA",WiFi.getHostname());
#endif
}
return true;
}
// possibly skip the config portal
if (!_enableConfigPortal) {
return false;
}
DEBUG_WM(F("AutoConnect: FAILED"));
// not connected start configportal
return startConfigPortal(apName, apPassword);
}
// CONFIG PORTAL
bool WiFiManager::startAP(){
bool ret = true;
DEBUG_WM(F("StartAP with SSID: "),_apName);
#ifdef ESP8266
// @bug workaround for bug #4372 https://github.com/esp8266/Arduino/issues/4372
if(!WiFi.enableAP(true)) {
DEBUG_WM(DEBUG_ERROR,"[ERROR] enableAP failed!");
return false;
}
delay(500); // workaround delay
#endif
// setup optional soft AP static ip config
if (_ap_static_ip) {
DEBUG_WM(F("Custom AP IP/GW/Subnet:"));
if(!WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn)){
DEBUG_WM(DEBUG_ERROR,"[ERROR] softAPConfig failed!");
}
}
//@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){
DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",channel);
}
// start soft AP with password or anonymous
if (_apPassword != "") {
if(channel>0){
ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),channel);
}
else{
ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str());//password option
}
} else {
DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!"));
if(channel>0){
ret = WiFi.softAP(_apName.c_str(),"",channel);
}
else{
ret = WiFi.softAP(_apName.c_str());
}
}
if(_debugLevel >= DEBUG_DEV) debugSoftAPConfig();
if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] There was a problem starting the AP");
// @todo add softAP retry here
delay(500); // slight delay to make sure we get an AP IP
DEBUG_WM(F("AP IP address:"),WiFi.softAPIP());
// set ap hostname
#ifdef ESP32
if(ret && (String)_hostname != ""){
DEBUG_WM(DEBUG_VERBOSE,"setting softAP Hostname:",_hostname);
bool res = WiFi.softAPsetHostname(_hostname);
if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: AP set failed!"));
DEBUG_WM(DEBUG_DEV,F("hostname: AP"),WiFi.softAPgetHostname());
}
#endif
return ret;
}
/**
* [startWebPortal description]
* @access public
* @return {[type]} [description]
*/
void WiFiManager::startWebPortal() {
if(configPortalActive || webPortalActive) return;
setupConfigPortal();
webPortalActive = true;
}
/**
* [stopWebPortal description]
* @access public
* @return {[type]} [description]
*/
void WiFiManager::stopWebPortal() {
if(!configPortalActive && !webPortalActive) return;
DEBUG_WM(DEBUG_VERBOSE,F("Stopping Web Portal"));
webPortalActive = false;
shutdownConfigPortal();
}
boolean WiFiManager::configPortalHasTimeout(){
if(_configPortalTimeout == 0 || (_apClientCheck && (WiFi_softap_num_stations() > 0))){
if(millis() - timer > 30000){
timer = millis();
DEBUG_WM(DEBUG_VERBOSE,"NUM CLIENTS: " + (String)WiFi_softap_num_stations());
}
_configPortalStart = millis(); // kludge, bump configportal start time to skew timeouts
return false;
}
// handle timeout
if(_webClientCheck && (_webPortalAccessed>_configPortalStart)>0) _configPortalStart = _webPortalAccessed;
if(millis() > _configPortalStart + _configPortalTimeout){
DEBUG_WM(F("config portal has timed out"));
return true;
} else if(_debugLevel > 0) {
// log timeout
if(_debug){
uint16_t logintvl = 30000; // how often to emit timeing out counter logging
if((millis() - timer) > logintvl){
timer = millis();
DEBUG_WM(DEBUG_VERBOSE,F("Portal Timeout In"),(String)((_configPortalStart + _configPortalTimeout-millis())/1000) + (String)F(" seconds"));
}
}
}
return false;
}
void WiFiManager::setupConfigPortal() {
DEBUG_WM(F("Starting Web Portal"));
// setup dns and web servers
dnsServer.reset(new DNSServer());
server.reset(new WM_WebServer(80));
/* Setup the DNS server redirecting all the domains to the apIP */
dnsServer->setErrorReplyCode(DNSReplyCode::NoError);
// DEBUG_WM("dns server started port: ",DNS_PORT);
DEBUG_WM(DEBUG_DEV,"dns server started with ip: ",WiFi.softAPIP());
dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP());
// @todo new callback, webserver started, callback cannot override handlers, but can grab them first
if ( _webservercallback != NULL) {
_webservercallback();
}
/* Setup httpd callbacks, web pages: root, wifi config pages, SO captive portal detectors and not found. */
server->on(String(FPSTR(R_root)).c_str(), std::bind(&WiFiManager::handleRoot, this));
server->on(String(FPSTR(R_wifi)).c_str(), std::bind(&WiFiManager::handleWifi, this, true));
server->on(String(FPSTR(R_wifinoscan)).c_str(), std::bind(&WiFiManager::handleWifi, this, false));
server->on(String(FPSTR(R_wifisave)).c_str(), std::bind(&WiFiManager::handleWifiSave, this));
server->on(String(FPSTR(R_info)).c_str(), std::bind(&WiFiManager::handleInfo, this));
server->on(String(FPSTR(R_param)).c_str(), std::bind(&WiFiManager::handleParam, this));
server->on(String(FPSTR(R_paramsave)).c_str(), std::bind(&WiFiManager::handleParamSave, this));
server->on(String(FPSTR(R_restart)).c_str(), std::bind(&WiFiManager::handleReset, this));
server->on(String(FPSTR(R_exit)).c_str(), std::bind(&WiFiManager::handleExit, this));
server->on(String(FPSTR(R_close)).c_str(), std::bind(&WiFiManager::handleClose, this));
server->on(String(FPSTR(R_erase)).c_str(), std::bind(&WiFiManager::handleErase, this, false));
server->on(String(FPSTR(R_status)).c_str(), std::bind(&WiFiManager::handleWiFiStatus, this));
server->onNotFound (std::bind(&WiFiManager::handleNotFound, this));
server->begin(); // Web server start
DEBUG_WM(DEBUG_VERBOSE,F("HTTP server started"));
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();
//setup AP
_apName = apName; // @todo check valid apname ?
_apPassword = apPassword;
DEBUG_WM(DEBUG_VERBOSE,F("Starting Config Portal"));
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
// @todo sometimes still cannot connect to AP for no known reason, no events in log either
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`
WiFi_Disconnect();
WiFi_enableSTA(false);
DEBUG_WM(DEBUG_VERBOSE,F("Disabling STA"));
}
else {
// @todo even if sta is connected, it is possible that softap connections will fail, IOS says "invalid password", windows says "cannot connect to this network" researching
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
DEBUG_WM(DEBUG_VERBOSE,F("Enabling AP"));
startAP();
WiFiSetCountry();
// do AP callback if set
if ( _apcallback != NULL) {
_apcallback(this);
}
// init configportal
DEBUG_WM(DEBUG_DEV,F("setupConfigPortal"));
setupConfigPortal();
if(!_configPortalIsBlocking){
DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, non blocking/processing"));
return result;
}
DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, blocking, waiting for clients..."));
// blocking loop waiting for config
while(1){
// if timed out or abort, break
if(configPortalHasTimeout() || abort){
DEBUG_WM(DEBUG_DEV,F("configportal abort"));
shutdownConfigPortal();
result = abort ? portalAbortResult : portalTimeoutResult; // false, false
break;
}
state = processConfigPortal();
// status change, break
if(state != WL_IDLE_STATUS){
result = (state == WL_CONNECTED); // true if connected
break;
}
yield(); // watchdog
}
DEBUG_WM(DEBUG_NOTIFY,F("config portal exiting"));
return result;
}
/**
* [process description]
* @access public
* @return {[type]} [description]
*/
boolean WiFiManager::process(){
if(webPortalActive || (configPortalActive && !_configPortalIsBlocking)){
uint8_t state = processConfigPortal();
return state == WL_CONNECTED;
}
return false;
}
//using esp enums returns for now, should be fine
uint8_t WiFiManager::processConfigPortal(){
//DNS handler
dnsServer->processNextRequest();
//HTTP handler
server->handleClient();
// Waiting for save...
if(connect) {
connect = false;
DEBUG_WM(DEBUG_VERBOSE,F("process connect"));
if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast.
// skip wifi if no ssid
if(_ssid == ""){
DEBUG_WM(DEBUG_VERBOSE,F("No ssid, skipping wifi"));
}
else{
// attempt sta connection to submitted _ssid, _pass
if (connectWifi(_ssid, _pass) == WL_CONNECTED) {
DEBUG_WM(F("Connect to new AP [SUCCESS]"));
DEBUG_WM(F("Got IP Address:"));
DEBUG_WM(WiFi.localIP());
if ( _savewificallback != NULL) {
_savewificallback();
}
shutdownConfigPortal();
return WL_CONNECTED; // CONNECT SUCCESS
}
DEBUG_WM(DEBUG_ERROR,F("[ERROR] Connect to new AP Failed"));
}
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) {
_savewificallback();
}
shutdownConfigPortal();
return WL_CONNECT_FAILED; // CONNECT FAIL
}
else{
// clear save strings
_ssid = "";
_pass = "";
// if connect fails, turn sta off to stabilize AP
WiFi_Disconnect();
WiFi_enableSTA(false);
DEBUG_WM(DEBUG_VERBOSE,F("Disabling STA"));
}
}
return WL_IDLE_STATUS;
}
/**
* [shutdownConfigPortal description]
* @access public
* @return bool success (softapdisconnect)
*/
bool WiFiManager::shutdownConfigPortal(){
if(webPortalActive) return false;
//DNS handler
dnsServer->processNextRequest();
//HTTP handler
server->handleClient();
// @todo what is the proper way to shutdown and free the server up
server->stop();
server.reset();
dnsServer->stop(); // free heap ?
dnsServer.reset();
WiFi.scanDelete(); // free wifi scan results
if(!configPortalActive) return false;
// 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
DEBUG_WM(DEBUG_VERBOSE,F("disconnect configportal"));
bool ret = false;
ret = WiFi.softAPdisconnect(false);
if(!ret)DEBUG_WM(DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED"));
delay(1000);
DEBUG_WM(DEBUG_VERBOSE,"restoring usermode",getModeString(_usermode));
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
DEBUG_WM(DEBUG_VERBOSE,"WiFi Reconnect, was idle");
}
DEBUG_WM(DEBUG_VERBOSE,"wifi status:",getWLStatusString(WiFi.status()));
DEBUG_WM(DEBUG_VERBOSE,"wifi mode:",getModeString(WiFi.getMode()));
configPortalActive = false;
_end();
return ret;
}
// @todo refactor this up into seperate functions
// one for connecting to flash , one for new client
// clean up, flow is convoluted, and causes bugs
uint8_t WiFiManager::connectWifi(String ssid, String pass) {
DEBUG_WM(DEBUG_VERBOSE,F("Connecting as wifi client..."));
uint8_t connRes = (uint8_t)WL_NO_SSID_AVAIL;
setSTAConfig();
//@todo catch failures in set_config
// make sure sta is on before `begin` so it does not call enablesta->mode while persistent is ON ( which would save WM AP state to eeprom !)
if(_cleanConnect) WiFi_Disconnect(); // disconnect before begin, in case anything is hung, this causes a 2 seconds delay for connect
// @todo find out what status is when this is needed, can we detect it and handle it, say in between states or idle_status
// if ssid argument provided connect to that
if (ssid != "") {
wifiConnectNew(ssid,pass);
if(_saveTimeout > 0){
connRes = waitForConnectResult(_saveTimeout); // use default save timeout for saves to prevent bugs in esp->waitforconnectresult loop
}
else {
connRes = waitForConnectResult(0);
}
}
else {
// connect using saved ssid if there is one
if (WiFi_hasAutoConnect()) {
wifiConnectDefault();
connRes = waitForConnectResult();
}
else {
DEBUG_WM(F("No saved credentials, skipping wifi"));
}
}
DEBUG_WM(DEBUG_VERBOSE,F("Connection result:"),getWLStatusString(connRes));
// WPS enabled? https://github.com/esp8266/Arduino/pull/4889
#ifdef NO_EXTRA_4K_HEAP
// do WPS, if WPS options enabled and not connected and no password was supplied
// @todo this seems like wrong place for this, is it a fallback or option?
if (_tryWPS && connRes != WL_CONNECTED && pass == "") {
startWPS();
// should be connected at the end of WPS
connRes = waitForConnectResult();
}
#endif
if(connRes != WL_SCAN_COMPLETED){
updateConxResult(connRes);
}
return connRes;
}
/**
* connect to a new wifi ap
* @since $dev
* @param String ssid
* @param String pass
* @return bool success
*/
bool WiFiManager::wifiConnectNew(String ssid, String pass){
bool ret = false;
DEBUG_WM(F("CONNECTED:"),WiFi.status() == WL_CONNECTED);
DEBUG_WM(F("Connecting to NEW AP:"),ssid);
DEBUG_WM(DEBUG_DEV,F("Using Password:"),pass);
WiFi_enableSTA(true,storeSTAmode); // storeSTAmode will also toggle STA on in default opmode (persistent) if true (default)
WiFi.persistent(true);
ret = WiFi.begin(ssid.c_str(), pass.c_str());
WiFi.persistent(false);
if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed");
return ret;
}
/**
* connect to stored wifi
* @since dev
* @return bool success
*/
bool WiFiManager::wifiConnectDefault(){
bool ret = false;
DEBUG_WM(F("Connecting to SAVED AP:"),WiFi_SSID(true));
DEBUG_WM(DEBUG_DEV,F("Using Password:"),WiFi_psk(true));
ret = WiFi_enableSTA(true,storeSTAmode);
if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi enableSta failed");
ret = WiFi.begin();
if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed");
return ret;
}
/**
* set sta config if set
* @since $dev
* @return bool success
*/
bool WiFiManager::setSTAConfig(){
DEBUG_WM(F("STA static IP:"),_sta_static_ip);
bool ret = true;
if (_sta_static_ip) {
DEBUG_WM(DEBUG_VERBOSE,F("Custom static IP/GW/Subnet/DNS"));
if(_sta_static_dns) {
DEBUG_WM(DEBUG_VERBOSE,F("Custom static DNS"));
ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn, _sta_static_dns);
}
else {
DEBUG_WM(DEBUG_VERBOSE,F("Custom STA IP/GW/Subnet"));
ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn);
}
if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi config failed");
else DEBUG_WM(F("STA IP set:"),WiFi.localIP());
} else {
DEBUG_WM(DEBUG_VERBOSE,F("setSTAConfig static ip not set"));
}
return ret;
}
// @todo change to getLastFailureReason and do not touch conxresult
void WiFiManager::updateConxResult(uint8_t status){
// hack in wrong password detection
_lastconxresult = status;
#ifdef ESP8266
if(_lastconxresult == WL_CONNECT_FAILED){
if(wifi_station_get_connect_status() == STATION_WRONG_PASSWORD){
_lastconxresult = WL_STATION_WRONG_PASSWORD;
}
}
#elif defined(ESP32)
// if(_lastconxresult == WL_CONNECT_FAILED){
if(_lastconxresult == WL_CONNECT_FAILED || _lastconxresult == WL_DISCONNECTED){
DEBUG_WM(DEBUG_DEV,"lastconxresulttmp:",getWLStatusString(_lastconxresulttmp));
if(_lastconxresulttmp != WL_IDLE_STATUS){
_lastconxresult = _lastconxresulttmp;
// _lastconxresulttmp = WL_IDLE_STATUS;
}
}
#endif
DEBUG_WM(DEBUG_DEV,"lastconxresult:",getWLStatusString(_lastconxresult));
}
uint8_t WiFiManager::waitForConnectResult() {
if(_connectTimeout > 0) DEBUG_WM(DEBUG_VERBOSE,_connectTimeout,F("ms connectTimeout set"));
return waitForConnectResult(_connectTimeout);
}
/**
* waitForConnectResult
* @param uint16_t timeout in seconds
* @return uint8_t WL Status
*/
uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) {
if (timeout == 0){
DEBUG_WM(F("connectTimeout not set, ESP waitForConnectResult..."));
return WiFi.waitForConnectResult();
}
unsigned long timeoutmillis = millis() + timeout;
DEBUG_WM(DEBUG_VERBOSE,timeout,F("ms timeout, waiting for connect..."));
uint8_t status = WiFi.status();
while(millis() < timeoutmillis) {
status = WiFi.status();
// @todo detect additional states, connect happens, then dhcp then get ip, there is some delay here, make sure not to timeout if waiting on IP
if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) {
return status;
}
DEBUG_WM (DEBUG_VERBOSE,F("."));
delay(100);
}
return status;
}
// WPS enabled? https://github.com/esp8266/Arduino/pull/4889
#ifdef NO_EXTRA_4K_HEAP
void WiFiManager::startWPS() {
DEBUG_WM(F("START WPS"));
#ifdef ESP8266
WiFi.beginWPSConfig();
#else
// @todo
#endif
DEBUG_WM(F("END WPS"));
}
#endif
String WiFiManager::getHTTPHead(String title){
String page;
page += FPSTR(HTTP_HEAD_START);
page.replace(FPSTR(T_v), title);
page += FPSTR(HTTP_SCRIPT);
page += FPSTR(HTTP_STYLE);
page += _customHeadElement;
if(_bodyClass != ""){
String p = FPSTR(HTTP_HEAD_END);
p.replace(FPSTR(T_c), _bodyClass); // add class str
page += p;
}
else {
page += FPSTR(HTTP_HEAD_END);
}
return page;
}
/**
* HTTPD handler for page requests
*/
void WiFiManager::handleRequest() {
_webPortalAccessed = millis();
}
/**
* HTTPD CALLBACK root or redirect to captive portal
*/
void WiFiManager::handleRoot() {
DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Root"));
if (captivePortal()) return; // If captive portal redirect instead of displaying the page
handleRequest();
String page = getHTTPHead(FPSTR(S_options)); // @token options
String str = FPSTR(HTTP_ROOT_MAIN);
str.replace(FPSTR(T_v),configPortalActive ? _apName : WiFi.localIP().toString()); // use ip if ap is not active for heading
page += str;
page += FPSTR(HTTP_PORTAL_OPTIONS);
page += getMenuOut();
reportStatus(page);
page += FPSTR(HTTP_END);
server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length()));
server->send(200, FPSTR(HTTP_HEAD_CT), page);
// server->close(); // testing reliability fix for content length mismatches during mutiple flood hits WiFi_scanNetworks(); // preload wifiscan
if(_preloadwifiscan) WiFi_scanNetworks(_scancachetime,true); // preload wifiscan throttled, async
// @todo buggy, captive portals make a query on every page load, causing this to run every time in addition to the real page load
// I dont understand why, when you are already in the captive portal, I guess they want to know that its still up and not done or gone
// if we can detect these and ignore them that would be great, since they come from the captive portal redirect maybe there is a refferer
}
/**
* HTTPD CALLBACK Wifi config page handler
*/
void WiFiManager::handleWifi(boolean scan) {
DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Wifi"));
handleRequest();
String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi
if (scan) {
// DEBUG_WM(DEBUG_DEV,"refresh flag:",server->hasArg(F("refresh")));
WiFi_scanNetworks(server->hasArg(F("refresh")),false); //wifiscan, force if arg refresh
page += getScanItemOut();
}
String pitem = "";
pitem = FPSTR(HTTP_FORM_START);
pitem.replace(FPSTR(T_v), F("wifisave")); // set form action
page += pitem;
pitem = FPSTR(HTTP_FORM_WIFI);
pitem.replace(FPSTR(T_v), WiFi_SSID());
page += pitem;
page += getStaticOut();
page += FPSTR(HTTP_FORM_WIFI_END);
if(_paramsInWifi && _paramsCount>0){
page += FPSTR(HTTP_FORM_PARAM_HEAD);
page += getParamOut();
}
page += FPSTR(HTTP_FORM_END);
page += FPSTR(HTTP_SCAN_LINK);
reportStatus(page);
page += FPSTR(HTTP_END);
server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length()));
server->send(200, FPSTR(HTTP_HEAD_CT), page);
// server->close(); // testing reliability fix for content length mismatches during mutiple flood hits
DEBUG_WM(DEBUG_DEV,F("Sent config page"));
}
/**
* HTTPD CALLBACK Wifi param page handler
*/
void WiFiManager::handleParam(){
DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Param"));
handleRequest();