From 8f90e0f5d75a4c422ff9cc105ffb259f31f8794b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Mon, 26 Jun 2017 15:04:57 +0200 Subject: [PATCH 001/146] Add a callback when reset settings is triggered --- WiFiManager.cpp | 7 +++++++ WiFiManager.h | 3 +++ 2 files changed, 10 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 84d16fd..8784bda 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -336,6 +336,8 @@ void WiFiManager::resetSettings() { DEBUG_WM(F("settings invalidated")); DEBUG_WM(F("THIS MAY CAUSE AP NOT TO START UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA.")); WiFi.disconnect(true); + if (_resetcallback != NULL) + _resetcallback(); //delay(200); } void WiFiManager::setTimeout(unsigned long seconds) { @@ -727,6 +729,11 @@ void WiFiManager::setSaveConfigCallback( void (*func)(void) ) { _savecallback = func; } +//start up reset config callback +void WiFiManager::setConfigResetCallback(void(*func)(void)) { + _resetcallback = func; +} + //sets a custom element to add to head, like a new style tag void WiFiManager::setCustomHeadElement(const char* element) { _customHeadElement = element; diff --git a/WiFiManager.h b/WiFiManager.h index 4e45aed..f4f2abc 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -99,6 +99,8 @@ class WiFiManager void setAPCallback( void (*func)(WiFiManager*) ); //called when settings have been changed and connection was successful void setSaveConfigCallback( void (*func)(void) ); + //called when settings reset have been triggered + void setConfigResetCallback(void(*func)(void)); //adds a custom parameter void addParameter(WiFiManagerParameter *p); //if this is set, it will exit after config, even if connection is unsucessful. @@ -175,6 +177,7 @@ class WiFiManager void (*_apcallback)(WiFiManager*) = NULL; void (*_savecallback)(void) = NULL; + void (*_resetcallback)(void) = NULL; WiFiManagerParameter* _params[WIFI_MANAGER_MAX_PARAMS]; From 5a6a365f0af73313773655c8d4b0f3a0fbd9b2a6 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Mon, 26 Feb 2018 22:11:43 -0600 Subject: [PATCH 002/146] Update CONTRIBUTING.md --- .github/CONTRIBUTING.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index a7dbf8b..6760b62 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -7,3 +7,6 @@ Please test against development branch before submitting issues, issues against PRs against master may be kept open if provides something useful to other members. Please open issues before sumbitting PRs against development, as commits might be occuring very frequently. + +### Documentation is in progress +https://github.com/tzapu/WiFiManager/issues/500 From 108af72d5f2ee73713dc29ae7b697822990fbc0e Mon Sep 17 00:00:00 2001 From: Shawn A Date: Fri, 2 Mar 2018 12:42:20 -0600 Subject: [PATCH 003/146] Update ISSUE_TEMPLATE.md --- .github/ISSUE_TEMPLATE.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 5700570..e77edf6 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -7,6 +7,8 @@ https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/stack_dump.rs for better debug messages: https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/debugging.rst +## PLEASE TRY DEVELOPMENT BRANCH BEFORE SUBMITTING BUGS ON RELEAASE, IN CASE THEY WERE ALREADY FIXED. ## + ----------------------------- Remove above ----------------------------- ### Basic Infos From 4f86945d7e4ddf4c4a959c4dd1c4ebb0b4fa2b9b Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 15 Mar 2018 07:44:26 -0500 Subject: [PATCH 004/146] Update ISSUE_TEMPLATE.md --- .github/ISSUE_TEMPLATE.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index e77edf6..2deb942 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,3 +1,6 @@ +## PLEASE TRY DEVELOPMENT BRANCH before submitting bugs on release or master, in case they were already fixed. ## + +Issues without basic info will be ignored or closed! Please fill the info fields, it helps to get you faster support ;) @@ -7,8 +10,6 @@ https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/stack_dump.rs for better debug messages: https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/debugging.rst -## PLEASE TRY DEVELOPMENT BRANCH BEFORE SUBMITTING BUGS ON RELEAASE, IN CASE THEY WERE ALREADY FIXED. ## - ----------------------------- Remove above ----------------------------- ### Basic Infos @@ -16,6 +17,8 @@ https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/debugging.rst #### Hardware WiFimanager Branch/Release: Development +Esp8266/Esp32: + Hardware: ESP-12e, esp01, esp25 Core Version: 2.4.0, staging From 0749e1bdd76c811a5a554ff5cc5fe2fb02fa8dd2 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 15 Mar 2018 16:05:02 -0500 Subject: [PATCH 005/146] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 10da7f6..3782339 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +## Current development going on here :arrow_right: [Development Branch](https://github.com/tzapu/WiFiManager/tree/development) + # WiFiManager ESP8266 WiFi Connection manager with fallback web configuration portal From 6270630d1a27ae6716d3745d21560c4c45aa124a Mon Sep 17 00:00:00 2001 From: Christopher Liebman Date: Wed, 21 Mar 2018 07:18:31 -0700 Subject: [PATCH 006/146] enable all example builds for esp32 --- .travis.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 97d018f..ca2ba85 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,8 +38,7 @@ script: - build_examples - arduino --board espressif:esp32:esp32doit-devkit-v1:FlashFreq=80,DebugLevel=info --save-prefs # some examples fail (SPIFFS defines differ esp32 vs esp8266) so we exclude them - - excludes=("AutoConnectWithFSParametersAndCustomIP.ino" "AutoConnectWithFSParameters.ino") - - build_examples "${excludes[@]}" + - build_examples # - arduino -v --verbose-build --verify $PWD/examples/AutoConnect/AutoConnect.ino # no coverage generated, no need to run From 174bb615e644b04e2787d2d0eea5b20086c2775a Mon Sep 17 00:00:00 2001 From: Chris Marrin Date: Sat, 7 Apr 2018 09:13:48 -0700 Subject: [PATCH 007/146] Changed setAPCallback and setSaveConfigCallback to take std::function params This allows Predicates and Lambdas to be passed. Still allows bare function pointers so this patch is fully backward compatible. Tested on WiFiManager examples for backward compatibility and on my own project (OfficeClock) for handling lambdas with captured variables --- WiFiManager.cpp | 6 +++--- WiFiManager.h | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index aabbe8d..e687c1c 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1809,17 +1809,17 @@ void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { * @access public * @param {[type]} void (*func)(WiFiManager* myWiFiManager) [description] */ -void WiFiManager::setAPCallback( void (*func)(WiFiManager* myWiFiManager) ) { +void WiFiManager::setAPCallback( std::function func ) { _apcallback = func; } - + /** * setSaveConfigCallback, set a save config callback after closing configportal * @todo only calls if configportal stopped * @access public * @param {[type]} void (*func)(void) [description] */ -void WiFiManager::setSaveConfigCallback( void (*func)(void) ) { +void WiFiManager::setSaveConfigCallback( std::function func ) { _savecallback = func; } diff --git a/WiFiManager.h b/WiFiManager.h index 6763833..bc760c9 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -177,9 +177,9 @@ class WiFiManager //sets config for a static IP with DNS void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns); //called when AP mode and config portal is started - void setAPCallback( void (*func)(WiFiManager*) ); + void setAPCallback( std::function func ); //called when settings have been changed and connection was successful - void setSaveConfigCallback( void (*func)(void) ); + void setSaveConfigCallback( std::function func ); //adds a custom parameter, returns false on failure bool addParameter(WiFiManagerParameter *p); //if this is set, it will exit after config, even if connection is unsuccessful. @@ -418,8 +418,8 @@ class WiFiManager void DEBUG_WM(wm_debuglevel_t level, Generic text,Genericb textb); // callbacks - void (*_apcallback)(WiFiManager*) = NULL; - void (*_savecallback)(void) = NULL; + std::function _apcallback; + std::function _savecallback; template auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { From d27fa7df618e7eaad7f54e26aec635e274dc2224 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 9 Apr 2018 19:16:12 -0500 Subject: [PATCH 008/146] hotfixing #425 this is a hotfix, there are numerous issues with this, development branch already addressed all of them. --- WiFiManager.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 1e6d805..ec235e8 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -197,9 +197,20 @@ boolean WiFiManager::startConfigPortal() { } boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { - //setup AP - WiFi.mode(WIFI_AP_STA); - DEBUG_WM(F("SET AP STA")); + + if(!WiFi.isConnected()){ + WiFi.persistent(false); + // disconnect sta, start ap + WiFi.disconnect(); // this alone is not enough to stop the autoconnecter + WiFi.mode(WIFI_AP); + WiFi.persistent(true); + } + else { + //setup AP + WiFi.mode(WIFI_AP_STA); + DEBUG_WM(F("SET AP STA")); + } + _apName = apName; _apPassword = apPassword; From 042640924f61e3fcfe0932e4344322f1cd9b9e45 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 19 Apr 2018 19:01:50 -0500 Subject: [PATCH 009/146] fix menu output removed test menu output, removed ref , not sure why I put that there.... --- WiFiManager.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 917f639..68d7697 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -207,8 +207,6 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { // so we must force it on else, if not connectimeout then waitforconnectionresult gets stuck endless loop WiFi_autoReconnect(); - getMenuOut(); - // set hostname before stating if((String)_hostname != ""){ DEBUG_WM(DEBUG_VERBOSE,"Setting hostname:",_hostname); @@ -882,7 +880,7 @@ void WiFiManager::handleParam(){ String WiFiManager::getMenuOut(){ String page; - for(auto& menuId :_menuIds ){ + for(auto menuId :_menuIds ){ if(((String)menuId == "param") && (_paramsCount == 0)) continue; // no params set, omit params page += HTTP_PORTAL_MENU[menuId]; } @@ -2010,6 +2008,7 @@ void WiFiManager::setShowInfoErase(boolean enabled){ * @param uint8_t menu[] array of menu ids */ void WiFiManager::setMenu(const char * menu[], uint8_t size){ + DEBUG_WM(DEBUG_VERBOSE,"setmenu array"); _menuIds.clear(); for(size_t i = 0; i < size; i++){ for(size_t j = 0; j < _nummenutokens; j++){ @@ -2019,10 +2018,11 @@ void WiFiManager::setMenu(const char * menu[], uint8_t size){ } } } - // DEBUG_WM(getMenuOut()); + DEBUG_WM(getMenuOut()); } void WiFiManager::setMenu(std::vector& menu){ + DEBUG_WM(DEBUG_VERBOSE,"setmenu vector"); _menuIds.clear(); for(auto menuitem : menu ){ for(size_t j = 0; j < _nummenutokens; j++){ @@ -2032,7 +2032,7 @@ void WiFiManager::setMenu(std::vector& menu){ } } } - // DEBUG_WM(getMenuOut()); + DEBUG_WM(getMenuOut()); } From 3c8af53440275a720b7c187a573a0330577cdcd5 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 25 Apr 2018 11:12:12 -0500 Subject: [PATCH 010/146] comments, debugging --- WiFiManager.cpp | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 68d7697..e6895b6 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -608,7 +608,7 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { //@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 !) - WiFi_Disconnect(); // disconnect before begin, in case anything is hung + WiFi_Disconnect(); // disconnect before begin, in case anything is hung, this causes a 2 seconds delay for connect // if ssid argument provided connect to that if (ssid != "") { @@ -2008,7 +2008,7 @@ void WiFiManager::setShowInfoErase(boolean enabled){ * @param uint8_t menu[] array of menu ids */ void WiFiManager::setMenu(const char * menu[], uint8_t size){ - DEBUG_WM(DEBUG_VERBOSE,"setmenu array"); + // DEBUG_WM(DEBUG_VERBOSE,"setmenu array"); _menuIds.clear(); for(size_t i = 0; i < size; i++){ for(size_t j = 0; j < _nummenutokens; j++){ @@ -2018,11 +2018,11 @@ void WiFiManager::setMenu(const char * menu[], uint8_t size){ } } } - DEBUG_WM(getMenuOut()); + // DEBUG_WM(getMenuOut()); } void WiFiManager::setMenu(std::vector& menu){ - DEBUG_WM(DEBUG_VERBOSE,"setmenu vector"); + // DEBUG_WM(DEBUG_VERBOSE,"setmenu vector"); _menuIds.clear(); for(auto menuitem : menu ){ for(size_t j = 0; j < _nummenutokens; j++){ @@ -2032,7 +2032,7 @@ void WiFiManager::setMenu(std::vector& menu){ } } } - DEBUG_WM(getMenuOut()); + // DEBUG_WM(getMenuOut()); } @@ -2092,22 +2092,20 @@ void WiFiManager::DEBUG_WM(Generic text,Genericb textb) { template void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { - if(_debugLevel < level) return; + if(!_debug || _debugLevel < level) return; - if (_debug) { - if(_debugLevel >= DEBUG_MAX){ - _debugPort.print("MEM: "); - _debugPort.println((String)ESP.getFreeHeap()); - } - _debugPort.print("*WM: "); - if(_debugLevel == DEBUG_DEV) _debugPort.print("["+(String)level+"] "); - _debugPort.print(text); - if(textb){ - _debugPort.print(" "); - _debugPort.print(textb); - } - _debugPort.print("\n"); + if(_debugLevel >= DEBUG_MAX){ + _debugPort.print("MEM: "); + _debugPort.println((String)ESP.getFreeHeap()); } + _debugPort.print("*WM: "); + if(_debugLevel == DEBUG_DEV) _debugPort.print("["+(String)level+"] "); + _debugPort.print(text); + if(textb){ + _debugPort.print(" "); + _debugPort.print(textb); + } + _debugPort.print("\n"); } From 718a8c8f4c15e477fc5bf28d26af5bfead21a9e0 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 26 Apr 2018 20:46:00 -0500 Subject: [PATCH 011/146] fixing up setmenu docblocks --- WiFiManager.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index e6895b6..2011b2b 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -2003,7 +2003,10 @@ void WiFiManager::setShowInfoErase(boolean enabled){ /** * set menu items and order - * if param is present, it will be removed from wifi + * if param is present in menu , params will be removed from wifi page automatically + * eg. + * const char * menu[] = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); * @since $dev * @param uint8_t menu[] array of menu ids */ @@ -2021,6 +2024,15 @@ void WiFiManager::setMenu(const char * menu[], uint8_t size){ // DEBUG_WM(getMenuOut()); } +/** + * setMenu with vector + * eg. + * std::vector menu = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); + * tokens can be found in _menutokens array in strings_en.h + * @shiftIncrement $dev + * @param {[type]} std::vector& menu [description] + */ void WiFiManager::setMenu(std::vector& menu){ // DEBUG_WM(DEBUG_VERBOSE,"setmenu vector"); _menuIds.clear(); From 128214a1596e12d1cd2c704558bbe3a9af5b30fe Mon Sep 17 00:00:00 2001 From: ohad Date: Mon, 14 May 2018 11:47:13 +0300 Subject: [PATCH 012/146] add CORS headers this will allow external portal on the network to send credentials via browser. --- WiFiManager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 2011b2b..8a2bd79 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1159,6 +1159,7 @@ void WiFiManager::handleWifiSave() { page += FPSTR(HTTP_END); server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->sendHeader(HTTP_HEAD_CORS, HTTP_HEAD_CORS_ALLOW_ALL); server->send(200, FPSTR(HTTP_HEAD_CT), page); DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); From 24a25fc687cafc3cb8a2251a17352329596093e4 Mon Sep 17 00:00:00 2001 From: ohad Date: Mon, 14 May 2018 11:47:26 +0300 Subject: [PATCH 013/146] add CORS headers this will allow external portal on the network to send credentials via browser. --- strings_en.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/strings_en.h b/strings_en.h index 2cb9f7a..5444d00 100644 --- a/strings_en.h +++ b/strings_en.h @@ -276,6 +276,8 @@ const char T_h[] PROGMEM = "{h}"; // @token h const char HTTP_HEAD_CL[] PROGMEM = "Content-Length"; const char HTTP_HEAD_CT[] PROGMEM = "text/html"; const char HTTP_HEAD_CT2[] PROGMEM = "text/plain"; +const char HTTP_HEAD_CORS[] PROGMEM = "Access-Control-Allow-Origin"; +const char HTTP_HEAD_CORS_ALLOW_ALL[] PROGMEM = "*"; const char * const WIFI_STA_STATUS[] PROGMEM { @@ -315,4 +317,4 @@ const char * const AUTH_MODE_NAMES[] PROGMEM }; #endif -const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; \ No newline at end of file +const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; From 5066b86102607a0f768573061123d3c88254aec0 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Mon, 18 Jun 2018 11:40:01 -0500 Subject: [PATCH 014/146] fix esp32 new bugs esp32 only uses persistent on wifiLowLevelInit if(!persistent){ esp_wifi_set_storage(WIFI_STORAGE_RAM); } which only gets applied during certain functions, namely changing modes, or turning on wifi --- WiFiManager.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index e6895b6..d19536e 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -155,8 +155,10 @@ void WiFiManager::WiFiManagerInit(){ setMenu(_menuIdsDefault); if(_debug && _debugLevel > DEBUG_DEV) debugPlatformInfo(); - _usermode = WiFi.getMode(); - WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites + #ifndef ESP32 + _usermode = WiFi.getMode(); + WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites + #endif _max_params = WIFI_MANAGER_MAX_PARAMS; } From 10088c71f3a8873d6c838029496bba14d3fa6ea3 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Mon, 18 Jun 2018 15:27:18 -0500 Subject: [PATCH 015/146] Move all wifi functions out of constructor Cannot use wifi in constructor on esp32, as it is not available yet, --- WiFiManager.cpp | 24 +++++++++++++++--------- WiFiManager.h | 5 +++++ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 89762d8..cc22363 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -154,20 +154,12 @@ WiFiManager::WiFiManager():WiFiManager(Serial) { void WiFiManager::WiFiManagerInit(){ setMenu(_menuIdsDefault); if(_debug && _debugLevel > DEBUG_DEV) debugPlatformInfo(); - - #ifndef ESP32 - _usermode = WiFi.getMode(); - WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites - #endif - _max_params = WIFI_MANAGER_MAX_PARAMS; } // destructor WiFiManager::~WiFiManager() { - if(_userpersistent) WiFi.persistent(true); // reenable persistent, there is no getter we rely on _userpersistent - // if(_usermode != WIFI_OFF) WiFi.mode(_usermode); - + _end(); // parameters // @todo belongs to wifimanagerparameter if (_params != NULL){ @@ -178,6 +170,17 @@ WiFiManager::~WiFiManager() { DEBUG_WM(DEBUG_DEV,F("unloading")); } +void WiFiManager::_begin(){ + if(_hasBegun) return; + _usermode = WiFi.getMode(); + WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites +} + +void WiFiManager::_end(){ + 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() { @@ -194,6 +197,7 @@ boolean WiFiManager::autoConnect() { */ 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)){ @@ -429,6 +433,8 @@ boolean WiFiManager::startConfigPortal() { * @return {[type]} [description] */ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { + _begin(); + //setup AP _apName = apName; // @todo check valid apname ? _apPassword = apPassword; diff --git a/WiFiManager.h b/WiFiManager.h index de75d4b..1953839 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -310,6 +310,11 @@ class WiFiManager boolean _preloadwifiscan = true; // preload wifiscan if true boolean _disableIpFields = false; // edge case, if true, showxFields(false) forces ip fields off instead of default show when set + // wrapper functions for handling setting and unsetting persistent for now. + bool _hasBegun = false; + void _begin(); + void _end(); + void setupConfigPortal(); void startWPS(); bool startAP(); From b3e19041fffd7f137a2b042198a82f06fbe8c81c Mon Sep 17 00:00:00 2001 From: Shawn A Date: Mon, 18 Jun 2018 15:27:47 -0500 Subject: [PATCH 016/146] fix esp32 erase w persistent --- WiFiManager.cpp | 6 +++++- WiFiManager.h | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index cc22363..dd50e20 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -2352,8 +2352,12 @@ bool WiFiManager::WiFi_eraseConfig() { return true; #endif #elif defined(ESP32) + bool ret; WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! - return WiFi.disconnect(true); + WiFi.persistent(true); + ret = WiFi.disconnect(true); + WiFi.persistent(false); + return ret; #endif } diff --git a/WiFiManager.h b/WiFiManager.h index 1953839..8538f4a 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -311,6 +311,7 @@ class WiFiManager boolean _disableIpFields = false; // edge case, if true, showxFields(false) forces ip fields off instead of default show when set // wrapper functions for handling setting and unsetting persistent for now. + bool esp32persistent = false; bool _hasBegun = false; void _begin(); void _end(); From e3d91a03ff62fe0690e32a9a5fece491618a51e4 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Mon, 18 Jun 2018 15:28:32 -0500 Subject: [PATCH 017/146] add esp32 persistent test support persistent support was added via a PR, but not very well, it is buggy. --- WiFiManager.cpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index dd50e20..86d41a1 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -2266,19 +2266,21 @@ String WiFiManager::getModeString(uint8_t mode){ // set mode ignores WiFi.persistent bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { + bool ret; #ifdef ESP8266 if((wifi_get_opmode() == (uint8) m ) && !persistent) { return true; } - bool ret; ETS_UART_INTR_DISABLE(); if(persistent) ret = wifi_set_opmode(m); else ret = wifi_set_opmode_current(m); ETS_UART_INTR_ENABLE(); - return ret; #elif defined(ESP32) - return WiFi.mode(m); // @todo persistent not implemented? + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.mode(m); // @todo persistent check persistant mode , NI + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; #endif } bool WiFiManager::WiFi_Mode(WiFiMode_t m) { @@ -2327,7 +2329,11 @@ bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { return true; } #elif defined(ESP32) - return WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform + bool ret; + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; #endif } bool WiFiManager::WiFi_enableSTA(bool enable) { From 8d7da2fd8b05ca59bd3638854f5138675652786c Mon Sep 17 00:00:00 2001 From: Shawn A Date: Wed, 27 Jun 2018 16:19:12 -0500 Subject: [PATCH 018/146] FIx esp32 updates Webserver now builtin to esp32 lib, esp32 persistent still not implemented properly, fixes erase again, fixes save again --- README.md | 3 +-- WiFiManager.cpp | 10 +++++++++- WiFiManager.h | 3 +-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 717a292..55469f8 100644 --- a/README.md +++ b/README.md @@ -16,12 +16,11 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are [https://github.com/esp8266/Arduino](https://github.com/esp8266/Arduino) -**This works with the ESP32 Arduino platform with staging , with caveats below** +**This works with the ESP32 Arduino platform with staging** [https://github.com/espressif/arduino-esp32](https://github.com/espressif/arduino-esp32) ### Known Issues -* :exclamation: ESP32 must be patched with webserver library, see [https://github.com/tzapu/WiFiManager/issues/513](https://github.com/tzapu/WiFiManager/issues/513) * Documentation needs to be updated, see [https://github.com/tzapu/WiFiManager/issues/500](https://github.com/tzapu/WiFiManager/issues/500) ## Contents diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 9cfff5b..049e695 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -165,6 +165,7 @@ WiFiManager::~WiFiManager() { if (_params != NULL){ DEBUG_WM(DEBUG_DEV,F("freeing allocated params!")); free(_params); + _params = NULL; } DEBUG_WM(DEBUG_DEV,F("unloading")); @@ -173,7 +174,10 @@ WiFiManager::~WiFiManager() { void WiFiManager::_begin(){ if(_hasBegun) return; _usermode = WiFi.getMode(); + + #ifndef ESP32 WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites + #endif } void WiFiManager::_end(){ @@ -206,6 +210,10 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { return false; } + #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 @@ -2362,7 +2370,7 @@ bool WiFiManager::WiFi_eraseConfig() { bool ret; WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! WiFi.persistent(true); - ret = WiFi.disconnect(true); + ret = WiFi.disconnect(true,true); WiFi.persistent(false); return ret; #endif diff --git a/WiFiManager.h b/WiFiManager.h index 3a49b98..9013b53 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -48,12 +48,11 @@ #define WM_WIFIOPEN WIFI_AUTH_OPEN #ifndef WEBSERVER_H - #warning "WEBSERVER not implemented in espressif/esp32, see readme notes" #ifdef WM_WEBSERVERSHIM #include #else #include - // Forthcoming official + // Forthcoming official ? // https://github.com/esp8266/ESPWebServer #endif #endif From 6d92ae5a1f815a0b20fcbf1daeef5fb0b2dd9450 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 28 Jun 2018 11:52:50 -0500 Subject: [PATCH 019/146] fixup examples --- .../AutoConnectWithFSParameters.ino | 77 +++++++++---------- 1 file changed, 37 insertions(+), 40 deletions(-) diff --git a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index 51b1d80..d2ca15f 100644 --- a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -8,8 +8,8 @@ //define your default values here, if there are different values in config.json, they are overwritten. char mqtt_server[40]; -char mqtt_port[6] = "8080"; -char blynk_token[34] = "YOUR_BLYNK_TOKEN"; +char mqtt_port[6] = "8080"; +char api_token[32] = "YOUR_API_TOKEN"; //flag for saving data bool shouldSaveConfig = false; @@ -20,14 +20,9 @@ void saveConfigCallback () { shouldSaveConfig = true; } - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println(); - +void setupSpiffs(){ //clean FS, for testing - //SPIFFS.format(); + // SPIFFS.format(); //read configuration from FS json Serial.println("mounting FS..."); @@ -53,7 +48,7 @@ void setup() { strcpy(mqtt_server, json["mqtt_server"]); strcpy(mqtt_port, json["mqtt_port"]); - strcpy(blynk_token, json["blynk_token"]); + strcpy(api_token, json["api_token"]); } else { Serial.println("failed to load json config"); @@ -64,51 +59,53 @@ void setup() { Serial.println("failed to mount FS"); } //end read +} +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + setupSpiffs(); + // WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + //set config save notify callback + wm.setSaveConfigCallback(saveConfigCallback); + + // setup custom parameters + // // The extra parameters to be configured (can be either global or just in the setup) // After connecting, parameter.getValue() will get you the configured value // id/name placeholder/prompt default length WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); - WiFiManagerParameter custom_blynk_token("blynk", "blynk token", "", 0); + WiFiManagerParameter custom_api_token("api", "api token", "", 32); - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - - //set config save notify callback - wifiManager.setSaveConfigCallback(saveConfigCallback); - - //set static ip - wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - //add all your parameters here - wifiManager.addParameter(&custom_mqtt_server); - wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_blynk_token); + wm.addParameter(&custom_mqtt_server); + wm.addParameter(&custom_mqtt_port); + wm.addParameter(&custom_api_token); - //reset settings - for testing - //wifiManager.resetSettings(); + //reset settings - wipe credentials for testing + //wm.resetSettings(); - //set minimu quality of signal so it ignores AP's under that quality - //defaults to 8% - //wifiManager.setMinimumSignalQuality(); + //set minimu quality of signal so it ignores AP's under that quality, default is 8% + //wm.setMinimumSignalQuality(); //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - //wifiManager.setConfigPortalTimeout(120); + //wm.setConfigPortalTimeout(120); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + //here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect("AutoConnectAP", "password")) { + if (!wm.autoConnect("AutoConnectAP", "password")) { Serial.println("failed to connect and hit timeout"); delay(3000); - //reset and try again, or maybe put it to deep sleep + // if we still have not connected restart and try all over again ESP.restart(); delay(5000); } @@ -119,7 +116,7 @@ void setup() { //read updated parameters strcpy(mqtt_server, custom_mqtt_server.getValue()); strcpy(mqtt_port, custom_mqtt_port.getValue()); - strcpy(blynk_token, custom_blynk_token.getValue()); + strcpy(api_token, custom_api_token.getValue()); //save the custom parameters to FS if (shouldSaveConfig) { @@ -127,8 +124,8 @@ void setup() { DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["mqtt_server"] = mqtt_server; - json["mqtt_port"] = mqtt_port; - json["blynk_token"] = blynk_token; + json["mqtt_port"] = mqtt_port; + json["api_token"] = api_token; File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { From 8f2791f90880a2d8bcd257226ab60810ae839058 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 28 Jun 2018 11:53:48 -0500 Subject: [PATCH 020/146] fix esp32 fatal --- WiFiManager.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 049e695..030178b 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -2314,6 +2314,8 @@ bool WiFiManager::WiFi_Disconnect() { // esp_wifi_start(); // @todo can only disconnect if enabled perhaps, prevent failure, or correct for previous call ? return esp_wifi_disconnect() == ESP_OK; // return WiFi.disconnect(); + DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); + return WiFi.disconnect(); // not persistent atm #endif return false; } From 9917f619b366ff941411128b125039e20eb228ea Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 28 Jun 2018 12:53:36 -0500 Subject: [PATCH 021/146] reworking examples --- examples/AutoConnect/AutoConnect.ino | 32 ----- .../AutoConnectWithFSParameters.ino | 39 ++++-- ...AutoConnectWithFSParametersAndCustomIP.ino | 102 ++++++-------- .../AutoConnectWithFeedbackLED.ino | 18 +-- .../AutoConnectWithTimeout/platformio.ini | 18 --- .../OnDemandConfigPortal.ino | 127 ++++++++++++++++++ .../AutoConnectWithFeedback.ino | 0 .../AutoConnectWithReset.ino | 0 .../AutoConnectWithStaticIP.ino | 0 .../AutoConnectWithTimeout.ino | 0 .../OnDemandConfigPortal.ino | 124 ++++------------- .../OnDemandWebPortal/OnDemandWebPortal.ino | 16 +-- examples/Simple/Simple.ino | 31 +++++ 13 files changed, 271 insertions(+), 236 deletions(-) delete mode 100644 examples/AutoConnect/AutoConnect.ino rename examples/{ => AutoConnect}/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino (81%) rename examples/{ => AutoConnect}/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino (66%) rename examples/{ => AutoConnect}/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino (80%) delete mode 100644 examples/AutoConnectWithTimeout/platformio.ini create mode 100644 examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino rename examples/{ => Old Examples}/AutoConnectWithFeedback/AutoConnectWithFeedback.ino (100%) rename examples/{ => Old Examples}/AutoConnectWithReset/AutoConnectWithReset.ino (100%) rename examples/{ => Old Examples}/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino (100%) rename examples/{ => Old Examples}/AutoConnectWithTimeout/AutoConnectWithTimeout.ino (100%) create mode 100644 examples/Simple/Simple.ino diff --git a/examples/AutoConnect/AutoConnect.ino b/examples/AutoConnect/AutoConnect.ino deleted file mode 100644 index 0f58900..0000000 --- a/examples/AutoConnect/AutoConnect.ino +++ /dev/null @@ -1,32 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - //reset saved settings - //wifiManager.resetSettings(); - - //set custom ip for portal - //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - - //fetches ssid and pass from eeprom and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - wifiManager.autoConnect("AutoConnectAP"); - //or use this for auto generated name ESP + ChipID - //wifiManager.autoConnect(); - - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino similarity index 81% rename from examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino rename to examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index d2ca15f..07c7dd9 100644 --- a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -11,6 +11,11 @@ char mqtt_server[40]; char mqtt_port[6] = "8080"; char api_token[32] = "YOUR_API_TOKEN"; +//default custom static IP +char static_ip[16] = "10.0.1.56"; +char static_gw[16] = "10.0.1.1"; +char static_sn[16] = "255.255.255.0"; + //flag for saving data bool shouldSaveConfig = false; @@ -50,6 +55,16 @@ void setupSpiffs(){ strcpy(mqtt_port, json["mqtt_port"]); strcpy(api_token, json["api_token"]); + if(json["ip"]) { + Serial.println("setting custom ip from config"); + strcpy(static_ip, json["ip"]); + strcpy(static_gw, json["gateway"]); + strcpy(static_sn, json["subnet"]); + Serial.println(static_ip); + } else { + Serial.println("no custom ip in config"); + } + } else { Serial.println("failed to load json config"); } @@ -88,19 +103,19 @@ void setup() { wm.addParameter(&custom_mqtt_port); wm.addParameter(&custom_api_token); + // set static ip + IPAddress _ip,_gw,_sn; + _ip.fromString(static_ip); + _gw.fromString(static_gw); + _sn.fromString(static_sn); + wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); + //reset settings - wipe credentials for testing //wm.resetSettings(); - //set minimu quality of signal so it ignores AP's under that quality, default is 8% - //wm.setMinimumSignalQuality(); - - //sets timeout until configuration portal gets turned off - //wm.setConfigPortalTimeout(120); - //automatically connect using saved credentials if they exist //If connection fails it starts an access point with the specified name //here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous - //and goes into a blocking loop awaiting configuration if (!wm.autoConnect("AutoConnectAP", "password")) { Serial.println("failed to connect and hit timeout"); @@ -127,20 +142,26 @@ void setup() { json["mqtt_port"] = mqtt_port; json["api_token"] = api_token; + json["ip"] = WiFi.localIP().toString(); + json["gateway"] = WiFi.gatewayIP().toString(); + json["subnet"] = WiFi.subnetMask().toString(); + File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } - json.printTo(Serial); + json.prettyPrintTo(Serial); json.printTo(configFile); configFile.close(); //end save + shouldSaveConfig = false; } Serial.println("local ip"); Serial.println(WiFi.localIP()); - + Serial.println(WiFi.gatewayIP()); + Serial.println(WiFi.subnetMask()); } void loop() { diff --git a/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino b/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino similarity index 66% rename from examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino rename to examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino index 3fa9bcd..35b32ed 100644 --- a/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino +++ b/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino @@ -7,10 +7,10 @@ #endif //define your default values here, if there are different values in config.json, they are overwritten. -//length should be max size + 1 char mqtt_server[40]; -char mqtt_port[6] = "8080"; -char blynk_token[33] = "YOUR_BLYNK_TOKEN"; +char mqtt_port[6] = "8080"; +char api_token[32] = "YOUR_API_TOKEN"; + //default custom static IP char static_ip[16] = "10.0.1.56"; char static_gw[16] = "10.0.1.1"; @@ -25,13 +25,9 @@ void saveConfigCallback () { shouldSaveConfig = true; } -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println(); - +void setupSpiffs(){ //clean FS, for testing - //SPIFFS.format(); + // SPIFFS.format(); //read configuration from FS json Serial.println("mounting FS..."); @@ -57,24 +53,18 @@ void setup() { strcpy(mqtt_server, json["mqtt_server"]); strcpy(mqtt_port, json["mqtt_port"]); - strcpy(blynk_token, json["blynk_token"]); + strcpy(api_token, json["api_token"]); if(json["ip"]) { Serial.println("setting custom ip from config"); - //static_ip = json["ip"]; strcpy(static_ip, json["ip"]); strcpy(static_gw, json["gateway"]); strcpy(static_sn, json["subnet"]); - //strcat(static_ip, json["ip"]); - //static_gw = json["gateway"]; - //static_sn = json["subnet"]; Serial.println(static_ip); -/* Serial.println("converting ip"); - IPAddress ip = ipFromCharArray(static_ip); - Serial.println(ip);*/ } else { Serial.println("no custom ip in config"); } + } else { Serial.println("failed to load json config"); } @@ -84,58 +74,53 @@ void setup() { Serial.println("failed to mount FS"); } //end read - Serial.println(static_ip); - Serial.println(blynk_token); - Serial.println(mqtt_server); +} +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + setupSpiffs(); + + // WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + //set config save notify callback + wm.setSaveConfigCallback(saveConfigCallback); + + // setup custom parameters + // // The extra parameters to be configured (can be either global or just in the setup) // After connecting, parameter.getValue() will get you the configured value // id/name placeholder/prompt default length WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); - WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5); - WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 34); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); + WiFiManagerParameter custom_api_token("api", "api token", "", 32); - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; + //add all your parameters here + wm.addParameter(&custom_mqtt_server); + wm.addParameter(&custom_mqtt_port); + wm.addParameter(&custom_api_token); - //set config save notify callback - wifiManager.setSaveConfigCallback(saveConfigCallback); - - //set static ip + // set static ip IPAddress _ip,_gw,_sn; _ip.fromString(static_ip); _gw.fromString(static_gw); _sn.fromString(static_sn); + wm.setSTAStaticIPConfig(_ip, _gw, _sn); - wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); - - //add all your parameters here - wifiManager.addParameter(&custom_mqtt_server); - wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_blynk_token); + //reset settings - wipe credentials for testing + //wm.resetSettings(); - //reset settings - for testing - //wifiManager.resetSettings(); - - //set minimu quality of signal so it ignores AP's under that quality - //defaults to 8% - wifiManager.setMinimumSignalQuality(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - //wifiManager.setConfigPortalTimeout(120); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + //here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect("AutoConnectAP", "password")) { + if (!wm.autoConnect("AutoConnectAP", "password")) { Serial.println("failed to connect and hit timeout"); delay(3000); - //reset and try again, or maybe put it to deep sleep + // if we still have not connected restart and try all over again ESP.restart(); delay(5000); } @@ -146,7 +131,7 @@ void setup() { //read updated parameters strcpy(mqtt_server, custom_mqtt_server.getValue()); strcpy(mqtt_port, custom_mqtt_port.getValue()); - strcpy(blynk_token, custom_blynk_token.getValue()); + strcpy(api_token, custom_api_token.getValue()); //save the custom parameters to FS if (shouldSaveConfig) { @@ -154,12 +139,12 @@ void setup() { DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["mqtt_server"] = mqtt_server; - json["mqtt_port"] = mqtt_port; - json["blynk_token"] = blynk_token; + json["mqtt_port"] = mqtt_port; + json["api_token"] = api_token; - json["ip"] = WiFi.localIP().toString(); - json["gateway"] = WiFi.gatewayIP().toString(); - json["subnet"] = WiFi.subnetMask().toString(); + json["ip"] = WiFi.localIP().toString(); + json["gateway"] = WiFi.gatewayIP().toString(); + json["subnet"] = WiFi.subnetMask().toString(); File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { @@ -170,6 +155,7 @@ void setup() { json.printTo(configFile); configFile.close(); //end save + shouldSaveConfig = false; } Serial.println("local ip"); diff --git a/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino b/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino similarity index 80% rename from examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino rename to examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino index df74e42..4a2c4dd 100644 --- a/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino +++ b/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino @@ -1,14 +1,16 @@ +// LED will blink when in config mode + #include // https://github.com/tzapu/WiFiManager //for LED status #include Ticker ticker; +int LED = BUILTIN_LED; void tick() { //toggle state - int state = digitalRead(BUILTIN_LED); // get the current state of GPIO1 pin - digitalWrite(BUILTIN_LED, !state); // set pin to the opposite state + digitalWrite(LED, !digitalRead(LED)); // set pin to the opposite state } //gets called when WiFiManager enters configuration mode @@ -26,24 +28,24 @@ void setup() { Serial.begin(115200); //set led pin as output - pinMode(BUILTIN_LED, OUTPUT); + pinMode(LED, OUTPUT); // start ticker with 0.5 because we start in AP mode and try to connect ticker.attach(0.6, tick); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; + WiFiManager wm; //reset settings - for testing - //wifiManager.resetSettings(); + wm.resetSettings(); //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode - wifiManager.setAPCallback(configModeCallback); + wm.setAPCallback(configModeCallback); //fetches ssid and pass and tries to connect //if it does not connect it starts an access point with the specified name //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect()) { + if (!wm.autoConnect()) { Serial.println("failed to connect and hit timeout"); //reset and try again, or maybe put it to deep sleep ESP.restart(); @@ -54,7 +56,7 @@ void setup() { Serial.println("connected...yeey :)"); ticker.detach(); //keep LED on - digitalWrite(BUILTIN_LED, LOW); + digitalWrite(LED, LOW); } void loop() { diff --git a/examples/AutoConnectWithTimeout/platformio.ini b/examples/AutoConnectWithTimeout/platformio.ini deleted file mode 100644 index 7e80288..0000000 --- a/examples/AutoConnectWithTimeout/platformio.ini +++ /dev/null @@ -1,18 +0,0 @@ -; PlatformIO Project Configuration File -; -; Build options: build flags, source filter -; Upload options: custom upload port, speed and extra flags -; Library options: dependencies, extra library storages -; Advanced options: extra scripting -; -; Please visit documentation for the other options and examples -; http://docs.platformio.org/page/projectconf.html - -[env:nodemcuv2] -platform=espressif8266 -board=nodemcuv2 -framework=arduino - -[platformio] -src_dir=AutoConnectWithTimeout -lib_dir=/Users/shawn/projects/microcontrollers/dev/libraries diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino new file mode 100644 index 0000000..0060d6d --- /dev/null +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -0,0 +1,127 @@ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +// ESP-01 users please note: the only pins available (0 and 2), are shared +// with the bootloader, so always set them HIGH at power-up +#define TRIGGER_PIN 0 +const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; + +WiFiManager wifiManager; + + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.setDebugOutput(true); + delay(3000); + Serial.println("\n Starting"); + + // WiFi.mode(WIFI_STA); + // WiFi.printDiag(Serial); + // Serial.println(modes[WiFi.getMode()]); + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + // WiFiManager wifiManager; + + //Local intialization. Once its business is done, there is no need to keep it around + //reset settings - for testing + //wifiManager.resetSettings(); + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep + //in seconds + wifiManager.setConfigPortalTimeout(60); + wifiManager.setConnectTimeout(20); + // wifiManager.setShowStaticFields(true); + + // uint8_t menu[] = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE}; + // wifiManager.setMenu(menu); + + // std::vector menu = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE,wifiManager.MENU_SEP,wifiManager.MENU_ERASE,wifiManager.MENU_EXIT}; + // wifiManager.setMenu(menu); + +// std::vector menu = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE,wifiManager.MENU_SEP,wifiManager.MENU_ERASE,wifiManager.MENU_EXIT}; + // wifiManager.setMenu(menu); + + + WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); + WiFiManagerParameter custom_token("api_token", "api token", "", 0); + WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); + + //add all your parameters here + wifiManager.addParameter(&custom_mqtt_server); + wifiManager.addParameter(&custom_mqtt_port); + wifiManager.addParameter(&custom_token); + wifiManager.addParameter(&custom_tokenb); + + // MENU_WIFI = 0, + // MENU_WIFINOSCAN = 1, + // MENU_INFO = 2, + // MENU_PARAM = 3, + // MENU_CLOSE = 4, + // MENU_RESTART = 5, + // MENU_EXIT = 6, + // MENU_ERASE = 7, + // MENU_SEP = 8 + + // const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; + // wifiManager.setMenu(menu,9); + + std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; + wifiManager.setMenu(menu); + + //set static ip + // wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // wifiManager.setShowStaticFields(false); + // wifiManager.setShowDnsFields(false); + + wifiManager.setConfigPortalTimeout(60); + wifiManager.startConfigPortal("AutoConnectAP", "password"); + + //fetches ssid and pass and tries to connect + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + if(!wifiManager.autoConnect("AutoConnectAP")) { + Serial.println("failed to connect and hit timeout"); + } + + pinMode(TRIGGER_PIN, INPUT); +} + + +void loop() { + // is configuration portal requested? + if ( digitalRead(TRIGGER_PIN) == LOW ) { + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + //reset settings - for testing + //wifiManager.resetSettings(); + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep + //in seconds + wifiManager.setConfigPortalTimeout(120); + + //it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + + //WITHOUT THIS THE AP DOES NOT SEEM TO WORK PROPERLY WITH SDK 1.5 , update to at least 1.5.1 + //WiFi.mode(WIFI_STA); + + // disable captive portal redirection + // wifiManager.setCaptivePortalEnable(false); + + if (!wifiManager.startConfigPortal("OnDemandAP")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + } else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + } + + // put your main code here, to run repeatedly: +} diff --git a/examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino b/examples/Old Examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino similarity index 100% rename from examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino rename to examples/Old Examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino diff --git a/examples/AutoConnectWithReset/AutoConnectWithReset.ino b/examples/Old Examples/AutoConnectWithReset/AutoConnectWithReset.ino similarity index 100% rename from examples/AutoConnectWithReset/AutoConnectWithReset.ino rename to examples/Old Examples/AutoConnectWithReset/AutoConnectWithReset.ino diff --git a/examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino b/examples/Old Examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino similarity index 100% rename from examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino rename to examples/Old Examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino diff --git a/examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino b/examples/Old Examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino similarity index 100% rename from examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino rename to examples/Old Examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino diff --git a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino index c9b1fe7..8c67274 100644 --- a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -1,124 +1,46 @@ +/** + * OnDemandConfigPortal.ino + * example of running the configPortal AP manually, independantly from the captiveportal + * trigger pin will start a configPortal AP for 120 seconds then turn it off. + * + */ #include // https://github.com/tzapu/WiFiManager // select which pin will trigger the configuration portal when set to LOW -// ESP-01 users please note: the only pins available (0 and 2), are shared -// with the bootloader, so always set them HIGH at power-up #define TRIGGER_PIN 0 -const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; - -WiFiManager wifiManager; +int timeout = 120; // seconds to run for +bool webportalrunning = false; void setup() { // put your setup code here, to run once: Serial.begin(115200); - Serial.setDebugOutput(true); - delay(3000); Serial.println("\n Starting"); - - // Serial.println(modes[WiFi.getMode()]); - // WiFi.printDiag(Serial); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - - //Local intialization. Once its business is done, there is no need to keep it around - //reset settings - for testing - //wifiManager.resetSettings(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - wifiManager.setConfigPortalTimeout(20); - wifiManager.setConnectTimeout(10); - // wifiManager.setShowStaticFields(true); - - // uint8_t menu[] = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE}; - // wifiManager.setMenu(menu); - - // std::vector menu = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE,wifiManager.MENU_SEP,wifiManager.MENU_ERASE,wifiManager.MENU_EXIT}; - // wifiManager.setMenu(menu); - -// std::vector menu = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE,wifiManager.MENU_SEP,wifiManager.MENU_ERASE,wifiManager.MENU_EXIT}; - // wifiManager.setMenu(menu); - - - WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); - WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); - WiFiManagerParameter custom_token("api_token", "api token", "", 0); - WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); - - //add all your parameters here - wifiManager.addParameter(&custom_mqtt_server); - wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_token); - wifiManager.addParameter(&custom_tokenb); - - // MENU_WIFI = 0, - // MENU_WIFINOSCAN = 1, - // MENU_INFO = 2, - // MENU_PARAM = 3, - // MENU_CLOSE = 4, - // MENU_RESTART = 5, - // MENU_EXIT = 6, - // MENU_ERASE = 7, - // MENU_SEP = 8 - - // const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - // wifiManager.setMenu(menu,9); - - std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - wifiManager.setMenu(menu); - - //set static ip - wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - // wifiManager.setShowStaticFields(false); - // wifiManager.setShowDnsFields(false); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - if(!wifiManager.autoConnect("AutoConnectAP")) { - Serial.println("failed to connect and hit timeout"); - } - - pinMode(TRIGGER_PIN, INPUT); + pinMode(TRIGGER_PIN, INPUT_PULLUP); } - void loop() { // is configuration portal requested? - if ( digitalRead(TRIGGER_PIN) == LOW ) { - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around + if ( digitalRead(TRIGGER_PIN) == LOW) { + WiFiManager wifiManager; //reset settings - for testing //wifiManager.resetSettings(); + + // set configportal timeout + wm.setConfigPortaltimeout(timeout); - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - wifiManager.setConfigPortalTimeout(120); - - //it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - - //WITHOUT THIS THE AP DOES NOT SEEM TO WORK PROPERLY WITH SDK 1.5 , update to at least 1.5.1 - //WiFi.mode(WIFI_STA); - - // disable captive portal redirection - // wifiManager.setCaptivePortalEnable(false); - - if (!wifiManager.startConfigPortal("OnDemandAP")) { + if (!wm.startConfigPortal("OnDemandAP")) { Serial.println("failed to connect and hit timeout"); delay(3000); - } else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - } + //reset and try again, or maybe put it to deep sleep + ESP.reset(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } // put your main code here, to run repeatedly: diff --git a/examples/OnDemandWebPortal/OnDemandWebPortal.ino b/examples/OnDemandWebPortal/OnDemandWebPortal.ino index b45e4a0..07f61e9 100644 --- a/examples/OnDemandWebPortal/OnDemandWebPortal.ino +++ b/examples/OnDemandWebPortal/OnDemandWebPortal.ino @@ -7,14 +7,11 @@ #include // https://github.com/tzapu/WiFiManager // select which pin will trigger the configuration portal when set to LOW -// ESP-01 users please note: the only pins available (0 and 2), are shared -// with the bootloader, so always set them HIGH at power-up #define TRIGGER_PIN 0 -int timeout = 120; // seconds - -WiFiManager wifiManager; +WiFiManager wm; +int timeout = 120; // seconds to run for bool webportalrunning = false; int start = millis(); @@ -27,19 +24,18 @@ void setup() { void loop() { - if(webportalrunning){ - wifiManager.process(); + wm.process(); if(millis()-start > timeout*1000){ Serial.println("webportaltimeout"); webportalrunning = false; - wifiManager.stopWebPortal(); // auto off + wm.stopWebPortal(); // auto off } } - // is configuration portal requested? if ( digitalRead(TRIGGER_PIN) == LOW && !webportalrunning) { - wifiManager.startWebPortal(); + wm.startWebPortal(); + // wm.startWebPortal(); webportalrunning = true; start = millis(); } diff --git a/examples/Simple/Simple.ino b/examples/Simple/Simple.ino new file mode 100644 index 0000000..e244fde --- /dev/null +++ b/examples/Simple/Simple.ino @@ -0,0 +1,31 @@ +#include // https://github.com/tzapu/WiFiManager + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + + //set custom ip for portal + //wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + //here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous + //and goes into a blocking loop awaiting configuration + wm.autoConnect("AutoConnectAP"); + //or use this for auto generated name ESP + ChipID + //wm.autoConnect(); + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); +} + +void loop() { + // put your main code here, to run repeatedly: + +} From 0ab6f57239c34066da28449005aebec0e89208af Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 28 Jun 2018 12:53:48 -0500 Subject: [PATCH 022/146] fix esp32 resetsettings --- WiFiManager.cpp | 58 +++++++++++++++++++++++++++---------------------- 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 030178b..51d39a8 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -173,9 +173,9 @@ WiFiManager::~WiFiManager() { void WiFiManager::_begin(){ if(_hasBegun) return; - _usermode = WiFi.getMode(); #ifndef ESP32 + _usermode = WiFi.getMode(); WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites #endif } @@ -538,21 +538,26 @@ uint8_t WiFiManager::processConfigPortal(){ DEBUG_WM(DEBUG_VERBOSE,F("process connect")); if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast. - // 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()); + // @todo 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 ( _savecallback != NULL) { - _savecallback(); - } - stopConfigPortal(); - return WL_CONNECTED; // CONNECT SUCCESS - } - - DEBUG_WM(DEBUG_ERROR,F("[ERROR] Connect to new AP Failed")); + if ( _savecallback != NULL) { + _savecallback(); + } + stopConfigPortal(); + return WL_CONNECTED; // CONNECT SUCCESS + } + DEBUG_WM(DEBUG_ERROR,F("[ERROR] Connect to new AP Failed")); + // } if (_shouldBreakAfterConfig) { // do save callback @@ -1041,6 +1046,7 @@ String WiFiManager::getIpForm(String id, String title, String value){ String WiFiManager::getStaticOut(){ String page; if ((_staShowStaticFields || _sta_static_ip) && _staShowStaticFields>=0) { + DEBUG_WM(DEBUG_DEV,"_staShowStaticFields"); page += FPSTR(HTTP_FORM_STATIC_HEAD); // @todo how can we get these accurate settings from memory , wifi_get_ip_info does not seem to reveal if struct ip_info is static or not page += getIpForm(FPSTR(S_ip),FPSTR(S_staticip),(_sta_static_ip ? _sta_static_ip.toString() : "")); // @token staticip @@ -1726,10 +1732,15 @@ bool WiFiManager::erase(bool opt){ */ void WiFiManager::resetSettings() { DEBUG_WM(F("SETTINGS ERASED")); - WiFi_enableSTA(true,true); - WiFi.persistent(true); - WiFi.disconnect(true); - WiFi.persistent(false); + WiFi_enableSTA(true,true); // must be sta to disconnect erase + + #ifdef ESP32 + WiFi.disconnect(true,true); + #else + WiFi.persistent(true); + WiFi.disconnect(true); + WiFi.persistent(false); + #endif } // SETTERS @@ -2301,19 +2312,13 @@ bool WiFiManager::WiFi_Disconnect() { #ifdef ESP8266 if((WiFi.getMode() & WIFI_STA) != 0) { bool ret; - DEBUG_WM(DEBUG_DEV,F("wifi station disconnect")); + DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); ETS_UART_INTR_DISABLE(); // @todo probably not needed ret = wifi_station_disconnect(); ETS_UART_INTR_ENABLE(); return ret; } #elif defined(ESP32) - DEBUG_WM(DEBUG_DEV,F("wifi station disconnect")); - // @todo why does disconnect call these, might be needed - // WiFi.getMode(); // @todo wifiLowLevelInit(), probably not needed, for save config only - // esp_wifi_start(); // @todo can only disconnect if enabled perhaps, prevent failure, or correct for previous call ? - return esp_wifi_disconnect() == ESP_OK; - // return WiFi.disconnect(); DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); return WiFi.disconnect(); // not persistent atm #endif @@ -2322,6 +2327,7 @@ bool WiFiManager::WiFi_Disconnect() { // toggle STA without persistent bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { + DEBUG_WM(DEBUG_DEV,F("WiFi station enable")); #ifdef ESP8266 WiFiMode_t newMode; WiFiMode_t currentMode = WiFi.getMode(); From c0187a60e150335f1b7586580aea1e09980c9e96 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 28 Jun 2018 12:54:49 -0500 Subject: [PATCH 023/146] fix esp32 usermode --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 51d39a8..fdeae7c 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -173,9 +173,9 @@ WiFiManager::~WiFiManager() { void WiFiManager::_begin(){ if(_hasBegun) return; + _usermode = WiFi.getMode(); #ifndef ESP32 - _usermode = WiFi.getMode(); WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites #endif } From 906a9d89cb23b3cef748ae0bc2a9ee7558ac4dfb Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 29 Jun 2018 16:52:20 -0500 Subject: [PATCH 024/146] advanced example testing --- WiFiManager.h | 2 +- examples/Advanced/Advanced.ino | 90 ++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 examples/Advanced/Advanced.ino diff --git a/WiFiManager.h b/WiFiManager.h index 9013b53..6779dcb 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -169,7 +169,7 @@ class WiFiManager void setSaveConnectTimeout(unsigned long seconds); // toggle debug output void setDebugOutput(boolean debug); - //defaults to not showing anything under 8% signal quality if called + //set min quality percentage to include in scan, defaults to 8% if not specified void setMinimumSignalQuality(int quality = 8); //sets a custom ip /gateway /subnet configuration void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); diff --git a/examples/Advanced/Advanced.ino b/examples/Advanced/Advanced.ino new file mode 100644 index 0000000..a864dda --- /dev/null +++ b/examples/Advanced/Advanced.ino @@ -0,0 +1,90 @@ +/** + * WiFiManager advanced demo, contains advanced configurartion options + * Implements TRIGGEN_PIN button press, press for ondemand configportal, hold for 3 seconds for reset settings. + */ +#include // https://github.com/tzapu/WiFiManager + +#define TRIGGER_PIN 0 + +WiFiManager wm; + +void setup() { + Serial.begin(115200); + Serial.setDebugOutput(true); + delay(3000); + Serial.println("\n Starting"); + + pinMode(TRIGGER_PIN, INPUT); + + // wm.resetSettings(); // wipe settings + + // add a custom input field + int customFieldLength = 40; + WiFiManagerParameter custom_field("customfield", "Custom Field", "Default Value", customFieldLength); + wm.addParameter(&custom_field); + + // custom menu via array or vector + // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" + // const char* menu[] = {"wifi","info","param","sep","restart","exit"}; + // wm.setMenu(menu,6); + std::vector menu = {"wifi","info","param","sep","restart","exit"}; + wm.setMenu(menu); + + //set static ip + // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn + // wm.setShowStaticFields(true); // force show static ip fields + // wm.setShowDnsFields(true); // force show dns field always + + // wm.setConnectTimeout(20); // how long to try to connect for before continuing + // wm.setConfigPortalTimeout(60); // auto close configportal after n seconds + // wifiManager.setCaptivePortalEnable(false); // disable captive portal redirection + + // wifi scan settings + // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) + // wm.setMinimumSignalQuality(20); // set min RSSI to show in scans, null = 8% + // wm.setShowInfoErase(false); // do not show erase button on info page + // wm.setScanDispPerc(true); // show RSSI as percentage not graph icons + + bool res; + // res = wm.autoConnect(); // auto generated AP name from chipid + // res = wm.autoConnect("AutoConnectAP"); // anonymous ap + res = wm.autoConnect("AutoConnectAP"); // password protected ap + + if(!res) { + Serial.println("Failed to connect or hit timeout"); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } +} + + +void loop() { + // check for button press + if ( digitalRead(TRIGGER_PIN) == LOW ) { + // poor mans debounce, not recommended for production code + delay(50); + if( digitalRead(TRIGGER_PIN) == LOW ){ + + delay(3000); // reset timer + if( digitalRead(TRIGGER_PIN) == LOW ){ + // holding button 3000 ms, reset settings + wm.resetSettings(); + ESP.restart(); + } + + wm.setConfigPortalTimeout(120); + + if (!wm.startConfigPortal("OnDemandAP")) { + Serial.println("failed to connect or hit timeout"); + delay(3000); + } else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + } + } + + // put your main code here, to run repeatedly: +} From 3a9d70f581ab2b09d53c5b60a62cf1c3938b2897 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sat, 30 Jun 2018 13:42:33 -0500 Subject: [PATCH 025/146] fix example --- examples/OnDemandConfigPortal/OnDemandConfigPortal.ino | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino index 8c67274..357276b 100644 --- a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -22,19 +22,19 @@ void setup() { void loop() { // is configuration portal requested? if ( digitalRead(TRIGGER_PIN) == LOW) { - WiFiManager wifiManager; + WiFiManager wm; //reset settings - for testing //wifiManager.resetSettings(); // set configportal timeout - wm.setConfigPortaltimeout(timeout); + wm.setConfigPortalTimeout(timeout); if (!wm.startConfigPortal("OnDemandAP")) { Serial.println("failed to connect and hit timeout"); delay(3000); //reset and try again, or maybe put it to deep sleep - ESP.reset(); + ESP.restart(); delay(5000); } From 4fdefaf67d411901893845197ff0873802303edb Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 2 Jul 2018 10:10:09 -0500 Subject: [PATCH 026/146] example work --- examples/Advanced/Advanced.ino | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/examples/Advanced/Advanced.ino b/examples/Advanced/Advanced.ino index a864dda..f47b021 100644 --- a/examples/Advanced/Advanced.ino +++ b/examples/Advanced/Advanced.ino @@ -24,7 +24,8 @@ void setup() { wm.addParameter(&custom_field); // custom menu via array or vector - // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" + // + // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (sep is seperator) (if param is in menu, params will not show up in wifi page!) // const char* menu[] = {"wifi","info","param","sep","restart","exit"}; // wm.setMenu(menu,6); std::vector menu = {"wifi","info","param","sep","restart","exit"}; @@ -41,14 +42,16 @@ void setup() { // wifi scan settings // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) - // wm.setMinimumSignalQuality(20); // set min RSSI to show in scans, null = 8% + // wm.setMinimumSignalQuality(20); // set min RSSI (percentage) to show in scans, null = 8% // wm.setShowInfoErase(false); // do not show erase button on info page // wm.setScanDispPerc(true); // show RSSI as percentage not graph icons + + // wm.setBreakAfterConfig(true); // always exit configportal even if wifi save fails bool res; // res = wm.autoConnect(); // auto generated AP name from chipid // res = wm.autoConnect("AutoConnectAP"); // anonymous ap - res = wm.autoConnect("AutoConnectAP"); // password protected ap + res = wm.autoConnect("AutoConnectAP","password"); // password protected ap if(!res) { Serial.println("Failed to connect or hit timeout"); @@ -59,7 +62,6 @@ void setup() { } } - void loop() { // check for button press if ( digitalRead(TRIGGER_PIN) == LOW ) { @@ -69,11 +71,13 @@ void loop() { delay(3000); // reset timer if( digitalRead(TRIGGER_PIN) == LOW ){ + Serial.println("Erasing Config"); // holding button 3000 ms, reset settings wm.resetSettings(); ESP.restart(); } + Serial.println("Starting config portal"); wm.setConfigPortalTimeout(120); if (!wm.startConfigPortal("OnDemandAP")) { From 5a06f29c5b96b973aa5a8e2ecaa5192d01abab3d Mon Sep 17 00:00:00 2001 From: Christopher Liebman Date: Sat, 7 Jul 2018 06:26:36 -0700 Subject: [PATCH 027/146] In https://github.com/esp8266/Arduino/pull/4889 the core was modified to disable WPS by default. Its only enabled if NO_EXTRA_4K_HEAP is defined. To enable you must re-run the board manager with --noextra4kheap. This addes #ifdef NO_EXTRA_4K_HEAP arround WPS usage so it won't generate compiler errors. --- WiFiManager.cpp | 5 ++++- WiFiManager.h | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index fdeae7c..9a09195 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -654,6 +654,7 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { DEBUG_WM(DEBUG_VERBOSE,F("Connection result:"),getWLStatusString(connRes)); +#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 == "") { @@ -661,6 +662,7 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { // should be connected at the end of WPS connRes = waitForConnectResult(); } +#endif if(connRes != WL_SCAN_COMPLETED){ updateConxResult(connRes); @@ -782,6 +784,7 @@ uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) { return status; } +#ifdef NO_EXTRA_4K_HEAP void WiFiManager::startWPS() { DEBUG_WM(F("START WPS")); #ifdef ESP8266 @@ -791,7 +794,7 @@ void WiFiManager::startWPS() { #endif DEBUG_WM(F("END WPS")); } - +#endif String WiFiManager::getHTTPHead(String title){ String page; diff --git a/WiFiManager.h b/WiFiManager.h index 6779dcb..795f67d 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -290,7 +290,9 @@ class WiFiManager int _staShowDns = 0; // ternary always show dns, only if not set in code, never(cannot change dns via web!) boolean _removeDuplicateAPs = true; // remove dup aps from wifiscan boolean _shouldBreakAfterConfig = false; // stop configportal on save failure +#ifdef NO_EXTRA_4K_HEAP boolean _tryWPS = false; // try WPS on save failure, unsupported +#endif boolean _configPortalIsBlocking = true; // configportal enters blocking loop boolean _enableCaptivePortal = true; // enable captive portal redirection boolean _userpersistent = true; // users preffered persistence to restore @@ -316,7 +318,9 @@ class WiFiManager void _end(); void setupConfigPortal(); +#ifdef NO_EXTRA_4K_HEAP void startWPS(); +#endif bool startAP(); uint8_t connectWifi(String ssid, String pass); From b9f6b472a7cfde507dcc8ee19bbf8549aded220b Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sat, 7 Jul 2018 09:45:24 -0500 Subject: [PATCH 028/146] #645 comments --- WiFiManager.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 9a09195..c36c2c4 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -654,6 +654,7 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { 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? @@ -784,6 +785,7 @@ uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) { return status; } +// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 #ifdef NO_EXTRA_4K_HEAP void WiFiManager::startWPS() { DEBUG_WM(F("START WPS")); From aeba5478ee7ddbdcfae3b4323f50600ca6e47e15 Mon Sep 17 00:00:00 2001 From: Christopher Liebman Date: Sun, 8 Jul 2018 07:14:11 -0700 Subject: [PATCH 029/146] fix bad progmem access introduced in https://github.com/tzapu/WiFiManager/pull/608 --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index c36c2c4..6120d33 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1186,7 +1186,7 @@ void WiFiManager::handleWifiSave() { page += FPSTR(HTTP_END); server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->sendHeader(HTTP_HEAD_CORS, HTTP_HEAD_CORS_ALLOW_ALL); + server->sendHeader(FPSTR(HTTP_HEAD_CORS), HTTP_HEAD_CORS_ALLOW_ALL); server->send(200, FPSTR(HTTP_HEAD_CT), page); DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); From e235a45d5a624e3eb380add327340071a2d3557d Mon Sep 17 00:00:00 2001 From: Chris Liebman Date: Sun, 8 Jul 2018 08:32:41 -0700 Subject: [PATCH 030/146] value is PROGMEM too.... --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 6120d33..0ee56e5 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1186,7 +1186,7 @@ void WiFiManager::handleWifiSave() { page += FPSTR(HTTP_END); server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->sendHeader(FPSTR(HTTP_HEAD_CORS), HTTP_HEAD_CORS_ALLOW_ALL); + server->sendHeader(FPSTR(HTTP_HEAD_CORS), FPSTR(HTTP_HEAD_CORS_ALLOW_ALL)); server->send(200, FPSTR(HTTP_HEAD_CT), page); DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); From 0f2ba754e2499e04c4d48d1ef00b488ae68f5778 Mon Sep 17 00:00:00 2001 From: vincentVDB Date: Tue, 10 Jul 2018 02:11:06 +0200 Subject: [PATCH 031/146] Update AutoConnectWithFSParameters.ino Close file ! --- .../AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index 1d58e5c..7e6c373 100644 --- a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -61,6 +61,7 @@ void setup() { } else { Serial.println("failed to load json config"); } + configFile.close(); } } } else { From 24d317b9da270dbb4124e72da74aef0de7174632 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 13 Jul 2018 18:27:50 -0500 Subject: [PATCH 032/146] fix #655 --- WiFiManager.cpp | 2 +- strings_en.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index c36c2c4..0245a88 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -800,7 +800,7 @@ void WiFiManager::startWPS() { String WiFiManager::getHTTPHead(String title){ String page; - page += FPSTR(HTTP_HEAD); + page += FPSTR(HTTP_HEAD_START); page.replace(FPSTR(T_v), title); page += FPSTR(HTTP_SCRIPT); page += FPSTR(HTTP_STYLE); diff --git a/strings_en.h b/strings_en.h index 5444d00..60850a2 100644 --- a/strings_en.h +++ b/strings_en.h @@ -17,7 +17,7 @@ // #define WIFI_MANAGER_OVERRIDE_STRINGS // Copy and paste ALL of the const char lines below and modify to suit. -const char HTTP_HEAD[] PROGMEM = "{v}"; +const char HTTP_HEAD_START[] PROGMEM = "{v}"; const char HTTP_SCRIPT[] PROGMEM = ""; const char HTTP_HEAD_END[] PROGMEM = "
"; From 17f2316ea84c694240b8ac7d02b20efce4e70ba4 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 13 Jul 2018 18:41:14 -0500 Subject: [PATCH 033/146] fixes #655 --- WiFiManager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 0245a88..765b65b 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1078,7 +1078,7 @@ String WiFiManager::getParamOut(){ String HTTP_PARAM_temp = FPSTR(HTTP_FORM_LABEL); HTTP_PARAM_temp += FPSTR(HTTP_FORM_PARAM); - bool tok_I = HTTP_PARAM_temp.indexOf(FPSTR(T_i)) > 0; + bool tok_I = HTTP_PARAM_temp.indexOf(FPSTR(T_I)) > 0; bool tok_i = HTTP_PARAM_temp.indexOf(FPSTR(T_i)) > 0; bool tok_n = HTTP_PARAM_temp.indexOf(FPSTR(T_n)) > 0; bool tok_p = HTTP_PARAM_temp.indexOf(FPSTR(T_p)) > 0; @@ -1113,7 +1113,7 @@ String WiFiManager::getParamOut(){ // if no ID use customhtml for item, else generate from param string if (_params[i]->getID() != NULL) { - if(tok_I)pitem.replace(FPSTR(T_i), (String)FPSTR(S_parampre)+(String)i); + if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); From 933f86720ab8a12d7a74ad67ad6710e189861fa0 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 13 Jul 2018 23:43:07 -0500 Subject: [PATCH 034/146] param was using user length for strncpy, causing overflows --- WiFiManager.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 576d10f..0e4f36f 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -63,12 +63,17 @@ WiFiManagerParameter::~WiFiManagerParameter() { void WiFiManagerParameter::setValue(const char *defaultValue, int length) { _length = length; + length = strlen(defaultValue); // length actual + if(_length < length){ + // Serial.println("defaultValue length mismatch"); + } _value = new char[length + 1]; for (int i = 0; i < length + 1; i++) { _value[i] = 0; } if (defaultValue != NULL) { - strncpy(_value, defaultValue, length + 1); // length+1 due to null terminated string + strncpy(_value, defaultValue, length); + _value[length] = '\0'; // explicit null } } const char* WiFiManagerParameter::getValue() { From fc84e7a2607b0d35c750ce1b7983238d2e4bf87e Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 13 Jul 2018 23:52:36 -0500 Subject: [PATCH 035/146] trying to fix param issues when param is out of scope Ideally this should be done entirely different so params can follow wm scope and object lifetime.. --- WiFiManager.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 0e4f36f..45aa4bf 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -59,6 +59,7 @@ 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 } void WiFiManagerParameter::setValue(const char *defaultValue, int length) { @@ -1095,7 +1096,8 @@ String WiFiManager::getParamOut(){ char parLength[5]; // add the extra parameters to the form for (int i = 0; i < _paramsCount; i++) { - if (_params[i] == NULL) { + if (_params[i] == NULL || _params[i]->_length == 0) { + DEBUG_WM(DEBUG_ERROR,"[ERROR] WiFiManagerParameter is out of scope"); break; } From 32495668d8ac691d72ec77b5e423c6f8d3d845b7 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Sat, 14 Jul 2018 16:46:07 -0500 Subject: [PATCH 036/146] Update ISSUE_TEMPLATE.md --- .github/ISSUE_TEMPLATE.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 2deb942..6fd55a7 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,5 +1,9 @@ ## PLEASE TRY DEVELOPMENT BRANCH before submitting bugs on release or master, in case they were already fixed. ## +## POST SERIAL OUTPUT ! +## POST SERIAL OUTPUT ! +## POST SERIAL OUTPUT ! + Issues without basic info will be ignored or closed! Please fill the info fields, it helps to get you faster support ;) From 85dd747949f302c022330dbd509107237fed7ecd Mon Sep 17 00:00:00 2001 From: Christopher Liebman Date: Sun, 15 Jul 2018 10:44:06 -0700 Subject: [PATCH 037/146] Use hasParam() instead of checking server.arg() for NULL, it returns a String anyway. Don't use .c_str() when its being assigned to a String anyway --- WiFiManager.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 45aa4bf..fb5eb08 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1228,9 +1228,13 @@ void WiFiManager::doParamSave(){ break; } //read parameter from server + String name = (String)FPSTR(S_parampre)+(String)i; String value; - if(server->arg((String)FPSTR(S_parampre)+(String)i) != NULL) value = server->arg((String)FPSTR(S_parampre)+(String)i).c_str(); - else value = server->arg(_params[i]->getID()).c_str(); + if(server->hasArg(name)) { + value = server->arg(name); + } else { + value = server->arg(_params[i]->getID()); + } //store it in params array value.toCharArray(_params[i]->_value, _params[i]->_length+1); // length+1 null terminated From 2fac07cbf0228d49a479fa2811bf97591a2d532d Mon Sep 17 00:00:00 2001 From: Christopher Liebman Date: Sun, 15 Jul 2018 14:39:11 -0700 Subject: [PATCH 038/146] WiFiManagerParameter::setValue used length of default value for i allocation and not passed length. Changed to use passed length or length of default value if > passed length. --- WiFiManager.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index fb5eb08..477dde4 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -67,14 +67,16 @@ void WiFiManagerParameter::setValue(const char *defaultValue, int length) { length = strlen(defaultValue); // length actual if(_length < length){ // Serial.println("defaultValue length mismatch"); + // use the length if it's longer. + _length = length; } - _value = new char[length + 1]; - for (int i = 0; i < length + 1; i++) { + _value = new char[_length + 1]; + for (int i = 0; i < _length + 1; i++) { _value[i] = 0; } if (defaultValue != NULL) { - strncpy(_value, defaultValue, length); - _value[length] = '\0'; // explicit null + strncpy(_value, defaultValue, _length); + _value[_length] = '\0'; // explicit null } } const char* WiFiManagerParameter::getValue() { @@ -1231,9 +1233,9 @@ void WiFiManager::doParamSave(){ String name = (String)FPSTR(S_parampre)+(String)i; String value; if(server->hasArg(name)) { - value = server->arg(name); + value = server->arg(name); } else { - value = server->arg(_params[i]->getID()); + value = server->arg(_params[i]->getID()); } //store it in params array From 9ab4deaf5bf0ff8163875a22f024a018f62f19e8 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Mon, 16 Jul 2018 08:06:03 -0500 Subject: [PATCH 039/146] clean up param length Just changing to not modify argument, spacing --- WiFiManager.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 477dde4..a6a6091 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -63,14 +63,15 @@ WiFiManagerParameter::~WiFiManagerParameter() { } void WiFiManagerParameter::setValue(const char *defaultValue, int length) { - _length = length; - length = strlen(defaultValue); // length actual + _length = length; + deflength = strlen(defaultValue); // length actual + // use the defult length if it's longer, + // @todo consider it might be useful to fail, so user knows they were wrong if(_length < length){ // Serial.println("defaultValue length mismatch"); - // use the length if it's longer. - _length = length; + _length = deflength; } - _value = new char[_length + 1]; + _value = new char[_length + 1]; for (int i = 0; i < _length + 1; i++) { _value[i] = 0; } From 08bb2322aa2987702786752f9d450b4b622e8768 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Mon, 16 Jul 2018 17:07:31 -0500 Subject: [PATCH 040/146] Oops --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index a6a6091..c21374f 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -64,7 +64,7 @@ WiFiManagerParameter::~WiFiManagerParameter() { void WiFiManagerParameter::setValue(const char *defaultValue, int length) { _length = length; - deflength = strlen(defaultValue); // length actual + int deflength = strlen(defaultValue); // length actual // use the defult length if it's longer, // @todo consider it might be useful to fail, so user knows they were wrong if(_length < length){ From 74ceba740976b841aaeb18aea701b8de82039299 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 18 Jul 2018 14:01:45 -0500 Subject: [PATCH 041/146] add non blocking example --- .../AutoConnectNonBlocking.ino | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 examples/AutoConnect/AutoConnectNonBlocking/AutoConnectNonBlocking.ino diff --git a/examples/AutoConnect/AutoConnectNonBlocking/AutoConnectNonBlocking.ino b/examples/AutoConnect/AutoConnectNonBlocking/AutoConnectNonBlocking.ino new file mode 100644 index 0000000..3187bec --- /dev/null +++ b/examples/AutoConnect/AutoConnectNonBlocking/AutoConnectNonBlocking.ino @@ -0,0 +1,26 @@ +#include // https://github.com/tzapu/WiFiManager +WiFiManager wm; + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + + wm.setConfigPortalBlocking(false); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + if(wm.autoConnect("AutoConnectAP")){ + Serial.println("connected...yeey :)"); + } + else { + Serial.println("Configportal running"); + } +} + +void loop() { + wm.process(); + // put your main code here, to run repeatedly: +} From a39b96be9ca51b0f942077d6419fc621c6524726 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 18 Jul 2018 16:25:53 -0500 Subject: [PATCH 042/146] disable autoreconect esp32 --- WiFiManager.cpp | 2 +- WiFiManager.h | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index c21374f..838b45a 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -2445,7 +2445,7 @@ void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ void WiFiManager::WiFi_autoReconnect(){ #ifdef ESP8266 WiFi.setAutoReconnect(_wifiAutoReconnect); - #elif defined(ESP32) + #elif defined(ESP32) && defined(esp32autoreconnect) if(_wifiAutoReconnect){ DEBUG_WM(DEBUG_VERBOSE,"ESP32 event handler enabled"); WiFi.onEvent(WiFiEvent); diff --git a/WiFiManager.h b/WiFiManager.h index 795f67d..99f4330 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -22,6 +22,9 @@ // #include "soc/efuse_reg.h" // include to add efuse chip rev to info, getChipRevision() is almost always the same though, so not sure why it matters. +// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge +// autoreconnect status WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 + #define WM_WEBSERVERSHIM // use webserver shim lib #ifdef ESP8266 From 0e6ed389864162056b754829f2133380f0c9b8e2 Mon Sep 17 00:00:00 2001 From: 0x1abin <270995079@qq.com> Date: Thu, 19 Jul 2018 14:36:18 +0800 Subject: [PATCH 043/146] compat macos newline --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 838b45a..85751aa 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -2164,7 +2164,7 @@ void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { _debugPort.print(" "); _debugPort.print(textb); } - _debugPort.print("\n"); + _debugPort.println(); } From f1fd553ac66edc205d9fc880ba475ce0a9b37b58 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 19 Jul 2018 08:40:46 -0500 Subject: [PATCH 044/146] fix autoreconnect, forgot we use event for other stuff --- WiFiManager.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 838b45a..1a2521a 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -2437,7 +2437,9 @@ void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ } else _lastconxresulttmp = WiFi.status(); // if(info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) Serial.println("*WM: EVENT: WIFI_REASON: NO_AP_FOUND"); // Serial.println("*WM: Event: SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); - WiFi.reconnect(); + #ifdef esp32autoreconnect + WiFi.reconnect(); + #endif } } #endif @@ -2445,7 +2447,7 @@ void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ void WiFiManager::WiFi_autoReconnect(){ #ifdef ESP8266 WiFi.setAutoReconnect(_wifiAutoReconnect); - #elif defined(ESP32) && defined(esp32autoreconnect) + #elif defined(ESP32) if(_wifiAutoReconnect){ DEBUG_WM(DEBUG_VERBOSE,"ESP32 event handler enabled"); WiFi.onEvent(WiFiEvent); From d140ccff84fc4881095aeddced2b7917e708963f Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 19 Jul 2018 10:02:53 -0500 Subject: [PATCH 045/146] adds setCountry, default US accepts US JP CN, codes must be added to strings and WiFiSetCountry atm --- WiFiManager.cpp | 28 +++++++++++++++++++++++++++- WiFiManager.h | 4 ++++ strings_en.h | 4 ++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 4f5ecaa..b18423e 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -218,6 +218,8 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { 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 @@ -484,6 +486,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo // start access point DEBUG_WM(DEBUG_VERBOSE,F("Enabling AP")); startAP(); + WiFiSetCountry(); // init configportal DEBUG_WM(DEBUG_DEV,F("setupConfigPortal")); @@ -2129,6 +2132,14 @@ bool WiFiManager::getWiFiIsSaved(){ return WiFi_hasAutoConnect(); } +/** + * setCountry + * @since $dev + * @param String cc country code, must be defined in WiFiSetCountry, US, JP, CN + */ +void WiFiManager::setCountry(String cc){ + _wificountry = cc; +} // HELPERS @@ -2167,7 +2178,6 @@ void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { _debugPort.println(); } - /** * [debugSoftAPConfig description] * @access public @@ -2303,6 +2313,22 @@ String WiFiManager::getModeString(uint8_t mode){ return FPSTR(S_NA); } + +bool WiFiManager::WiFiSetCountry(){ + bool ret = false; + // @todo check if wifi is init, no idea how, doesnt seem to be exposed + if(_wificountry == "") return ret; // skip not set + else if(WiFi.getMode() == WIFI_MODE_NULL); // exception if wifi not init! + else if(_wificountry == "US") ret = esp_wifi_set_country(&WM_COUNTRY_US) == ESP_OK; + else if(_wificountry == "JP") ret = esp_wifi_set_country(&WM_COUNTRY_JP) == ESP_OK; + else if(_wificountry == "CN") ret = esp_wifi_set_country(&WM_COUNTRY_CN) == ESP_OK; + else DEBUG_WM(DEBUG_ERROR,"[ERROR] country code not found"); + + if(ret) DEBUG_WM(DEBUG_VERBOSE,"esp_wifi_set_country: " + _wificountry); + else DEBUG_WM(DEBUG_ERROR,"[ERROR] esp_wifi_set_country failed"); + return ret; +} + // set mode ignores WiFi.persistent bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { bool ret; diff --git a/WiFiManager.h b/WiFiManager.h index 99f4330..6720ce5 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -235,6 +235,7 @@ class WiFiManager // debug output platform info and versioning void debugPlatformInfo(); String htmlEntities(String str); + void setCountry(String cc); private: std::unique_ptr dnsServer; @@ -314,6 +315,8 @@ class WiFiManager boolean _preloadwifiscan = true; // preload wifiscan if true boolean _disableIpFields = false; // edge case, if true, showxFields(false) forces ip fields off instead of default show when set + String _wificountry = "US"; // country code, @todo define in strings lang + // wrapper functions for handling setting and unsetting persistent for now. bool esp32persistent = false; bool _hasBegun = false; @@ -372,6 +375,7 @@ class WiFiManager bool WiFi_scanNetworks(); bool WiFi_scanNetworks(bool force); bool WiFi_scanNetworks(unsigned int cachetime); + bool WiFiSetCountry(); #ifdef ESP32 static void WiFiEvent(WiFiEvent_t event, system_event_info_t info); diff --git a/strings_en.h b/strings_en.h index 60850a2..de5d57d 100644 --- a/strings_en.h +++ b/strings_en.h @@ -318,3 +318,7 @@ const char * const AUTH_MODE_NAMES[] PROGMEM #endif const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; + +const wifi_country_t WM_COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; \ No newline at end of file From 2db93d28c74ab4444ba118c7345c184e757d0a43 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 19 Jul 2018 10:05:25 -0500 Subject: [PATCH 046/146] clean up --- WiFiManager.h | 6 +- .../OnDemandConfigPortal.ino | 67 ++++++++++--------- 2 files changed, 39 insertions(+), 34 deletions(-) diff --git a/WiFiManager.h b/WiFiManager.h index 6720ce5..1c26eab 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -294,9 +294,6 @@ class WiFiManager int _staShowDns = 0; // ternary always show dns, only if not set in code, never(cannot change dns via web!) boolean _removeDuplicateAPs = true; // remove dup aps from wifiscan boolean _shouldBreakAfterConfig = false; // stop configportal on save failure -#ifdef NO_EXTRA_4K_HEAP - boolean _tryWPS = false; // try WPS on save failure, unsupported -#endif boolean _configPortalIsBlocking = true; // configportal enters blocking loop boolean _enableCaptivePortal = true; // enable captive portal redirection boolean _userpersistent = true; // users preffered persistence to restore @@ -324,9 +321,12 @@ class WiFiManager void _end(); void setupConfigPortal(); + #ifdef NO_EXTRA_4K_HEAP + boolean _tryWPS = false; // try WPS on save failure, unsupported void startWPS(); #endif + bool startAP(); uint8_t connectWifi(String ssid, String pass); diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index 0060d6d..cdd718c 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -1,12 +1,9 @@ #include // https://github.com/tzapu/WiFiManager -// select which pin will trigger the configuration portal when set to LOW -// ESP-01 users please note: the only pins available (0 and 2), are shared -// with the bootloader, so always set them HIGH at power-up #define TRIGGER_PIN 0 const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; -WiFiManager wifiManager; +WiFiManager wm; void setup() { @@ -21,27 +18,27 @@ void setup() { // Serial.println(modes[WiFi.getMode()]); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around - // WiFiManager wifiManager; + // WiFiManager wm; //Local intialization. Once its business is done, there is no need to keep it around //reset settings - for testing - //wifiManager.resetSettings(); + //wm.resetSettings(); //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds - wifiManager.setConfigPortalTimeout(60); - wifiManager.setConnectTimeout(20); - // wifiManager.setShowStaticFields(true); + wm.setConfigPortalTimeout(60); + wm.setConnectTimeout(10); + // wm.setShowStaticFields(true); - // uint8_t menu[] = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE}; - // wifiManager.setMenu(menu); + // uint8_t menu[] = {wm.MENU_WIFI,wm.MENU_INFO,wm.MENU_PARAM,wm.MENU_CLOSE}; + // wm.setMenu(menu); - // std::vector menu = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE,wifiManager.MENU_SEP,wifiManager.MENU_ERASE,wifiManager.MENU_EXIT}; - // wifiManager.setMenu(menu); + // std::vector menu = {wm.MENU_WIFI,wm.MENU_INFO,wm.MENU_PARAM,wm.MENU_CLOSE,wm.MENU_SEP,wm.MENU_ERASE,wm.MENU_EXIT}; + // wm.setMenu(menu); -// std::vector menu = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE,wifiManager.MENU_SEP,wifiManager.MENU_ERASE,wifiManager.MENU_EXIT}; - // wifiManager.setMenu(menu); +// std::vector menu = {wm.MENU_WIFI,wm.MENU_INFO,wm.MENU_PARAM,wm.MENU_CLOSE,wm.MENU_SEP,wm.MENU_ERASE,wm.MENU_EXIT}; + // wm.setMenu(menu); WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); @@ -50,10 +47,10 @@ void setup() { WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); //add all your parameters here - wifiManager.addParameter(&custom_mqtt_server); - wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_token); - wifiManager.addParameter(&custom_tokenb); + wm.addParameter(&custom_mqtt_server); + wm.addParameter(&custom_mqtt_port); + wm.addParameter(&custom_token); + wm.addParameter(&custom_tokenb); // MENU_WIFI = 0, // MENU_WIFINOSCAN = 1, @@ -66,24 +63,32 @@ void setup() { // MENU_SEP = 8 // const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - // wifiManager.setMenu(menu,9); + // wm.setMenu(menu,9); std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - wifiManager.setMenu(menu); + wm.setMenu(menu); //set static ip - // wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - // wifiManager.setShowStaticFields(false); - // wifiManager.setShowDnsFields(false); + // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // wm.setShowStaticFields(false); + // wm.setShowDnsFields(false); - wifiManager.setConfigPortalTimeout(60); - wifiManager.startConfigPortal("AutoConnectAP", "password"); + // WiFi.mode(WIFI_STA); + // const wifi_country_t COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; + // const wifi_country_t COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; + // const wifi_country_t COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; + // esp_wifi_set_country(&COUNTRY_US); + + wm.setCountry("US"); + + // wm.setConfigPortalTimeout(120); + // wm.startConfigPortal("AutoConnectAP", "password"); //fetches ssid and pass and tries to connect //if it does not connect it starts an access point with the specified name //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration - if(!wifiManager.autoConnect("AutoConnectAP")) { + if(!wm.autoConnect("AutoConnectAP","password")) { Serial.println("failed to connect and hit timeout"); } @@ -97,12 +102,12 @@ void loop() { //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around //reset settings - for testing - //wifiManager.resetSettings(); + //wm.resetSettings(); //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds - wifiManager.setConfigPortalTimeout(120); + wm.setConfigPortalTimeout(120); //it starts an access point with the specified name //here "AutoConnectAP" @@ -112,9 +117,9 @@ void loop() { //WiFi.mode(WIFI_STA); // disable captive portal redirection - // wifiManager.setCaptivePortalEnable(false); + // wm.setCaptivePortalEnable(false); - if (!wifiManager.startConfigPortal("OnDemandAP")) { + if (!wm.startConfigPortal("OnDemandAP")) { Serial.println("failed to connect and hit timeout"); delay(3000); } else { From c9ca210803c30a84269e170eb0c06ff8e35c965a Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 19 Jul 2018 11:33:38 -0500 Subject: [PATCH 047/146] removing US default --- WiFiManager.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.h b/WiFiManager.h index 1c26eab..6433261 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -312,7 +312,7 @@ class WiFiManager boolean _preloadwifiscan = true; // preload wifiscan if true boolean _disableIpFields = false; // edge case, if true, showxFields(false) forces ip fields off instead of default show when set - String _wificountry = "US"; // country code, @todo define in strings lang + String _wificountry = ""; // country code, @todo define in strings lang // wrapper functions for handling setting and unsetting persistent for now. bool esp32persistent = false; From 37cdda33c7b0ebd525892fc23f825cb530febcc9 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 19 Jul 2018 13:10:37 -0500 Subject: [PATCH 048/146] adds setClass(invert) black theme adds class string to body, invert(black) is built in ` wm.setClass("invert");` --- WiFiManager.cpp | 20 ++++++++++++++++++-- WiFiManager.h | 5 +++++ extras/WiFiManager.template.html | 24 +++++++++++++++++++----- strings_en.h | 28 ++++++++++++++-------------- 4 files changed, 56 insertions(+), 21 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index b18423e..39cea64 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -817,7 +817,16 @@ String WiFiManager::getHTTPHead(String title){ page += FPSTR(HTTP_SCRIPT); page += FPSTR(HTTP_STYLE); page += _customHeadElement; - page += FPSTR(HTTP_HEAD_END); + + 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; } @@ -1567,7 +1576,6 @@ void WiFiManager::handleErase(boolean opt) { DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Erase")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase - page += FPSTR(HTTP_HEAD_END); bool ret = erase(opt); @@ -2141,6 +2149,14 @@ void WiFiManager::setCountry(String cc){ _wificountry = cc; } +/** + * setClass + * @param String str body class string + */ +void WiFiManager::setClass(String str){ + _bodyClass = str; +} + // HELPERS // DEBUG diff --git a/WiFiManager.h b/WiFiManager.h index 6433261..7f63817 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -235,7 +235,11 @@ class WiFiManager // debug output platform info and versioning void debugPlatformInfo(); String htmlEntities(String str); + + // set the country code for wifi settings void setCountry(String cc); + // set body class (invert) + void setClass(String str); private: std::unique_ptr dnsServer; @@ -307,6 +311,7 @@ class WiFiManager const char * _hostname = ""; const char* _customHeadElement = ""; // store custom head element html from user + String _bodyClass = ""; // class to add to body // internal options boolean _preloadwifiscan = true; // preload wifiscan if true diff --git a/extras/WiFiManager.template.html b/extras/WiFiManager.template.html index e3b6ee9..e4dc77f 100644 --- a/extras/WiFiManager.template.html +++ b/extras/WiFiManager.template.html @@ -7,6 +7,23 @@ "; const char HTTP_HELP[] PROGMEM = @@ -134,7 +134,7 @@ const char HTTP_JS[] PROGMEM = #ifdef ESP32 const char HTTP_INFO_esphead[] PROGMEM = "

esp32


"; const char HTTP_INFO_chiprev[] PROGMEM = "
Chip Rev
{1}
"; - const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
CPU0: {1}
CPU1: {2}
"; + const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
CPU0: {1}
CPU1: {2}
"; const char HTTP_INFO_aphost[] PROGMEM = "
Acccess Point Hostname
{1}
"; #else const char HTTP_INFO_esphead[] PROGMEM = "

esp8266


"; @@ -245,11 +245,11 @@ const char S_dns[] PROGMEM = "dns"; // softap ssid default prefix #ifdef ESP8266 - const char S_ssidpre[] PROGMEM = "ESP"; + const char S_ssidpre[] PROGMEM = "ESP"; #elif defined(ESP32) - const char S_ssidpre[] PROGMEM = "ESP32"; + const char S_ssidpre[] PROGMEM = "ESP32"; #else - const char S_ssidpre[] PROGMEM = "WM"; + const char S_ssidpre[] PROGMEM = "WM"; #endif //Tokens @@ -276,8 +276,8 @@ const char T_h[] PROGMEM = "{h}"; // @token h const char HTTP_HEAD_CL[] PROGMEM = "Content-Length"; const char HTTP_HEAD_CT[] PROGMEM = "text/html"; const char HTTP_HEAD_CT2[] PROGMEM = "text/plain"; -const char HTTP_HEAD_CORS[] PROGMEM = "Access-Control-Allow-Origin"; -const char HTTP_HEAD_CORS_ALLOW_ALL[] PROGMEM = "*"; +const char HTTP_HEAD_CORS[] PROGMEM = "Access-Control-Allow-Origin"; +const char HTTP_HEAD_CORS_ALLOW_ALL[] PROGMEM = "*"; const char * const WIFI_STA_STATUS[] PROGMEM { From f2f0aabe3e75fd495c87f1b4a4a14f82184f02f8 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 19 Jul 2018 14:02:02 -0500 Subject: [PATCH 049/146] dark theme tweaks --- examples/Advanced/Advanced.ino | 3 +++ extras/WiFiManager.template.html | 23 ++++++++++++----------- strings_en.h | 8 ++++---- 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/examples/Advanced/Advanced.ino b/examples/Advanced/Advanced.ino index f47b021..7bc3795 100644 --- a/examples/Advanced/Advanced.ino +++ b/examples/Advanced/Advanced.ino @@ -30,6 +30,9 @@ void setup() { // wm.setMenu(menu,6); std::vector menu = {"wifi","info","param","sep","restart","exit"}; wm.setMenu(menu); + + // set dark theme + // wm.setClass("invert"); //set static ip // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn diff --git a/extras/WiFiManager.template.html b/extras/WiFiManager.template.html index e4dc77f..ecb09de 100644 --- a/extras/WiFiManager.template.html +++ b/extras/WiFiManager.template.html @@ -11,13 +11,14 @@ body.invert, body.invert a, body.invert h1 { - background-color:black; + background-color:#060606; color:white; } body.invert .msg{ - border-top: 1px solid #696969; - border-right: 1px solid #696969; - border-bottom: 1px solid #696969; + background-color: #282828; + border-top: 1px solid #555; + border-right: 1px solid #555; + border-bottom: 1px solid #555; } body.invert .q[role=img] { -webkit-filter: invert(1); @@ -46,7 +47,7 @@ input { button { border: 0; border-radius: .3rem; - background-color: #1fa3ec; + background-color: #9933CC; color: #fff; line-height: 2.4rem; font-size: 1.2rem; @@ -58,7 +59,7 @@ a { text-decoration: none; } a:hover { - color: #1fa3ec; + color: #9933CC; text-decoration: underline; } .h { @@ -123,10 +124,10 @@ a:hover { margin-bottom: 5px; } .msg.P { - border-left-color: #1fa3ec; + border-left-color: #9933CC; } .msg.P h4 { - color: #1fa3ec; + color: #9933CC; } /*.msg.S { border-left-color: #5cb85c; @@ -135,10 +136,10 @@ a:hover { color: #5cb85c; }*/ .msg.D { - border-left-color: #d9534f; + border-left-color: #dc3630; } .msg.D h4 { - color: #d9534f; + color: #dc3630; } dt { @@ -152,7 +153,7 @@ td { vertical-align: top; } button.D{ - background-color:#d9534f; + background-color:#dc3630; } diff --git a/strings_en.h b/strings_en.h index 097d971..2ef052e 100644 --- a/strings_en.h +++ b/strings_en.h @@ -73,15 +73,15 @@ const char HTTP_STYLE[] PROGMEM = ""; From ad623cb586ec73ed92fc28e3087101e76742fec4 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 19 Jul 2018 16:03:14 -0500 Subject: [PATCH 050/146] oops --- strings_en.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/strings_en.h b/strings_en.h index 2ef052e..2fd34af 100644 --- a/strings_en.h +++ b/strings_en.h @@ -80,8 +80,8 @@ const char HTTP_STYLE[] PROGMEM = ""; From 24de319c7ecd618bacb65206a85cf678939c2cca Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 19 Jul 2018 16:54:38 -0500 Subject: [PATCH 051/146] issues with captive portals and preloadscan hammering --- WiFiManager.cpp | 10 +++++++--- extras/WiFiManager.template.html | 1 + 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 39cea64..c051ef0 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -856,7 +856,10 @@ void WiFiManager::handleRoot() { 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((unsigned)10000); // preload wifiscan throttled + if(_preloadwifiscan) WiFi_scanNetworks((unsigned)20000); // preload wifiscan throttled + // @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 } /** @@ -945,11 +948,12 @@ bool WiFiManager::WiFi_scanNetworks(bool force){ // DEBUG_WM("scanNetworks force:",force == true); // DEBUG_WM(_numNetworks,(millis()-_lastscan )); if(force || _numNetworks == 0 || (millis()-_lastscan > 60000)){ + unsigned int _scanstart = millis(); _numNetworks = WiFi.scanNetworks(); _lastscan = millis(); - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan done")); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan done"), "in "+(String)(_lastscan - _scanstart)+"ms"); return true; - } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached"); + } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+"ago"); return false; } diff --git a/extras/WiFiManager.template.html b/extras/WiFiManager.template.html index ecb09de..9a0b082 100644 --- a/extras/WiFiManager.template.html +++ b/extras/WiFiManager.template.html @@ -19,6 +19,7 @@ body.invert .msg{ border-top: 1px solid #555; border-right: 1px solid #555; border-bottom: 1px solid #555; + color:#fff; } body.invert .q[role=img] { -webkit-filter: invert(1); From 8d5e9e397728ae63509b6d977b3617bed0510b7c Mon Sep 17 00:00:00 2001 From: Shawn A Date: Fri, 20 Jul 2018 16:16:08 -0500 Subject: [PATCH 052/146] esp32 autoconnect is deprecated https://github.com/espressif/esp-idf/issues/1960 --- WiFiManager.cpp | 5 +++-- WiFiManager.h | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index c051ef0..72ebaaa 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1338,8 +1338,7 @@ void WiFiManager::handleInfo() { F("dnss"), F("host"), F("stamac"), - F("conx"), - F("autoconx") + F("conx") }; for(size_t i=0; i<23;i++){ @@ -1532,8 +1531,10 @@ String WiFiManager::getInfoData(String id){ p.replace(FPSTR(T_1),WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); } else if(id==F("autoconx")){ + #ifdef ESP8266 p = FPSTR(HTTP_INFO_autoconx); p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); + #endif } return p; } diff --git a/WiFiManager.h b/WiFiManager.h index 7f63817..49f17fd 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -428,7 +428,7 @@ class WiFiManager } wm_debuglevel_t; boolean _debug = true; - uint8_t _debugLevel = DEBUG_VERBOSE; + uint8_t _debugLevel = DEBUG_DEV; Stream& _debugPort; // debug output stream ref template From cba606b84697615629040ddeb3c1260e600dfd65 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Fri, 20 Jul 2018 16:23:38 -0500 Subject: [PATCH 053/146] password invalid better error msg --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 72ebaaa..b3a7deb 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -2285,7 +2285,7 @@ boolean WiFiManager::validApPassword(){ if (_apPassword == NULL) _apPassword = ""; if (_apPassword != "") { if (_apPassword.length() < 8 || _apPassword.length() > 63) { - DEBUG_WM(F("AccessPoint set password is INVALID")); + DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); _apPassword = ""; return false; // @todo FATAL or fallback to empty ? } From afbad01ee10196edb07c8958c524a3a3095d46e4 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Fri, 20 Jul 2018 16:32:43 -0500 Subject: [PATCH 054/146] dev test sketch --- .../OnDemandConfigPortal.ino | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index cdd718c..fcf1b8f 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -12,7 +12,7 @@ void setup() { Serial.setDebugOutput(true); delay(3000); Serial.println("\n Starting"); - + // WiFi.mode(WIFI_STA); // WiFi.printDiag(Serial); // Serial.println(modes[WiFi.getMode()]); @@ -22,12 +22,14 @@ void setup() { //Local intialization. Once its business is done, there is no need to keep it around //reset settings - for testing - //wm.resetSettings(); + // wm.resetSettings(); + // + wm.setClass("invert"); //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds - wm.setConfigPortalTimeout(60); + // wm.setConfigPortalTimeout(600); wm.setConnectTimeout(10); // wm.setShowStaticFields(true); @@ -43,7 +45,7 @@ void setup() { WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); - WiFiManagerParameter custom_token("api_token", "api token", "", 0); + WiFiManagerParameter custom_token("api_token", "api token", "", 16); WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); //add all your parameters here @@ -79,8 +81,8 @@ void setup() { // const wifi_country_t COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; // esp_wifi_set_country(&COUNTRY_US); - wm.setCountry("US"); - + // wm.setCountry("US"); + // wm.setConfigPortalTimeout(120); // wm.startConfigPortal("AutoConnectAP", "password"); @@ -88,7 +90,7 @@ void setup() { //if it does not connect it starts an access point with the specified name //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration - if(!wm.autoConnect("AutoConnectAP","password")) { + if(!wm.autoConnect("AutoConnectAP","123456789")) { Serial.println("failed to connect and hit timeout"); } From 2c41af00f5ac244dca1500fd628736a12365cf5e Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 22 Jul 2018 10:41:50 -0500 Subject: [PATCH 055/146] fixes #671 --- WiFiManager.cpp | 4 +++- strings_en.h | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index b3a7deb..a088478 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -2334,9 +2334,9 @@ String WiFiManager::getModeString(uint8_t mode){ return FPSTR(S_NA); } - bool WiFiManager::WiFiSetCountry(){ bool ret = false; + #ifdef ESP32 // @todo check if wifi is init, no idea how, doesnt seem to be exposed if(_wificountry == "") return ret; // skip not set else if(WiFi.getMode() == WIFI_MODE_NULL); // exception if wifi not init! @@ -2347,9 +2347,11 @@ bool WiFiManager::WiFiSetCountry(){ if(ret) DEBUG_WM(DEBUG_VERBOSE,"esp_wifi_set_country: " + _wificountry); else DEBUG_WM(DEBUG_ERROR,"[ERROR] esp_wifi_set_country failed"); + #endif return ret; } + // set mode ignores WiFi.persistent bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { bool ret; diff --git a/strings_en.h b/strings_en.h index 2fd34af..09a0e8b 100644 --- a/strings_en.h +++ b/strings_en.h @@ -319,6 +319,8 @@ const char * const AUTH_MODE_NAMES[] PROGMEM const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; +#ifdef esp32 const wifi_country_t WM_COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; const wifi_country_t WM_COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; -const wifi_country_t WM_COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; \ No newline at end of file +const wifi_country_t WM_COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; +#endif \ No newline at end of file From 704a7ae393e8b8f820a73924d0480aae85781c26 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 22 Jul 2018 10:47:33 -0500 Subject: [PATCH 056/146] hotfix WPS NO_EXTRA_4K_HEAP --- WiFiManager.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index ec235e8..2e7884d 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -308,11 +308,13 @@ int WiFiManager::connectWifi(String ssid, String pass) { DEBUG_WM ("Connection result: "); DEBUG_WM ( connRes ); //not connected, WPS enabled, no pass - first attempt + #ifdef NO_EXTRA_4K_HEAP if (_tryWPS && connRes != WL_CONNECTED && pass == "") { startWPS(); //should be connected at the end of WPS connRes = waitForConnectResult(); } + #endif return connRes; } From e18bc49a2a25c19035c5dbb44217cb8f3b52ac73 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Mon, 23 Jul 2018 07:06:22 -0500 Subject: [PATCH 057/146] Wrong case --- strings_en.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/strings_en.h b/strings_en.h index 09a0e8b..edbc84e 100644 --- a/strings_en.h +++ b/strings_en.h @@ -319,8 +319,8 @@ const char * const AUTH_MODE_NAMES[] PROGMEM const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; -#ifdef esp32 +#ifdef ESP32 const wifi_country_t WM_COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; const wifi_country_t WM_COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; const wifi_country_t WM_COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; -#endif \ No newline at end of file +#endif From 02de95c5293011f65c3b9f0f365ef5e7ef75d949 Mon Sep 17 00:00:00 2001 From: dontsovcmc Date: Sat, 4 Aug 2018 20:29:55 +0300 Subject: [PATCH 058/146] issuu #644 add utf-8 charset to head --- WiFiManager.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.h b/WiFiManager.h index 3da163e..64bb96e 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -22,7 +22,7 @@ extern "C" { #include "user_interface.h" } -const char HTTP_HEAD[] PROGMEM = "{v}"; +const char HTTP_HEAD[] PROGMEM = "{v}"; const char HTTP_STYLE[] PROGMEM = ""; const char HTTP_SCRIPT[] PROGMEM = ""; const char HTTP_HEAD_END[] PROGMEM = "
"; From b855c0a4404d0b10dd2b72847f54a69630121ca2 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 5 Aug 2018 10:48:23 -0500 Subject: [PATCH 059/146] updating library managers --- library.json | 20 ++++++++++++++++---- library.properties | 10 +++++----- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/library.json b/library.json index 99b43c3..0ceb4c8 100644 --- a/library.json +++ b/library.json @@ -1,8 +1,20 @@ { "name": "WifiManager", - "keywords": "wifi, wi-fi", - "description": "ESP8266 WiFi Connection manager with fallback web configuration portal", - "repository": + "keywords": "wifi,wi-fi,esp,esp8266,esp32,espressif8266,espressif32,nodemcu,wemos,arduino", + "description": "WiFi Configuration manager with web configuration portal for ESP boards", +"authors": +[ + { + "name": "tzapu", + "url": "https://github.com/tzapu" + }, + { + "name": "tablatronix", + "url": "https://github.com/tablatronix", + "maintainer": true + } +], +"repository": { "type": "git", "url": "https://github.com/tzapu/WiFiManager.git" @@ -13,5 +25,5 @@ "espressif8266", "espressif32" ], - "version": "0.12" + "version": "1.0.0" } diff --git a/library.properties b/library.properties index 382a56a..5ee6e46 100644 --- a/library.properties +++ b/library.properties @@ -1,9 +1,9 @@ name=WiFiManager -version=0.12 -author=tzapu -maintainer=tzapu -sentence=WiFi Connection manager with fallback web configuration portal for ESP boards -paragraph=Library for configuring ESP8266 modules WiFi credentials at runtime. +version=1.0.0 +author=tzapu,tablatronix +maintainer=tablatronix +sentence=WiFi Configuration manager with web configuration portal for ESP boards +paragraph=Library for configuring ESP8266/ESP32 modules WiFi credentials and custom parameters at runtime. category=Communication url=https://github.com/tzapu/WiFiManager.git architectures=esp8266,esp32 From 6a139688f3876b3bdf90d0a09b58dec04ce4b516 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 5 Aug 2018 11:03:39 -0500 Subject: [PATCH 060/146] ver .13 --- library.json | 2 +- library.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library.json b/library.json index 44400f6..27c6385 100644 --- a/library.json +++ b/library.json @@ -9,5 +9,5 @@ }, "frameworks": "arduino", "platforms": "espressif8266", - "version": "0.12" + "version": "0.13" } diff --git a/library.properties b/library.properties index 2466f0d..0fc964a 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=WiFiManager -version=0.12 +version=0.13 author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal From 440f312575fc92ed7fe6eec9f81f33b1c011fbbe Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sun, 5 Aug 2018 11:06:15 -0500 Subject: [PATCH 061/146] v 0.14 --- library.json | 2 +- library.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library.json b/library.json index 27c6385..8f0830a 100644 --- a/library.json +++ b/library.json @@ -9,5 +9,5 @@ }, "frameworks": "arduino", "platforms": "espressif8266", - "version": "0.13" + "version": "0.14" } diff --git a/library.properties b/library.properties index 0fc964a..e0420ad 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=WiFiManager -version=0.13 +version=0.14 author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal From 573f8113ef9dbae21cd709500b4e1e4046f9e8c3 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 7 Aug 2018 12:48:00 -0500 Subject: [PATCH 062/146] fixes #691 --- WiFiManager.cpp | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index a088478..8393e18 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1272,8 +1272,11 @@ void WiFiManager::handleInfo() { String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo reportStatus(page); - //@todo convert to enum + int infos = 0; + + //@todo convert to enum or refactor to strings #ifdef ESP8266 + infos = 27; String infoids[] = { F("esphead"), F("uptime"), @@ -1304,28 +1307,18 @@ void WiFiManager::handleInfo() { F("autoconx") }; - for(size_t i=0; i<27;i++){ - if(infoids[i] != NULL) page += getInfoData(infoids[i]); - } - page += F("
"); - #elif defined(ESP32) + infos = 22; String infoids[] = { F("esphead"), F("uptime"), F("chipid"), - F("chiprev"), // esp32 - // "fchipid)", //esp8266 - F("idesize"), //esp8266 - // "flashsize)", //esp8266 + F("chiprev"), + F("idesize"), F("sdkver"), - // "corever)", //esp8266 - // "bootver)", //esp8266 F("cpufreq"), F("freeheap"), - // "memsketch)", //esp8266 - // "memsmeter)", //esp8266 - F("lastreset"), //esp8266 + F("lastreset"), F("wifihead"), F("apip"), F("apmac"), @@ -1340,13 +1333,12 @@ void WiFiManager::handleInfo() { F("stamac"), F("conx") }; - - for(size_t i=0; i<23;i++){ - if(infoids[i] != NULL) page += getInfoData(infoids[i]); - } - page += F("
"); #endif + for(size_t i=0; i"); if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); page += FPSTR(HTTP_HELP); page += FPSTR(HTTP_END); @@ -1530,12 +1522,12 @@ String WiFiManager::getInfoData(String id){ p = FPSTR(HTTP_INFO_conx); p.replace(FPSTR(T_1),WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); } + #ifdef ESP8266 else if(id==F("autoconx")){ - #ifdef ESP8266 p = FPSTR(HTTP_INFO_autoconx); p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); - #endif } + #endif return p; } From 5a5f1c631b99129f57a4cf8dd10ec234bbd2c709 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 7 Aug 2018 13:55:14 -0500 Subject: [PATCH 063/146] fix warning --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 8393e18..732fef8 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1272,7 +1272,7 @@ void WiFiManager::handleInfo() { String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo reportStatus(page); - int infos = 0; + uint16_t infos = 0; //@todo convert to enum or refactor to strings #ifdef ESP8266 From c6ecad1b3a8db814676d7186efa421f01a1cf9fd Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 7 Aug 2018 13:55:45 -0500 Subject: [PATCH 064/146] fixes #678 --- WiFiManager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 732fef8..faefd4c 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -25,7 +25,7 @@ uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS; WiFiManagerParameter::WiFiManagerParameter(const char *custom) { _id = NULL; _placeholder = NULL; - _length = 0; + _length = 1; _value = NULL; _labelPlacement = WFM_LABEL_BEFORE; _customHTML = custom; @@ -63,7 +63,7 @@ WiFiManagerParameter::~WiFiManagerParameter() { } void WiFiManagerParameter::setValue(const char *defaultValue, int length) { - _length = length; + _length = length; int deflength = strlen(defaultValue); // length actual // use the defult length if it's longer, // @todo consider it might be useful to fail, so user knows they were wrong From 768a965810d5069802cf673c36c7a2d1d307c113 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 7 Aug 2018 13:57:10 -0500 Subject: [PATCH 065/146] remove custom ip from example --- .../AutoConnectWithFSParameters.ino | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index 07c7dd9..41024da 100644 --- a/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -55,15 +55,15 @@ void setupSpiffs(){ strcpy(mqtt_port, json["mqtt_port"]); strcpy(api_token, json["api_token"]); - if(json["ip"]) { - Serial.println("setting custom ip from config"); - strcpy(static_ip, json["ip"]); - strcpy(static_gw, json["gateway"]); - strcpy(static_sn, json["subnet"]); - Serial.println(static_ip); - } else { - Serial.println("no custom ip in config"); - } + // if(json["ip"]) { + // Serial.println("setting custom ip from config"); + // strcpy(static_ip, json["ip"]); + // strcpy(static_gw, json["gateway"]); + // strcpy(static_sn, json["subnet"]); + // Serial.println(static_ip); + // } else { + // Serial.println("no custom ip in config"); + // } } else { Serial.println("failed to load json config"); @@ -104,11 +104,11 @@ void setup() { wm.addParameter(&custom_api_token); // set static ip - IPAddress _ip,_gw,_sn; - _ip.fromString(static_ip); - _gw.fromString(static_gw); - _sn.fromString(static_sn); - wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); + // IPAddress _ip,_gw,_sn; + // _ip.fromString(static_ip); + // _gw.fromString(static_gw); + // _sn.fromString(static_sn); + // wm.setSTAStaticIPConfig(_ip, _gw, _sn); //reset settings - wipe credentials for testing //wm.resetSettings(); @@ -125,6 +125,10 @@ void setup() { delay(5000); } + // always start configportal for a little while + wm.setConfigPortalTimeout(60); + wm.startConfigPortal("AutoConnectAP","password"); + //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); @@ -142,9 +146,9 @@ void setup() { json["mqtt_port"] = mqtt_port; json["api_token"] = api_token; - json["ip"] = WiFi.localIP().toString(); - json["gateway"] = WiFi.gatewayIP().toString(); - json["subnet"] = WiFi.subnetMask().toString(); + // json["ip"] = WiFi.localIP().toString(); + // json["gateway"] = WiFi.gatewayIP().toString(); + // json["subnet"] = WiFi.subnetMask().toString(); File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { From e9c4cdb2c63675ce74dae61c89cc8b0b311fde85 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 7 Aug 2018 14:06:31 -0500 Subject: [PATCH 066/146] disable setvalue on customhtml params --- WiFiManager.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index faefd4c..01e9c13 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -63,6 +63,10 @@ WiFiManagerParameter::~WiFiManagerParameter() { } void WiFiManagerParameter::setValue(const char *defaultValue, int length) { + if(!_id){ + // Serial.println("cannot set value of this parameter"); + return; + } _length = length; int deflength = strlen(defaultValue); // length actual // use the defult length if it's longer, From c6027058c906ad8235de6a370888c588d6848383 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 9 Aug 2018 15:21:12 -0500 Subject: [PATCH 067/146] added some debugging and testing --- WiFiManager.cpp | 3 +- .../OnDemandConfigPortal.ino | 131 +++++++++++++++++- 2 files changed, 130 insertions(+), 4 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 01e9c13..330721d 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -627,8 +627,9 @@ boolean WiFiManager::stopConfigPortal(){ if(!ret)DEBUG_WM(DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); // WiFi_Mode(_usermode); // restore users wifi mode, BUG https://github.com/esp8266/Arduino/issues/4372 // DEBUG_WM("usermode",_usermode); - // DEBUG_WM(getWLStatusString(WiFi.status())); if(WiFi.status()==WL_IDLE_STATUS) WiFi.reconnect(); // restart wifi since we disconnected it in startconfigportal + DEBUG_WM("wifi status:",getWLStatusString(WiFi.status())); + DEBUG_WM("wifi mode:",getModeString(WiFi.getMode())); configPortalActive = false; return ret; } diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index fcf1b8f..b66f1e7 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -1,3 +1,6 @@ +/** + * This is a kind of unit test for DEV for now + */ #include // https://github.com/tzapu/WiFiManager #define TRIGGER_PIN 0 @@ -5,6 +8,26 @@ const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; WiFiManager wm; +#include +#include + +char ssid[] = "*************"; // your network SSID (name) +char pass[] = "********"; // your network password + +unsigned int localPort = 2390; // local port to listen for UDP packets + +/* Don't hardwire the IP address or we won't get the benefits of the pool. + * Lookup the IP address for the host name instead */ +//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server +IPAddress timeServerIP; // time.nist.gov NTP server address +const char* ntpServerName = "time.nist.gov"; +// const char* ntpServerName = "ns1.mtsu.edu"; +const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message +byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets + +// A UDP instance to let us send and receive packets over UDP +WiFiUDP udp; + void setup() { // put your setup code here, to run once: @@ -13,13 +36,20 @@ void setup() { delay(3000); Serial.println("\n Starting"); + Serial.println("Starting UDP"); + udp.begin(localPort); + Serial.print("Local port: "); + Serial.println(udp.localPort()); + // WiFi.mode(WIFI_STA); - // WiFi.printDiag(Serial); + WiFi.printDiag(Serial); // Serial.println(modes[WiFi.getMode()]); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around // WiFiManager wm; + wm.debugPlatformInfo(); + //Local intialization. Once its business is done, there is no need to keep it around //reset settings - for testing // wm.resetSettings(); @@ -43,17 +73,22 @@ void setup() { // wm.setMenu(menu); + WiFiManagerParameter custom_html("

This Is Custom HTML

"); WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); WiFiManagerParameter custom_token("api_token", "api token", "", 16); WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); //add all your parameters here + wm.addParameter(&custom_html); wm.addParameter(&custom_mqtt_server); wm.addParameter(&custom_mqtt_port); wm.addParameter(&custom_token); wm.addParameter(&custom_tokenb); + custom_html.setValue("test",4); + custom_token.setValue("test",4); + // MENU_WIFI = 0, // MENU_WIFINOSCAN = 1, // MENU_INFO = 2, @@ -83,16 +118,22 @@ void setup() { // wm.setCountry("US"); - // wm.setConfigPortalTimeout(120); + wm.setConfigPortalTimeout(120); // wm.startConfigPortal("AutoConnectAP", "password"); //fetches ssid and pass and tries to connect //if it does not connect it starts an access point with the specified name //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration - if(!wm.autoConnect("AutoConnectAP","123456789")) { + + if(!wm.autoConnect("AutoConnectAP")) { Serial.println("failed to connect and hit timeout"); } + else { + // start configportal always + // wm.setConfigPortalTimeout(60); + // wm.startConfigPortal(); + } pinMode(TRIGGER_PIN, INPUT); } @@ -131,4 +172,88 @@ void loop() { } // put your main code here, to run repeatedly: + getTime(); + delay(10000); } + +// send an NTP request to the time server at the given address +void sendNTPpacket(IPAddress& address) +{ + Serial.println("sending NTP packet..."); + // set all bytes in the buffer to 0 + memset(packetBuffer, 0, NTP_PACKET_SIZE); + // Initialize values needed to form NTP request + // (see URL above for details on the packets) + packetBuffer[0] = 0b11100011; // LI, Version, Mode + packetBuffer[1] = 0; // Stratum, or type of clock + packetBuffer[2] = 6; // Polling Interval + packetBuffer[3] = 0xEC; // Peer Clock Precision + // 8 bytes of zero for Root Delay & Root Dispersion + packetBuffer[12] = 49; + packetBuffer[13] = 0x4E; + packetBuffer[14] = 49; + packetBuffer[15] = 52; + + // all NTP fields have been given values, now + // you can send a packet requesting a timestamp: + udp.beginPacket(address, 123); //NTP requests are to port 123 + udp.write(packetBuffer, NTP_PACKET_SIZE); + udp.endPacket(); +} + +void getTime(){ + //get a random server from the pool + WiFi.hostByName(ntpServerName, timeServerIP); + + sendNTPpacket(timeServerIP); // send an NTP packet to a time server + // wait to see if a reply is available + delay(1000); + + int cb = udp.parsePacket(); + if (!cb) { + Serial.println("no packet yet"); + } + else { + Serial.print("packet received, length="); + Serial.println(cb); + // We've received a packet, read the data from it + udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer + + //the timestamp starts at byte 40 of the received packet and is four bytes, + // or two words, long. First, esxtract the two words: + + unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); + unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); + // combine the four bytes (two words) into a long integer + // this is NTP time (seconds since Jan 1 1900): + unsigned long secsSince1900 = highWord << 16 | lowWord; + Serial.print("Seconds since Jan 1 1900 = " ); + Serial.println(secsSince1900); + + // now convert NTP time into everyday time: + Serial.print("Unix time = "); + // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: + const unsigned long seventyYears = 2208988800UL; + // subtract seventy years: + unsigned long epoch = secsSince1900 - seventyYears; + // print Unix time: + Serial.println(epoch); + + + // print the hour, minute and second: + Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) + Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) + Serial.print(':'); + if ( ((epoch % 3600) / 60) < 10 ) { + // In the first 10 minutes of each hour, we'll want a leading '0' + Serial.print('0'); + } + Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) + Serial.print(':'); + if ( (epoch % 60) < 10 ) { + // In the first 10 seconds of each minute, we'll want a leading '0' + Serial.print('0'); + } + Serial.println(epoch % 60); // print the second + } +} \ No newline at end of file From 4cceb95a42e626b8d2f0b96cb27ab67735b984c8 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 10 Aug 2018 11:42:09 -0500 Subject: [PATCH 068/146] debugging --- WiFiManager.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 330721d..fac7af1 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -612,8 +612,10 @@ boolean WiFiManager::stopConfigPortal(){ // @todo what is the proper way to shutdown and free the server up server->stop(); server.reset(); + // dnsServer->stop(); // free heap ? dnsServer.reset(); + if(!configPortalActive) return false; // turn off AP @@ -625,8 +627,9 @@ boolean WiFiManager::stopConfigPortal(){ bool ret = false; ret = WiFi.softAPdisconnect(false); if(!ret)DEBUG_WM(DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); - // WiFi_Mode(_usermode); // restore users wifi mode, BUG https://github.com/esp8266/Arduino/issues/4372 - // DEBUG_WM("usermode",_usermode); + delay(1000); + DEBUG_WM("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("wifi status:",getWLStatusString(WiFi.status())); DEBUG_WM("wifi mode:",getModeString(WiFi.getMode())); From 5ee1ae78c0fc808ad5eacec398d19a658ec35aa3 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 10 Aug 2018 11:45:25 -0500 Subject: [PATCH 069/146] fix callback order --- WiFiManager.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index fac7af1..90a7970 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -304,6 +304,11 @@ bool WiFiManager::startAP(){ bool ret = true; DEBUG_WM(F("StartAP with SSID: "),_apName); + // do AP callback if set + if ( _apcallback != NULL) { + _apcallback(this); + } + // setup optional soft AP static ip config if (_ap_static_ip) { DEBUG_WM(F("Custom AP IP/GW/Subnet:")); @@ -347,11 +352,6 @@ bool WiFiManager::startAP(){ } #endif - // do AP callback if set - if ( _apcallback != NULL) { - _apcallback(this); - } - return ret; } From 792ed84f4bac9df822294b16097db097d1b1b77d Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 10 Aug 2018 11:51:31 -0500 Subject: [PATCH 070/146] debugging --- WiFiManager.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 90a7970..60631b1 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -308,7 +308,7 @@ bool WiFiManager::startAP(){ if ( _apcallback != NULL) { _apcallback(this); } - + // setup optional soft AP static ip config if (_ap_static_ip) { DEBUG_WM(F("Custom AP IP/GW/Subnet:")); @@ -628,11 +628,14 @@ boolean WiFiManager::stopConfigPortal(){ ret = WiFi.softAPdisconnect(false); if(!ret)DEBUG_WM(DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); delay(1000); - DEBUG_WM("restoring usermode",getModeString(_usermode)); + 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("wifi status:",getWLStatusString(WiFi.status())); - DEBUG_WM("wifi mode:",getModeString(WiFi.getMode())); + 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; return ret; } From 915023ccb95054d1f0e126823aff0f9df80b94e7 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 10 Aug 2018 13:49:15 -0500 Subject: [PATCH 071/146] fixes #619 unconfirmed needed --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 60631b1..9f66fcd 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -612,7 +612,7 @@ boolean WiFiManager::stopConfigPortal(){ // @todo what is the proper way to shutdown and free the server up server->stop(); server.reset(); - // dnsServer->stop(); // free heap ? + dnsServer->stop(); // free heap ? dnsServer.reset(); From f1a1f44a086c62af3121aa932f163526ae36e929 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 15 Aug 2018 19:11:53 -0500 Subject: [PATCH 072/146] #700 --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 9f66fcd..d04c109 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -615,7 +615,6 @@ boolean WiFiManager::stopConfigPortal(){ dnsServer->stop(); // free heap ? dnsServer.reset(); - if(!configPortalActive) return false; // turn off AP @@ -637,6 +636,7 @@ boolean WiFiManager::stopConfigPortal(){ DEBUG_WM(DEBUG_VERBOSE,"wifi status:",getWLStatusString(WiFi.status())); DEBUG_WM(DEBUG_VERBOSE,"wifi mode:",getModeString(WiFi.getMode())); configPortalActive = false; + _end() return ret; } From 1b8ce615220bffa05b15738f5cd07c1c13dbf7bf Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 17 Aug 2018 19:38:53 -0500 Subject: [PATCH 073/146] well shit --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index d04c109..16f85ac 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -636,7 +636,7 @@ boolean WiFiManager::stopConfigPortal(){ DEBUG_WM(DEBUG_VERBOSE,"wifi status:",getWLStatusString(WiFi.status())); DEBUG_WM(DEBUG_VERBOSE,"wifi mode:",getModeString(WiFi.getMode())); configPortalActive = false; - _end() + _end(); return ret; } From 2074d85da740b798e3ac8d4495df2929b62e7059 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 23 Aug 2018 12:54:48 -0500 Subject: [PATCH 074/146] cleanconnect --- WiFiManager.cpp | 2 +- WiFiManager.h | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 16f85ac..806da56 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -652,7 +652,7 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { //@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 !) - WiFi_Disconnect(); // disconnect before begin, in case anything is hung, this causes a 2 seconds delay for connect + if(cleanConnect) WiFi_Disconnect(); // disconnect before begin, in case anything is hung, this causes a 2 seconds delay for connect // if ssid argument provided connect to that if (ssid != "") { diff --git a/WiFiManager.h b/WiFiManager.h index 49f17fd..bb0de74 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -283,6 +283,7 @@ class WiFiManager int _numNetworks = 0; unsigned long _lastscan = 0; // ms int _cpclosedelay = 2000; // delay before wifisave, prevents captive portal from closing to fast. + bool _cleanConnect = true; // disconnect before connect in connectwifi, increases stability on connects #ifdef ESP32 static uint8_t _lastconxresulttmp; // tmp var for esp32 callback From 8f03b5df10d9bc026d61d8d7d29529053cef1abf Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 23 Aug 2018 13:35:07 -0500 Subject: [PATCH 075/146] testing sta ap modes --- WiFiManager.cpp | 13 +++++++------ WiFiManager.h | 3 +++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 806da56..085c970 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -328,10 +328,12 @@ bool WiFiManager::startAP(){ // start soft AP with password or anonymous if (_apPassword != "") { - ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str());//password option + if(_channelSync) ret = WiFi.softAxP(_apName.c_str(), _apPassword.c_str(),WiFi.channel()); + else ret = WiFi.softAxP(_apName.c_str(), _apPassword.c_str());//password option } else { DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!")); - ret = WiFi.softAP(_apName.c_str()); + if(_channelSync) ret = WiFi.softAP(_apName.c_str(),"",WiFi.channel()); + else ret = WiFi.softAP(_apName.c_str()); } if(_debugLevel > DEBUG_DEV) debugSoftAPConfig(); @@ -465,11 +467,9 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo if(_apName == "") _apName = _wifissidprefix + "_" + String(WIFI_getChipId()); if(!validApPassword()) return false; - bool disableSTA = false; // debug, always disable sta - // 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(!WiFi.isConnected() || disableSTA){ + 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); @@ -652,7 +652,8 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { //@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 + 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 != "") { diff --git a/WiFiManager.h b/WiFiManager.h index bb0de74..d56225d 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -284,6 +284,9 @@ class WiFiManager unsigned long _lastscan = 0; // ms int _cpclosedelay = 2000; // delay before wifisave, prevents captive portal from closing to fast. bool _cleanConnect = true; // disconnect before connect in connectwifi, increases stability on connects + bool _disableSTA = false; // disable sta when starting ap, always + bool _disableSTAConn = true; // disable sta when starting ap, if sta is not connected ( stability ) + bool _channelSync = false; // use wifi channel when starting ap #ifdef ESP32 static uint8_t _lastconxresulttmp; // tmp var for esp32 callback From 3123eac5c8572be3bc81ba97baab0dea025a2294 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 23 Aug 2018 13:36:08 -0500 Subject: [PATCH 076/146] typo --- WiFiManager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 085c970..3f94fb9 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -328,8 +328,8 @@ bool WiFiManager::startAP(){ // start soft AP with password or anonymous if (_apPassword != "") { - if(_channelSync) ret = WiFi.softAxP(_apName.c_str(), _apPassword.c_str(),WiFi.channel()); - else ret = WiFi.softAxP(_apName.c_str(), _apPassword.c_str());//password option + if(_channelSync) ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),WiFi.channel()); + else ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str());//password option } else { DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!")); if(_channelSync) ret = WiFi.softAP(_apName.c_str(),"",WiFi.channel()); From c651ab4b62d2e87c89faaf28008069e23af1307f Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 23 Aug 2018 13:46:13 -0500 Subject: [PATCH 077/146] cleanup --- WiFiManager.cpp | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 3f94fb9..2c0d9ac 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -326,20 +326,32 @@ bool WiFiManager::startAP(){ delay(500); // workaround delay #endif + if(_channelSync){ + DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",WiFi.channel()); + } + // start soft AP with password or anonymous if (_apPassword != "") { - if(_channelSync) ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),WiFi.channel()); - else ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str());//password option + if(_channelSync){ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),WiFi.channel()); + } + else{ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str());//password option + } } else { DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!")); - if(_channelSync) ret = WiFi.softAP(_apName.c_str(),"",WiFi.channel()); - else ret = WiFi.softAP(_apName.c_str()); + if(_channelSync){ + ret = WiFi.softAP(_apName.c_str(),"",WiFi.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"); - // @tood add softAP retry here + // @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()); From 51432d0ef7787db12a15d0788cd32df3caad7496 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 23 Aug 2018 15:04:31 -0500 Subject: [PATCH 078/146] remove tests from example --- WiFiManager.h | 1 + .../AutoConnectWithFSParameters.ino | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/WiFiManager.h b/WiFiManager.h index d56225d..04776a3 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -284,6 +284,7 @@ class WiFiManager unsigned long _lastscan = 0; // ms int _cpclosedelay = 2000; // delay before wifisave, prevents captive portal from closing to fast. bool _cleanConnect = true; // disconnect before connect in connectwifi, increases stability on connects + bool _disableSTA = false; // disable sta when starting ap, always bool _disableSTAConn = true; // disable sta when starting ap, if sta is not connected ( stability ) bool _channelSync = false; // use wifi channel when starting ap diff --git a/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index 41024da..fea3287 100644 --- a/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -126,8 +126,8 @@ void setup() { } // always start configportal for a little while - wm.setConfigPortalTimeout(60); - wm.startConfigPortal("AutoConnectAP","password"); + // wm.setConfigPortalTimeout(60); + // wm.startConfigPortal("AutoConnectAP","password"); //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); From 28cf8eed16e617bf74be58a15b721ac7e17d1e30 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 23 Aug 2018 16:46:17 -0500 Subject: [PATCH 079/146] adding async scannetworks --- WiFiManager.cpp | 40 +++++++++++++++++++++++++++++++++++----- WiFiManager.h | 4 +++- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 2c0d9ac..6d96943 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -627,6 +627,8 @@ boolean WiFiManager::stopConfigPortal(){ dnsServer->stop(); // free heap ? dnsServer.reset(); + WiFi.scanDelete(); // free wifi scan results + if(!configPortalActive) return false; // turn off AP @@ -880,7 +882,7 @@ void WiFiManager::handleRoot() { 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((unsigned)20000); // preload wifiscan throttled + if(_preloadwifiscan) WiFi_scanNetworks((unsigned)20000,true); // preload wifiscan throttled // @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 @@ -962,18 +964,46 @@ String WiFiManager::getMenuOut(){ return page; } +// // is it possible in softap mode to detect aps without scanning +// bool WiFiManager::WiFi_scanNetworksForAP(bool force){ +// WiFi_scanNetworks(force); +// } + +void WiFiManager::WiFi_scanComplete(int networksFound){ + DEBUG_WM(DEBUG_VERBOSE,F("ASYNC WiFi Scan done")); + _numNetworks = networksFound; + _lastscan = millis(); +} + bool WiFiManager::WiFi_scanNetworks(){ - return WiFi_scanNetworks(false); + return WiFi_scanNetworks(false,false); +} + +bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime,bool async){ + return WiFi_scanNetworks(millis()-_lastscan > cachetime,async); } bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime){ - return WiFi_scanNetworks(millis()-_lastscan > cachetime); + return WiFi_scanNetworks(millis()-_lastscan > cachetime,false); } -bool WiFiManager::WiFi_scanNetworks(bool force){ +bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ // DEBUG_WM("scanNetworks force:",force == true); // DEBUG_WM(_numNetworks,(millis()-_lastscan )); if(force || _numNetworks == 0 || (millis()-_lastscan > 60000)){ unsigned int _scanstart = millis(); - _numNetworks = WiFi.scanNetworks(); + int8_t res; + // if(async) res = WiFi.scanNetworksAsync(&WiFiManager::WiFi_scanComplete); + // else + res = WiFi.scanNetworks(); + if(res == WIFI_SCAN_FAILED) DEBUG_WM(DEBUG_ERROR,"[ERROR] scan failed"); + else if(res == WIFI_SCAN_RUNNING){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] scan waiting"); + while(WiFi.scanComplete() == WIFI_SCAN_RUNNING){ + DEBUG_WM(DEBUG_ERROR,"."); + delay(100); + } + _numNetworks = WiFi.scanComplete(); + } + else if(res >=0 ) _numNetworks = res; _lastscan = millis(); DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan done"), "in "+(String)(_lastscan - _scanstart)+"ms"); return true; diff --git a/WiFiManager.h b/WiFiManager.h index 04776a3..0d243a3 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -383,8 +383,10 @@ class WiFiManager void WiFi_autoReconnect(); String WiFi_SSID(); bool WiFi_scanNetworks(); - bool WiFi_scanNetworks(bool force); + bool WiFi_scanNetworks(bool force,bool async); + bool WiFi_scanNetworks(unsigned int cachetime,bool async); bool WiFi_scanNetworks(unsigned int cachetime); + void WiFi_scanComplete(int networksFound); bool WiFiSetCountry(); #ifdef ESP32 From 34b7d1ea032a5dd3ae1ecf02a574db4ac29111ac Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 24 Aug 2018 12:19:26 -0500 Subject: [PATCH 080/146] scan preload async This changes the preload wifiscan to async and adds async support for wifi scans. preload async occursd on cp stsart and root loads(throttled) --- WiFiManager.cpp | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 6d96943..e2871fc 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -337,7 +337,7 @@ bool WiFiManager::startAP(){ } else{ ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str());//password option - } + } } else { DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!")); if(_channelSync){ @@ -454,7 +454,7 @@ void WiFiManager::setupConfigPortal() { server->begin(); // Web server start DEBUG_WM(DEBUG_VERBOSE,F("HTTP server started")); - if(_preloadwifiscan) WiFi_scanNetworks(); // preload wifiscan + if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan } boolean WiFiManager::startConfigPortal() { @@ -896,7 +896,8 @@ void WiFiManager::handleWifi(boolean scan) { handleRequest(); String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi if (scan) { - WiFi_scanNetworks(server->hasArg(F("refresh"))); //wifiscan, force if arg refresh + 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 = ""; @@ -986,20 +987,27 @@ bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime){ return WiFi_scanNetworks(millis()-_lastscan > cachetime,false); } bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ - // DEBUG_WM("scanNetworks force:",force == true); - // DEBUG_WM(_numNetworks,(millis()-_lastscan )); + // DEBUG_WM(DEBUG_DEV,"scanNetworks async:",async == true); + // DEBUG_WM(DEBUG_DEV,_numNetworks,(millis()-_lastscan )); + // DEBUG_WM(DEBUG_DEV,"scanNetworks force:",force == true); if(force || _numNetworks == 0 || (millis()-_lastscan > 60000)){ unsigned int _scanstart = millis(); - int8_t res; - // if(async) res = WiFi.scanNetworksAsync(&WiFiManager::WiFi_scanComplete); - // else - res = WiFi.scanNetworks(); + if(async){ + using namespace std::placeholders; // for `_1` + WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); + return false; + } + else{ + int8_t res; + res = WiFi.scanNetworks(); + } if(res == WIFI_SCAN_FAILED) DEBUG_WM(DEBUG_ERROR,"[ERROR] scan failed"); else if(res == WIFI_SCAN_RUNNING){ DEBUG_WM(DEBUG_ERROR,"[ERROR] scan waiting"); while(WiFi.scanComplete() == WIFI_SCAN_RUNNING){ DEBUG_WM(DEBUG_ERROR,"."); - delay(100); + delay(100); } _numNetworks = WiFi.scanComplete(); } @@ -1007,7 +1015,7 @@ bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ _lastscan = millis(); DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan done"), "in "+(String)(_lastscan - _scanstart)+"ms"); return true; - } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+"ago"); + } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+"ms ago"); return false; } From f2bbb5f4e24281d6fdacd82c9e5b0f2fe9eeb46c Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 24 Aug 2018 12:21:20 -0500 Subject: [PATCH 081/146] comments --- WiFiManager.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index e2871fc..e131fd8 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -454,7 +454,7 @@ void WiFiManager::setupConfigPortal() { server->begin(); // Web server start DEBUG_WM(DEBUG_VERBOSE,F("HTTP server started")); - if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan + if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan , async } boolean WiFiManager::startConfigPortal() { @@ -882,7 +882,7 @@ void WiFiManager::handleRoot() { 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((unsigned)20000,true); // preload wifiscan throttled + if(_preloadwifiscan) WiFi_scanNetworks((unsigned)20000,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 @@ -896,7 +896,7 @@ void WiFiManager::handleWifi(boolean scan) { handleRequest(); String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi if (scan) { - DEBUG_WM(DEBUG_DEV,"refresh flag:",server->hasArg(F("refresh"))); + // DEBUG_WM(DEBUG_DEV,"refresh flag:",server->hasArg(F("refresh"))); WiFi_scanNetworks(server->hasArg(F("refresh")),false); //wifiscan, force if arg refresh page += getScanItemOut(); } From 4f5e21647ff29c91e8044f42628562ffcc140598 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 24 Aug 2018 13:02:34 -0500 Subject: [PATCH 082/146] fix res error --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index e131fd8..4632adb 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -991,6 +991,7 @@ bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ // DEBUG_WM(DEBUG_DEV,_numNetworks,(millis()-_lastscan )); // DEBUG_WM(DEBUG_DEV,"scanNetworks force:",force == true); if(force || _numNetworks == 0 || (millis()-_lastscan > 60000)){ + int8_t res; unsigned int _scanstart = millis(); if(async){ using namespace std::placeholders; // for `_1` @@ -999,7 +1000,6 @@ bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ return false; } else{ - int8_t res; res = WiFi.scanNetworks(); } if(res == WIFI_SCAN_FAILED) DEBUG_WM(DEBUG_ERROR,"[ERROR] scan failed"); From 1bf3fc04eacc79ac1aed6090e4f37cce6fc7aea8 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 24 Aug 2018 13:37:15 -0500 Subject: [PATCH 083/146] fixes #707 --- WiFiManager.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 4632adb..f473450 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -201,7 +201,7 @@ void WiFiManager::_end(){ // AUTOCONNECT boolean WiFiManager::autoConnect() { - String ssid = _wifissidprefix + "_" + String(WIFI_getChipId()); + String ssid = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); return autoConnect(ssid.c_str(), NULL); } @@ -458,7 +458,7 @@ void WiFiManager::setupConfigPortal() { } boolean WiFiManager::startConfigPortal() { - String ssid = _wifissidprefix + "_" + String(WIFI_getChipId()); + String ssid = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); return startConfigPortal(ssid.c_str(), NULL); } @@ -476,7 +476,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo _apName = apName; // @todo check valid apname ? _apPassword = apPassword; - if(_apName == "") _apName = _wifissidprefix + "_" + String(WIFI_getChipId()); + if(_apName == "") _apName = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); 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 @@ -1425,7 +1425,7 @@ String WiFiManager::getInfoData(String id){ } else if(id==F("chipid")){ p = FPSTR(HTTP_INFO_chipid); - p.replace(FPSTR(T_1),(String)WIFI_getChipId()); + p.replace(FPSTR(T_1),String(WIFI_getChipId(),HEX)); } #ifdef ESP32 else if(id==F("chiprev")){ @@ -1817,6 +1817,7 @@ bool WiFiManager::erase(bool opt){ /** * [resetSettings description] + * ERASES STA CREDENTIALS * @access public */ void WiFiManager::resetSettings() { From b963e7f95a544c84172951485858fbf70b34eda1 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sat, 25 Aug 2018 14:55:51 -0500 Subject: [PATCH 084/146] fix esp32 fatal, disabled async --- WiFiManager.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index f473450..a2fcde3 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -994,10 +994,14 @@ bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ int8_t res; unsigned int _scanstart = millis(); if(async){ + #ifdef ESP8266 using namespace std::placeholders; // for `_1` WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); return false; + #else + res = WiFi.scanNetworks(); + #endif } else{ res = WiFi.scanNetworks(); From 16c37e5389923c8d5232884f0c0ef27482bb6a27 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Mon, 27 Aug 2018 12:16:14 -0500 Subject: [PATCH 085/146] remove npt example, not esp32 compat --- .../OnDemandConfigPortal.ino | 107 +----------------- 1 file changed, 1 insertion(+), 106 deletions(-) diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index b66f1e7..e72c921 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -8,26 +8,9 @@ const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; WiFiManager wm; -#include -#include - char ssid[] = "*************"; // your network SSID (name) char pass[] = "********"; // your network password -unsigned int localPort = 2390; // local port to listen for UDP packets - -/* Don't hardwire the IP address or we won't get the benefits of the pool. - * Lookup the IP address for the host name instead */ -//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server -IPAddress timeServerIP; // time.nist.gov NTP server address -const char* ntpServerName = "time.nist.gov"; -// const char* ntpServerName = "ns1.mtsu.edu"; -const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message -byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets - -// A UDP instance to let us send and receive packets over UDP -WiFiUDP udp; - void setup() { // put your setup code here, to run once: @@ -36,13 +19,8 @@ void setup() { delay(3000); Serial.println("\n Starting"); - Serial.println("Starting UDP"); - udp.begin(localPort); - Serial.print("Local port: "); - Serial.println(udp.localPort()); - // WiFi.mode(WIFI_STA); - WiFi.printDiag(Serial); + // WiFi.printDiag(Serial); // Serial.println(modes[WiFi.getMode()]); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around @@ -172,88 +150,5 @@ void loop() { } // put your main code here, to run repeatedly: - getTime(); delay(10000); } - -// send an NTP request to the time server at the given address -void sendNTPpacket(IPAddress& address) -{ - Serial.println("sending NTP packet..."); - // set all bytes in the buffer to 0 - memset(packetBuffer, 0, NTP_PACKET_SIZE); - // Initialize values needed to form NTP request - // (see URL above for details on the packets) - packetBuffer[0] = 0b11100011; // LI, Version, Mode - packetBuffer[1] = 0; // Stratum, or type of clock - packetBuffer[2] = 6; // Polling Interval - packetBuffer[3] = 0xEC; // Peer Clock Precision - // 8 bytes of zero for Root Delay & Root Dispersion - packetBuffer[12] = 49; - packetBuffer[13] = 0x4E; - packetBuffer[14] = 49; - packetBuffer[15] = 52; - - // all NTP fields have been given values, now - // you can send a packet requesting a timestamp: - udp.beginPacket(address, 123); //NTP requests are to port 123 - udp.write(packetBuffer, NTP_PACKET_SIZE); - udp.endPacket(); -} - -void getTime(){ - //get a random server from the pool - WiFi.hostByName(ntpServerName, timeServerIP); - - sendNTPpacket(timeServerIP); // send an NTP packet to a time server - // wait to see if a reply is available - delay(1000); - - int cb = udp.parsePacket(); - if (!cb) { - Serial.println("no packet yet"); - } - else { - Serial.print("packet received, length="); - Serial.println(cb); - // We've received a packet, read the data from it - udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer - - //the timestamp starts at byte 40 of the received packet and is four bytes, - // or two words, long. First, esxtract the two words: - - unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); - unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); - // combine the four bytes (two words) into a long integer - // this is NTP time (seconds since Jan 1 1900): - unsigned long secsSince1900 = highWord << 16 | lowWord; - Serial.print("Seconds since Jan 1 1900 = " ); - Serial.println(secsSince1900); - - // now convert NTP time into everyday time: - Serial.print("Unix time = "); - // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: - const unsigned long seventyYears = 2208988800UL; - // subtract seventy years: - unsigned long epoch = secsSince1900 - seventyYears; - // print Unix time: - Serial.println(epoch); - - - // print the hour, minute and second: - Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) - Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) - Serial.print(':'); - if ( ((epoch % 3600) / 60) < 10 ) { - // In the first 10 minutes of each hour, we'll want a leading '0' - Serial.print('0'); - } - Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) - Serial.print(':'); - if ( (epoch % 60) < 10 ) { - // In the first 10 seconds of each minute, we'll want a leading '0' - Serial.print('0'); - } - Serial.println(epoch % 60); // print the second - } -} \ No newline at end of file From 85d7f2a549890bcf2c06cd0cd2bf7a38fc3fc8b9 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Mon, 27 Aug 2018 12:17:37 -0500 Subject: [PATCH 086/146] esp32 fix event cb to std::bind, adds async preload esp32 does not have scan cb, must use event system and oncomplete to get scan count --- WiFiManager.cpp | 32 ++++++++++++++++++-------------- WiFiManager.h | 2 +- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index a2fcde3..4d4687a 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -971,8 +971,8 @@ String WiFiManager::getMenuOut(){ // } void WiFiManager::WiFi_scanComplete(int networksFound){ - DEBUG_WM(DEBUG_VERBOSE,F("ASYNC WiFi Scan done")); _numNetworks = networksFound; + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC completed, found:"),_numNetworks); _lastscan = millis(); } @@ -994,14 +994,14 @@ bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ int8_t res; unsigned int _scanstart = millis(); if(async){ + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); #ifdef ESP8266 using namespace std::placeholders; // for `_1` WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); - return false; #else - res = WiFi.scanNetworks(); + res = WiFi.scanNetworks(true); #endif + return false; } else{ res = WiFi.scanNetworks(); @@ -1017,9 +1017,9 @@ bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ } else if(res >=0 ) _numNetworks = res; _lastscan = millis(); - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan done"), "in "+(String)(_lastscan - _scanstart)+"ms"); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan done"), "in "+(String)(_lastscan - _scanstart)+" ms"); return true; - } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+"ms ago"); + } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+" ms ago"); return false; } @@ -2536,19 +2536,22 @@ String WiFiManager::WiFi_SSID(){ #ifdef ESP32 void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ - // WiFiManager _WiFiManager; - // Serial.print("WM: EVENT: ");Serial.println(event); + DEBUG_WM(DEBUG_VERBOSE,"[EVENT]",event); if(event == SYSTEM_EVENT_STA_DISCONNECTED){ - // Serial.print("WM: EVENT: WIFI_REASON: ");Serial.println(info.disconnected.reason); + DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON:",info.disconnected.reason); if(info.disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.disconnected.reason == WIFI_REASON_AUTH_FAIL){ _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail } else _lastconxresulttmp = WiFi.status(); - // if(info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) Serial.println("*WM: EVENT: WIFI_REASON: NO_AP_FOUND"); - // Serial.println("*WM: Event: SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); + if(info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON: NO_AP_FOUND"); #ifdef esp32autoreconnect + DEBUG_WM(DEBUG_VERBOSE,"[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); WiFi.reconnect(); #endif } + else if(event == SYSTEM_EVENT_SCAN_DONE){ + uint16_t scans = WiFi.scanComplete(); + WiFi_scanComplete(scans); + } } #endif @@ -2556,9 +2559,10 @@ void WiFiManager::WiFi_autoReconnect(){ #ifdef ESP8266 WiFi.setAutoReconnect(_wifiAutoReconnect); #elif defined(ESP32) - if(_wifiAutoReconnect){ + // if(_wifiAutoReconnect){ DEBUG_WM(DEBUG_VERBOSE,"ESP32 event handler enabled"); - WiFi.onEvent(WiFiEvent); - } + using namespace std::placeholders; + WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); + // } #endif } diff --git a/WiFiManager.h b/WiFiManager.h index 0d243a3..c70ae27 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -390,7 +390,7 @@ class WiFiManager bool WiFiSetCountry(); #ifdef ESP32 - static void WiFiEvent(WiFiEvent_t event, system_event_info_t info); + void WiFiEvent(WiFiEvent_t event, system_event_info_t info); #endif // output helpers From c78b76ba2e3d00328becc0db185a47838f59231a Mon Sep 17 00:00:00 2001 From: Shawn A Date: Mon, 27 Aug 2018 12:30:28 -0500 Subject: [PATCH 087/146] scan timing debugging --- WiFiManager.cpp | 9 +++++---- WiFiManager.h | 3 ++- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 4d4687a..3c80bc2 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -971,9 +971,10 @@ String WiFiManager::getMenuOut(){ // } void WiFiManager::WiFi_scanComplete(int networksFound){ - _numNetworks = networksFound; - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC completed, found:"),_numNetworks); _lastscan = millis(); + _numNetworks = networksFound; + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan found:"),_numNetworks); } bool WiFiManager::WiFi_scanNetworks(){ @@ -992,7 +993,7 @@ bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ // DEBUG_WM(DEBUG_DEV,"scanNetworks force:",force == true); if(force || _numNetworks == 0 || (millis()-_lastscan > 60000)){ int8_t res; - unsigned int _scanstart = millis(); + _startscan = millis(); if(async){ DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); #ifdef ESP8266 @@ -1017,7 +1018,7 @@ bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ } else if(res >=0 ) _numNetworks = res; _lastscan = millis(); - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan done"), "in "+(String)(_lastscan - _scanstart)+" ms"); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); return true; } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+" ms ago"); return false; diff --git a/WiFiManager.h b/WiFiManager.h index c70ae27..787c987 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -281,7 +281,8 @@ class WiFiManager String _wifissidprefix = FPSTR(S_ssidpre); // auto apname prefix prefix+chipid uint8_t _lastconxresult = WL_IDLE_STATUS; int _numNetworks = 0; - unsigned long _lastscan = 0; // ms + unsigned long _lastscan = 0; // ms for timing wifi scans + unsigned long _startscan = 0; // ms for timing wifi scans int _cpclosedelay = 2000; // delay before wifisave, prevents captive portal from closing to fast. bool _cleanConnect = true; // disconnect before connect in connectwifi, increases stability on connects From 247aecb2fcc60882adfa3f3f6a3b417aa9ade0fc Mon Sep 17 00:00:00 2001 From: Shawn A Date: Tue, 28 Aug 2018 09:00:24 -0500 Subject: [PATCH 088/146] update requirements esp8266 2.4.0 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 55469f8..1f355a2 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are You can either install through the Arduino Library Manager or checkout the latest changes or a release from github #### Install through Library Manager -__Currently version 0.8+ works with release 2.0.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ +__Currently version 0.8+ works with release 2.4.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ - in Arduino IDE got to Sketch/Include Library/Manage Libraries ![Manage Libraries](http://i.imgur.com/9BkEBkR.png) @@ -87,7 +87,7 @@ __Currently version 0.8+ works with release 2.0.0 or newer of the [ESP8266 core - click Install and start [using it](#using) #### Checkout from github -__Github version works with release 2.0.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ +__Github version works with release 2.4.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ - Checkout library to your Arduino libraries folder ### Using From 805072c4c4d354e00c8bf15abbfe33f26b198a2b Mon Sep 17 00:00:00 2001 From: Shawn A Date: Wed, 29 Aug 2018 10:37:28 -0500 Subject: [PATCH 089/146] adds checkboxes --- .github/ISSUE_TEMPLATE.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 6fd55a7..499d50e 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -19,13 +19,24 @@ https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/debugging.rst ### Basic Infos #### Hardware -WiFimanager Branch/Release: Development +WiFimanager Branch/Release: +- [ ] Master +- [ ] Development -Esp8266/Esp32: +Esp8266/Esp32: +- [ ] ESP8266 +- [ ] ESP32 Hardware: ESP-12e, esp01, esp25 +- [ ] ESP01 +- [ ] ESP12 E/F/S (nodemcu, wemos, feather) +- [ ] Other -Core Version: 2.4.0, staging + +ESP Core Version: 2.4.0, staging +- [ ] 2.3.0 +- [ ] 2.4.0 +- [ ] staging (master/dev) ### Description From b2f6ff4a1fab22fe1800eea24a83d1d2c7add760 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Wed, 29 Aug 2018 10:39:28 -0500 Subject: [PATCH 090/146] formatting --- .github/ISSUE_TEMPLATE.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 499d50e..b209e5e 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,7 +1,5 @@ ## PLEASE TRY DEVELOPMENT BRANCH before submitting bugs on release or master, in case they were already fixed. ## -## POST SERIAL OUTPUT ! -## POST SERIAL OUTPUT ! ## POST SERIAL OUTPUT ! Issues without basic info will be ignored or closed! @@ -19,21 +17,21 @@ https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/debugging.rst ### Basic Infos #### Hardware -WiFimanager Branch/Release: +**WiFimanager Branch/Release:** - [ ] Master - [ ] Development -Esp8266/Esp32: +**Esp8266/Esp32:** - [ ] ESP8266 - [ ] ESP32 -Hardware: ESP-12e, esp01, esp25 +**Hardware: ESP-12e, esp01, esp25** - [ ] ESP01 - [ ] ESP12 E/F/S (nodemcu, wemos, feather) - [ ] Other -ESP Core Version: 2.4.0, staging +**ESP Core Version: 2.4.0, staging** - [ ] 2.3.0 - [ ] 2.4.0 - [ ] staging (master/dev) From 8b579bb8a7e05b0e9f36b05525724132ec96e970 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Wed, 29 Aug 2018 11:22:05 -0500 Subject: [PATCH 091/146] debug --- WiFiManager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 3c80bc2..be2bcaa 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -973,8 +973,8 @@ String WiFiManager::getMenuOut(){ void WiFiManager::WiFi_scanComplete(int networksFound){ _lastscan = millis(); _numNetworks = networksFound; - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan found:"),_numNetworks); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC completed"), "in "+(String)(_lastscan - _startscan)+" ms"); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC found:"),_numNetworks); } bool WiFiManager::WiFi_scanNetworks(){ From c1f018ca7c548bbf634630e5bc575a9f4edff099 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 3 Sep 2018 08:49:13 -0500 Subject: [PATCH 092/146] tentative fix for #720 --- WiFiManager.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index be2bcaa..30bda4c 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -272,7 +272,15 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { // 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 - if (WiFi.status() == WL_CONNECTED || connectWifi("", "") == WL_CONNECTED) { + // @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()); From b17c328f0fc06e8c4fa415aa0218de9aa6890668 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 3 Sep 2018 17:19:25 -0500 Subject: [PATCH 093/146] more debugging --- WiFiManager.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 30bda4c..8660c43 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -771,6 +771,8 @@ bool WiFiManager::setSTAConfig(){ 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; } From 42241d6e363a5e76faf5afb66e7bc815d8f9f99d Mon Sep 17 00:00:00 2001 From: Shawn A Date: Tue, 4 Sep 2018 08:13:30 -0500 Subject: [PATCH 094/146] fix nvs erase log --- WiFiManager.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index be2bcaa..663fc0d 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1807,13 +1807,14 @@ bool WiFiManager::erase(bool opt){ if(opt){ DEBUG_WM("Erasing NVS"); int err; + esp_err_t err; err = nvs_flash_init(); - DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_init: ",err==ESP_OK ? (String)err : "Success"); + DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_init: ",err!=ESP_OK ? (String)err : "Success"); err = nvs_flash_erase(); - DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_erase: ", err==ESP_OK ? (String)err : "Success"); + DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_erase: ", err!=ESP_OK ? (String)err : "Success"); return err == ESP_OK; } - #else + #else (void)opt; #endif From 3a0723cf667c9f7037db9d57237768fb43e94c20 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Tue, 4 Sep 2018 16:36:47 -0500 Subject: [PATCH 095/146] skip connect if wifi empty --- WiFiManager.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 6449371..c38ab2f 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -574,11 +574,11 @@ uint8_t WiFiManager::processConfigPortal(){ DEBUG_WM(DEBUG_VERBOSE,F("process connect")); if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast. - // @todo skip wifi if no ssid - // if(_ssid == ""){ - // DEBUG_WM(DEBUG_VERBOSE,F("No ssid, skipping wifi")); - // } - // else{ + // 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) { From 7ab5f6d5b2b39a3e3ad2dd42377fc307d8c58620 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Tue, 4 Sep 2018 16:36:58 -0500 Subject: [PATCH 096/146] clear wifi strings --- WiFiManager.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index c38ab2f..7080e58 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -606,6 +606,9 @@ uint8_t WiFiManager::processConfigPortal(){ 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); From 43051f9f51fa51a58bb2d993ce5e284f77230414 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Tue, 4 Sep 2018 16:37:14 -0500 Subject: [PATCH 097/146] fix --- WiFiManager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 7080e58..634cd7b 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -593,8 +593,8 @@ uint8_t WiFiManager::processConfigPortal(){ 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 From 338544bc6a6d0af4fff7407797d09a4bdeef492d Mon Sep 17 00:00:00 2001 From: Shawn A Date: Tue, 4 Sep 2018 16:39:00 -0500 Subject: [PATCH 098/146] do savecallback on parmsave fo rnow #714 --- WiFiManager.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 634cd7b..a6092ff 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1307,6 +1307,11 @@ void WiFiManager::handleParamSave() { handleRequest(); doParamSave(); + // @todo use new callback for paramsaves + if ( _savecallback != NULL) { + _savecallback(); + } + String page = getHTTPHead(FPSTR(S_titleparamsaved)); // @token titleparamsaved page += FPSTR(HTTP_PARAMSAVED); page += FPSTR(HTTP_END); From 8871bdd311f1598f1201db7f4301fc3c4eb495c3 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Tue, 4 Sep 2018 16:39:16 -0500 Subject: [PATCH 099/146] logging --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index a6092ff..ebd5c14 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1297,7 +1297,7 @@ void WiFiManager::handleWifiSave() { DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); - connect = true; //signal ready to connect/reset + connect = true; //signal ready to connect/reset process in processConfigPortal } void WiFiManager::handleParamSave() { From 5827c2f8cb170c82ee5321d0e70bc8b8c77c19fe Mon Sep 17 00:00:00 2001 From: Rodrigo Jose Carbajales Date: Thu, 6 Sep 2018 12:11:38 +0200 Subject: [PATCH 100/146] Swapping enableAP and softAPConfig Swapping enableAP and softAPConfig for static IP STA --- WiFiManager.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index ebd5c14..a5c3f52 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -317,14 +317,6 @@ bool WiFiManager::startAP(){ _apcallback(this); } - // 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!"); - } - } - #ifdef ESP8266 // @bug workaround for bug #4372 https://github.com/esp8266/Arduino/issues/4372 if(!WiFi.enableAP(true)) { @@ -334,6 +326,15 @@ bool WiFiManager::startAP(){ 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!"); + } + } + + if(_channelSync){ DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",WiFi.channel()); } From 0d8b96ebf382e373f688e616b1a6da80b9769999 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 6 Sep 2018 20:45:38 -0500 Subject: [PATCH 101/146] update docblock to reflect setConfigPortalBlocking ignored configportaltimeout --- WiFiManager.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/WiFiManager.h b/WiFiManager.h index 787c987..4a9cf45 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -162,7 +162,7 @@ class WiFiManager //sets timeout before AP,webserver loop ends and exits even if there has been no setup. //useful for devices that failed to connect at some point and got stuck in a webserver loop - //in seconds setConfigPortalTimeout is a new name for setTimeout + //in seconds setConfigPortalTimeout is a new name for setTimeout, ! not used if setConfigPortalBlocking void setConfigPortalTimeout(unsigned long seconds); void setTimeout(unsigned long seconds); // @deprecated, alias @@ -188,7 +188,9 @@ class WiFiManager bool addParameter(WiFiManagerParameter *p); //if this is set, it will exit after config, even if connection is unsuccessful. void setBreakAfterConfig(boolean shouldBreak); - //if this is set, portal will be blocking and wait until save or exit, is false user must manually `process()` to handle config portal + // if this is set, portal will be blocking and wait until save or exit, + // is false user must manually `process()` to handle config portal, + // setConfigPortalTimeout is ignored in this mode, user is responsible for closing configportal void setConfigPortalBlocking(boolean shouldBlock); //if this is set, customise style void setCustomHeadElement(const char* element); From 04552e40d842a564fadfbf25fe108f1b054f7274 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Fri, 7 Sep 2018 14:51:27 -0500 Subject: [PATCH 102/146] some testing --- .../OnDemandConfigPortal.ino | 63 +++++++++++++++---- 1 file changed, 52 insertions(+), 11 deletions(-) diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index e72c921..b7f495f 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -11,17 +11,50 @@ WiFiManager wm; char ssid[] = "*************"; // your network SSID (name) char pass[] = "********"; // your network password +void debugchipid(){ + // WiFi.mode(WIFI_STA); + // WiFi.printDiag(Serial); + // Serial.println(modes[WiFi.getMode()]); + + // ESP.eraseConfig(); + // wm.resetSettings(); + // wm.erase(true); + WiFi.mode(WIFI_AP); + // WiFi.softAP(); + WiFi.enableAP(true); + delay(500); + // esp_wifi_start(); + delay(1000); + WiFi.printDiag(Serial); + delay(60000); + ESP.restart(); + + // AP esp_267751 + // 507726A4AE30 + // ESP32 Chip ID = 507726A4AE30 +} + +void saveCallback(){ + Serial.println("saveCallback fired"); +} + + +//gets called when WiFiManager enters configuration mode +void configModeCallback (WiFiManager *myWiFiManager) { + Serial.println("configModeCallback fired"); + // myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // Serial.println(WiFi.softAPIP()); + //if you used auto generated SSID, print it + // Serial.println(myWiFiManager->getConfigPortalSSID()); +} void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.setDebugOutput(true); - delay(3000); + // delay(3000); Serial.println("\n Starting"); - // WiFi.mode(WIFI_STA); - // WiFi.printDiag(Serial); - // Serial.println(modes[WiFi.getMode()]); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around // WiFiManager wm; @@ -31,14 +64,16 @@ void setup() { //Local intialization. Once its business is done, there is no need to keep it around //reset settings - for testing // wm.resetSettings(); - // + // wm.erase(); + wm.setClass("invert"); + wm.setAPCallback(configModeCallback); //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds // wm.setConfigPortalTimeout(600); - wm.setConnectTimeout(10); + // wm.setConnectTimeout(5); // wm.setShowStaticFields(true); // uint8_t menu[] = {wm.MENU_WIFI,wm.MENU_INFO,wm.MENU_PARAM,wm.MENU_CLOSE}; @@ -57,6 +92,9 @@ void setup() { WiFiManagerParameter custom_token("api_token", "api token", "", 16); WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); + // callbacks + wm.setSaveConfigCallback(saveCallback); + //add all your parameters here wm.addParameter(&custom_html); wm.addParameter(&custom_mqtt_server); @@ -83,11 +121,15 @@ void setup() { std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; wm.setMenu(menu); - //set static ip + // set static sta ip // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // wm.setShowStaticFields(false); // wm.setShowDnsFields(false); + // set static ip + // wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // wm.setAPStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // WiFi.mode(WIFI_STA); // const wifi_country_t COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; // const wifi_country_t COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; @@ -116,18 +158,17 @@ void setup() { pinMode(TRIGGER_PIN, INPUT); } - void loop() { // is configuration portal requested? if ( digitalRead(TRIGGER_PIN) == LOW ) { + Serial.println("BUTTON PRESSED"); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around //reset settings - for testing //wm.resetSettings(); //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds + //useful to make it all retry or go to sleep, in seconds wm.setConfigPortalTimeout(120); //it starts an access point with the specified name @@ -150,5 +191,5 @@ void loop() { } // put your main code here, to run repeatedly: - delay(10000); + delay(5000); } From 97e7d30c660cee98a616bcfe20e29042b5513518 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Fri, 7 Sep 2018 14:53:08 -0500 Subject: [PATCH 103/146] esp8266 2.3.0 compatability restored #576 asyncscannetworks not available in esp8266 2.3.0, adjusted server on to take cstr for backwards compatability --- WiFiManager.cpp | 28 ++++++++++++++++------------ WiFiManager.h | 6 ++++++ 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index ebd5c14..c7303e3 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -445,18 +445,18 @@ void WiFiManager::setupConfigPortal() { dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); /* Setup httpd callbacks, web pages: root, wifi config pages, SO captive portal detectors and not found. */ - server->on((String)FPSTR(R_root), std::bind(&WiFiManager::handleRoot, this)); - server->on((String)FPSTR(R_wifi), std::bind(&WiFiManager::handleWifi, this, true)); - server->on((String)FPSTR(R_wifinoscan), std::bind(&WiFiManager::handleWifi, this, false)); - server->on((String)FPSTR(R_wifisave), std::bind(&WiFiManager::handleWifiSave, this)); - server->on((String)FPSTR(R_info), std::bind(&WiFiManager::handleInfo, this)); - server->on((String)FPSTR(R_param), std::bind(&WiFiManager::handleParam, this)); - server->on((String)FPSTR(R_paramsave), std::bind(&WiFiManager::handleParamSave, this)); - server->on((String)FPSTR(R_restart), std::bind(&WiFiManager::handleReset, this)); - server->on((String)FPSTR(R_exit), std::bind(&WiFiManager::handleExit, this)); - server->on((String)FPSTR(R_close), std::bind(&WiFiManager::handleClose, this)); - server->on((String)FPSTR(R_erase), std::bind(&WiFiManager::handleErase, this, false)); - server->on((String)FPSTR(R_status), std::bind(&WiFiManager::handleWiFiStatus, this)); + server->on(String(FPSTR(R_wifi)).c_str(), std::bind(&WiFiManager::handleWifi, this, true)); + server->on(String(FPSTR(R_root)).c_str(), std::bind(&WiFiManager::handleRoot, this)); + 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 @@ -1010,9 +1010,13 @@ bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ if(async){ DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); #ifdef ESP8266 + #ifndef WM_NOASYNC // no async available < 2.4.0 using namespace std::placeholders; // for `_1` WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); #else + res = WiFi.scanNetworks(); + #endif + #else res = WiFi.scanNetworks(true); #endif return false; diff --git a/WiFiManager.h b/WiFiManager.h index 787c987..0619fa7 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -13,6 +13,7 @@ #ifndef WiFiManager_h #define WiFiManager_h +#include #include // #define WM_MDNS // also set MDNS with sethostname @@ -20,6 +21,11 @@ // #define WM_ERASE_NVS // esp32 erase(true) will erase NVS // #define WM_RTC // esp32 info page will include reset reasons +#ifdef ARDUINO_ESP8266_RELEASE_2_3_0 +#warning "ARDUINO_ESP8266_RELEASE_2_3_0, some WM features disabled" +#define WM_NOASYNC // esp8266 no async scan wifi +#endif + // #include "soc/efuse_reg.h" // include to add efuse chip rev to info, getChipRevision() is almost always the same though, so not sure why it matters. // #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge From c52186079a45216966f135bcf62896fc95731aa0 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Fri, 7 Sep 2018 15:43:21 -0500 Subject: [PATCH 104/146] stopconfigportal public --- WiFiManager.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/WiFiManager.h b/WiFiManager.h index 12c3a09..fa18c1c 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -145,6 +145,9 @@ class WiFiManager //manually start the config portal, autoconnect does this automatically on connect failure boolean startConfigPortal(); // auto generates apname boolean startConfigPortal(char const *apName, char const *apPassword = NULL); + + //manually stop the config portal if started manually + boolean stopConfigPortal(); //manually start the web portal, autoconnect does this automatically on connect failure void startWebPortal(); @@ -376,7 +379,6 @@ class WiFiManager boolean captivePortal(); boolean configPortalHasTimeout(); - boolean stopConfigPortal(); uint8_t processConfigPortal(); void stopCaptivePortal(); From ed80635e32728b467cddaf565bf6d8313fe7500b Mon Sep 17 00:00:00 2001 From: Shawn A Date: Fri, 7 Sep 2018 15:43:43 -0500 Subject: [PATCH 105/146] non blocking examples --- WiFiManager.cpp | 2 +- .../OnDemandConfigPortal.ino | 3 +- .../AutoConnectNonBlocking.ino | 0 .../onDemandNonBlocking.ino | 61 +++++++++++++++++++ .../OnDemandConfigPortal.ino | 3 +- .../OnDemandWebPortal/OnDemandWebPortal.ino | 43 ------------- 6 files changed, 65 insertions(+), 47 deletions(-) rename examples/{AutoConnect => NonBlocking}/AutoConnectNonBlocking/AutoConnectNonBlocking.ino (100%) create mode 100644 examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino delete mode 100644 examples/OnDemandWebPortal/OnDemandWebPortal.ino diff --git a/WiFiManager.cpp b/WiFiManager.cpp index c7303e3..e92c1ee 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -445,8 +445,8 @@ void WiFiManager::setupConfigPortal() { dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); /* Setup httpd callbacks, web pages: root, wifi config pages, SO captive portal detectors and not found. */ - server->on(String(FPSTR(R_wifi)).c_str(), std::bind(&WiFiManager::handleWifi, this, true)); 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)); diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index b7f495f..d209f31 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -54,7 +54,8 @@ void setup() { Serial.setDebugOutput(true); // delay(3000); Serial.println("\n Starting"); - + WiFi.setSleepMode(WIFI_NONE_SLEEP); + //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around // WiFiManager wm; diff --git a/examples/AutoConnect/AutoConnectNonBlocking/AutoConnectNonBlocking.ino b/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino similarity index 100% rename from examples/AutoConnect/AutoConnectNonBlocking/AutoConnectNonBlocking.ino rename to examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino diff --git a/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino new file mode 100644 index 0000000..c250038 --- /dev/null +++ b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino @@ -0,0 +1,61 @@ +/** + * OnDemandWebPortal.ino + * example of running the webportal or configportal manually and no blocking + * trigger pin will start a webportal for 120 seconds then turn it off. + * startCP = true will start the configportal AP and webportal + */ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +WiFiManager wm; + +unsigned int timeout = 120; // seconds to run for +unsigned int startTime = millis(); +bool portalRunning = false; +bool startCP = false; // start AP and webserver if true, else start only webserver + +void setup() { + // put your setup code here, to run once + Serial.begin(115200); + Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); +} + +void loop() { + doWiFiManager(); + // put your main code here, to run repeatedly: +} + +void doWiFiManager(){ + // is auto timeout portal running + if(portalRunning){ + wm.process(); + if((millis()-startTime) > (timeout*1000)){ + Serial.println("portaltimeout"); + portalRunning = false; + if(startCP){ + wm.stopConfigPortal(); + } + else{ + wm.stopWebPortal(); + } + } + } + + // is configuration portal requested? + if(digitalRead(TRIGGER_PIN) == LOW && (!portalRunning)) { + Serial.println("Button Pressed, Starting Portal"); + if(startCP){ + wm.startConfigPortal(); + } + else{ + wm.startWebPortal(); + } + portalRunning = true; + startTime = millis(); + } +} + + diff --git a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino index 357276b..e9252c3 100644 --- a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -9,8 +9,7 @@ // select which pin will trigger the configuration portal when set to LOW #define TRIGGER_PIN 0 -int timeout = 120; // seconds to run for -bool webportalrunning = false; +int timeout = 120; // seconds to run for void setup() { // put your setup code here, to run once: diff --git a/examples/OnDemandWebPortal/OnDemandWebPortal.ino b/examples/OnDemandWebPortal/OnDemandWebPortal.ino deleted file mode 100644 index 07f61e9..0000000 --- a/examples/OnDemandWebPortal/OnDemandWebPortal.ino +++ /dev/null @@ -1,43 +0,0 @@ -/** - * OnDemandWebPortal.ino - * example of running the webportal manually, independantly from the captiveportal - * trigger pin will start a webportal for 120 seconds then turn it off. - * - */ -#include // https://github.com/tzapu/WiFiManager - -// select which pin will trigger the configuration portal when set to LOW -#define TRIGGER_PIN 0 - -WiFiManager wm; - -int timeout = 120; // seconds to run for -bool webportalrunning = false; -int start = millis(); - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println("\n Starting"); - pinMode(TRIGGER_PIN, INPUT_PULLUP); -} - - -void loop() { - if(webportalrunning){ - wm.process(); - if(millis()-start > timeout*1000){ - Serial.println("webportaltimeout"); - webportalrunning = false; - wm.stopWebPortal(); // auto off - } - } - // is configuration portal requested? - if ( digitalRead(TRIGGER_PIN) == LOW && !webportalrunning) { - wm.startWebPortal(); - // wm.startWebPortal(); - webportalrunning = true; - start = millis(); - } - // put your main code here, to run repeatedly: -} From 2610dcb2c5d7dd87ad431106d560476d5968752f Mon Sep 17 00:00:00 2001 From: Shawn A Date: Fri, 7 Sep 2018 15:52:52 -0500 Subject: [PATCH 106/146] change simple to basic clean up --- examples/Basic/Basic.ino | 37 +++++++++++++++++++++++++++++++++++++ examples/Simple/Simple.ino | 31 ------------------------------- 2 files changed, 37 insertions(+), 31 deletions(-) create mode 100644 examples/Basic/Basic.ino delete mode 100644 examples/Simple/Simple.ino diff --git a/examples/Basic/Basic.ino b/examples/Basic/Basic.ino new file mode 100644 index 0000000..26ec6d4 --- /dev/null +++ b/examples/Basic/Basic.ino @@ -0,0 +1,37 @@ +#include // https://github.com/tzapu/WiFiManager + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + + // Automatically connect using saved credentials, + // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"), + // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect()) + // then goes into a blocking loop awaiting configuration and will return success result + + bool res; + // res = wm.autoConnect(); // auto generated AP name from chipid + // res = wm.autoConnect("AutoConnectAP"); // anonymous ap + res = wm.autoConnect("AutoConnectAP","password"); // password protected ap + + if(!res) { + Serial.println("Failed to connect"); + // ESP.restart(); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + +} + +void loop() { + // put your main code here, to run repeatedly: + +} diff --git a/examples/Simple/Simple.ino b/examples/Simple/Simple.ino deleted file mode 100644 index e244fde..0000000 --- a/examples/Simple/Simple.ino +++ /dev/null @@ -1,31 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - - //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wm; - - //reset settings - wipe credentials for testing - //wm.resetSettings(); - - //set custom ip for portal - //wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - - //automatically connect using saved credentials if they exist - //If connection fails it starts an access point with the specified name - //here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous - //and goes into a blocking loop awaiting configuration - wm.autoConnect("AutoConnectAP"); - //or use this for auto generated name ESP + ChipID - //wm.autoConnect(); - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); -} - -void loop() { - // put your main code here, to run repeatedly: - -} From 1e10ffa49a0b3009eb76fac7c49fc7fb2c67f2aa Mon Sep 17 00:00:00 2001 From: Shawn A Date: Fri, 7 Sep 2018 16:16:44 -0500 Subject: [PATCH 107/146] reworkgin examples --- examples/Advanced/Advanced.ino | 44 +++++++++------- .../onDemandNonBlocking.ino | 9 ++-- .../OnDemandConfigPortal.ino | 0 .../OnDemandWebPortal/onDemandWebPortal.ino | 50 +++++++++++++++++++ 4 files changed, 80 insertions(+), 23 deletions(-) rename examples/{ => OnDemand}/OnDemandConfigPortal/OnDemandConfigPortal.ino (100%) create mode 100644 examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino diff --git a/examples/Advanced/Advanced.ino b/examples/Advanced/Advanced.ino index 7bc3795..700ab6c 100644 --- a/examples/Advanced/Advanced.ino +++ b/examples/Advanced/Advanced.ino @@ -58,6 +58,7 @@ void setup() { if(!res) { Serial.println("Failed to connect or hit timeout"); + // ESP.restart(); } else { //if you get here you have connected to the WiFi @@ -65,33 +66,38 @@ void setup() { } } -void loop() { +void checkButton(){ // check for button press if ( digitalRead(TRIGGER_PIN) == LOW ) { - // poor mans debounce, not recommended for production code + // poor mans debounce/press-hold, not recommended for production code delay(50); if( digitalRead(TRIGGER_PIN) == LOW ){ - delay(3000); // reset timer - if( digitalRead(TRIGGER_PIN) == LOW ){ - Serial.println("Erasing Config"); // holding button 3000 ms, reset settings - wm.resetSettings(); - ESP.restart(); - } - - Serial.println("Starting config portal"); - wm.setConfigPortalTimeout(120); - - if (!wm.startConfigPortal("OnDemandAP")) { - Serial.println("failed to connect or hit timeout"); - delay(3000); - } else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); + delay(3000); // reset delay hold + if( digitalRead(TRIGGER_PIN) == LOW ){ + Serial.println("Erasing Config"); + wm.resetSettings(); + ESP.restart(); + } + + // start portal w delay + Serial.println("Starting config portal"); + wm.setConfigPortalTimeout(120); + + if (!wm.startConfigPortal("OnDemandAP")) { + Serial.println("failed to connect or hit timeout"); + delay(3000); + // ESP.restart(); + } else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } } } - } +} +void loop() { + checkButton(); // put your main code here, to run repeatedly: } diff --git a/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino index c250038..9d283ec 100644 --- a/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino +++ b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino @@ -1,8 +1,8 @@ /** - * OnDemandWebPortal.ino - * example of running the webportal or configportal manually and no blocking + * OnDemandNonBlocking.ino + * example of running the webportal or configportal manually and non blocking * trigger pin will start a webportal for 120 seconds then turn it off. - * startCP = true will start the configportal AP and webportal + * startCP = true will start both the configportal AP and webportal */ #include // https://github.com/tzapu/WiFiManager @@ -46,11 +46,12 @@ void doWiFiManager(){ // is configuration portal requested? if(digitalRead(TRIGGER_PIN) == LOW && (!portalRunning)) { - Serial.println("Button Pressed, Starting Portal"); if(startCP){ + Serial.println("Button Pressed, Starting Config Portal"); wm.startConfigPortal(); } else{ + Serial.println("Button Pressed, Starting Web Portal"); wm.startWebPortal(); } portalRunning = true; diff --git a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino similarity index 100% rename from examples/OnDemandConfigPortal/OnDemandConfigPortal.ino rename to examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino diff --git a/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino b/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino new file mode 100644 index 0000000..5850e40 --- /dev/null +++ b/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino @@ -0,0 +1,50 @@ +/** + * OnDemandWebPortal.ino + * example of running the webportal (always NON blocking) + */ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +WiFiManager wm; + +bool portalRunning = false; + +void setup() { + // put your setup code here, to run once + Serial.begin(115200); + Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); +} + +void loop() { + checkButton(); + // put your main code here, to run repeatedly: +} + +void checkButton(){ + // is auto timeout portal running + if(portalRunning){ + wm.process(); + } + + // is configuration portal requested? + if(digitalRead(TRIGGER_PIN) == LOW) { + delay(50) + if(digitalRead(TRIGGER_PIN) == LOW) { + if(!portalRunning){ + Serial.println("Button Pressed, Starting Portal"); + wm.startWebPortal(); + portalRunning = true; + } + else{ + Serial.println("Button Pressed, Stopping Portal"); + wm.startWebPortal(); + portalRunning = false; + } + } + } +} + + From 393e7e45dffc4b07e0aff74fcb75c17ce4f4cb98 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Wed, 12 Sep 2018 09:56:20 -0500 Subject: [PATCH 108/146] bug fixes #726 --- WiFiManager.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/WiFiManager.h b/WiFiManager.h index fa18c1c..262189f 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -13,7 +13,10 @@ #ifndef WiFiManager_h #define WiFiManager_h +#ifdef ESP8266 #include +#endif + #include // #define WM_MDNS // also set MDNS with sethostname From 9ce498c5b6ef82808fa42189ffd000604fd30fb6 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Wed, 12 Sep 2018 10:55:04 -0500 Subject: [PATCH 109/146] remove sleep mode --- examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index d209f31..2677711 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -54,7 +54,7 @@ void setup() { Serial.setDebugOutput(true); // delay(3000); Serial.println("\n Starting"); - WiFi.setSleepMode(WIFI_NONE_SLEEP); + // WiFi.setSleepMode(WIFI_NONE_SLEEP); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around From 4f0a87a0a5ae3b4e738662eaf7c994fe68cb5f59 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Wed, 12 Sep 2018 13:19:53 -0500 Subject: [PATCH 110/146] adds esp32 core temp, not enabled the core temp sensors are not calibrated in production atm, they are large offsets form chip to chip and are useful for relative temp swings only. Until the IDF comes up with a new temp sense, this is commented out. --- WiFiManager.cpp | 9 +++++++++ strings_en.h | 1 + 2 files changed, 10 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index e92c1ee..2cb5dd4 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1408,6 +1408,7 @@ void WiFiManager::handleInfo() { F("cpufreq"), F("freeheap"), F("lastreset"), + // F("temp"), F("wifihead"), F("apip"), F("apmac"), @@ -1617,6 +1618,14 @@ String WiFiManager::getInfoData(String id){ p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); } #endif + #ifdef ESP32 + else if(id==F("temp")){ + // temperature is not calibrated, varying large offsets are present, use for relative temp changes only + p = FPSTR(HTTP_INFO_temp); + p.replace(FPSTR(T_1),(String)temperatureRead()); + p.replace(FPSTR(T_2),(String)((temperatureRead()+32)*1.8)); + } + #endif return p; } diff --git a/strings_en.h b/strings_en.h index edbc84e..21f3f2b 100644 --- a/strings_en.h +++ b/strings_en.h @@ -166,6 +166,7 @@ const char HTTP_INFO_host[] PROGMEM = "
Hostname
{1}
"; const char HTTP_INFO_stamac[] PROGMEM = "
Station MAC
{1}
"; const char HTTP_INFO_conx[] PROGMEM = "
Connected
{1}
"; const char HTTP_INFO_autoconx[] PROGMEM = "
Autoconnect
{1}
"; +const char HTTP_INFO_temp[] PROGMEM = "
Temperature
{1} C° / {2} F°
"; // Strings const char S_y[] PROGMEM = "Yes"; From d9c27b98d41069150b45ddc9c3d8d8f39eee8a18 Mon Sep 17 00:00:00 2001 From: ayeah Date: Mon, 17 Sep 2018 01:10:37 +0700 Subject: [PATCH 111/146] add listener setPreSaveConfigCallback this listener required for action before save process behind wifi or params. --- WiFiManager.cpp | 2669 ++++++++++++++++++++++++++++------------------- WiFiManager.h | 3 + 2 files changed, 1571 insertions(+), 1101 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index e92c1ee..9fd7539 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -22,84 +22,103 @@ uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS; * -------------------------------------------------------------------------------- **/ -WiFiManagerParameter::WiFiManagerParameter(const char *custom) { - _id = NULL; - _placeholder = NULL; - _length = 1; - _value = NULL; +WiFiManagerParameter::WiFiManagerParameter(const char *custom) +{ + _id = NULL; + _placeholder = NULL; + _length = 1; + _value = NULL; _labelPlacement = WFM_LABEL_BEFORE; - _customHTML = custom; + _customHTML = custom; } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder) { +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder) +{ init(id, placeholder, "", 0, "", WFM_LABEL_BEFORE); } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length) { +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length) +{ init(id, placeholder, defaultValue, length, "", WFM_LABEL_BEFORE); } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom) { +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom) +{ init(id, placeholder, defaultValue, length, custom, WFM_LABEL_BEFORE); } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) { +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) +{ init(id, placeholder, defaultValue, length, custom, labelPlacement); } -void WiFiManagerParameter::init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) { - _id = id; - _placeholder = placeholder; +void WiFiManagerParameter::init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) +{ + _id = id; + _placeholder = placeholder; _labelPlacement = labelPlacement; - _customHTML = custom; - setValue(defaultValue,length); + _customHTML = custom; + setValue(defaultValue, length); } -WiFiManagerParameter::~WiFiManagerParameter() { - if (_value != NULL) { +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 + _length = 0; // setting length 0, ideally the entire parameter should be removed, or added to wifimanager scope so it follows } -void WiFiManagerParameter::setValue(const char *defaultValue, int length) { - if(!_id){ +void WiFiManagerParameter::setValue(const char *defaultValue, int length) +{ + if (!_id) + { // Serial.println("cannot set value of this parameter"); return; } - _length = length; + _length = length; int deflength = strlen(defaultValue); // length actual - // use the defult length if it's longer, + // use the defult length if it's longer, // @todo consider it might be useful to fail, so user knows they were wrong - if(_length < length){ + if (_length < length) + { // Serial.println("defaultValue length mismatch"); _length = deflength; } _value = new char[_length + 1]; - for (int i = 0; i < _length + 1; i++) { + for (int i = 0; i < _length + 1; i++) + { _value[i] = 0; } - if (defaultValue != NULL) { + if (defaultValue != NULL) + { strncpy(_value, defaultValue, _length); _value[_length] = '\0'; // explicit null } } -const char* WiFiManagerParameter::getValue() { +const char *WiFiManagerParameter::getValue() +{ return _value; } -const char* WiFiManagerParameter::getID() { +const char *WiFiManagerParameter::getID() +{ return _id; } -const char* WiFiManagerParameter::getPlaceholder() { +const char *WiFiManagerParameter::getPlaceholder() +{ return _placeholder; } -int WiFiManagerParameter::getValueLength() { +int WiFiManagerParameter::getValueLength() +{ return _length; } -int WiFiManagerParameter::getLabelPlacement() { +int WiFiManagerParameter::getLabelPlacement() +{ return _labelPlacement; } -const char* WiFiManagerParameter::getCustomHTML() { +const char *WiFiManagerParameter::getCustomHTML() +{ return _customHTML; } @@ -108,45 +127,54 @@ const char* WiFiManagerParameter::getCustomHTML() { * @access public * @param {[type]} WiFiManagerParameter *p [description] */ -bool WiFiManager::addParameter(WiFiManagerParameter *p) { +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"); + 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*)); + 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){ + 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(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) { + if (new_params != NULL) + { _params = new_params; - } else { - DEBUG_WM(DEBUG_ERROR,"[ERROR] failed to realloc params, size not increased!"); + } + 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()); + + DEBUG_WM(DEBUG_VERBOSE, "Added Parameter:", p->getID()); return true; } @@ -157,51 +185,62 @@ bool WiFiManager::addParameter(WiFiManagerParameter *p) { **/ // constructors -WiFiManager::WiFiManager(Stream& consolePort):_debugPort(consolePort){ +WiFiManager::WiFiManager(Stream &consolePort) : _debugPort(consolePort) +{ WiFiManagerInit(); } -WiFiManager::WiFiManager():WiFiManager(Serial) { +WiFiManager::WiFiManager() : WiFiManager(Serial) +{ } -void WiFiManager::WiFiManagerInit(){ +void WiFiManager::WiFiManagerInit() +{ setMenu(_menuIdsDefault); - if(_debug && _debugLevel > DEBUG_DEV) debugPlatformInfo(); + if (_debug && _debugLevel > DEBUG_DEV) + debugPlatformInfo(); _max_params = WIFI_MANAGER_MAX_PARAMS; } // destructor -WiFiManager::~WiFiManager() { +WiFiManager::~WiFiManager() +{ _end(); // parameters // @todo belongs to wifimanagerparameter - if (_params != NULL){ - DEBUG_WM(DEBUG_DEV,F("freeing allocated params!")); + if (_params != NULL) + { + DEBUG_WM(DEBUG_DEV, F("freeing allocated params!")); free(_params); _params = NULL; } - DEBUG_WM(DEBUG_DEV,F("unloading")); + DEBUG_WM(DEBUG_DEV, F("unloading")); } -void WiFiManager::_begin(){ - if(_hasBegun) return; +void WiFiManager::_begin() +{ + if (_hasBegun) + return; _usermode = WiFi.getMode(); - #ifndef ESP32 +#ifndef ESP32 WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites - #endif +#endif } -void WiFiManager::_end(){ - if(_userpersistent) WiFi.persistent(true); // reenable persistent, there is no getter we rely on _userpersistent +void WiFiManager::_end() +{ + 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 = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); +boolean WiFiManager::autoConnect() +{ + String ssid = _wifissidprefix + "_" + String(WIFI_getChipId(), HEX); return autoConnect(ssid.c_str(), NULL); } @@ -212,22 +251,25 @@ boolean WiFiManager::autoConnect() { * @param {[type]} char const *apPassword [description] * @return {[type]} [description] */ -boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { +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)){ + if (!WiFi.enableSTA(true)) + { // handle failure mode Brownout detector etc. - DEBUG_WM(DEBUG_ERROR,"[FATAL] Unable to enable wifi!"); + 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 +#ifdef ESP32 + if (esp32persistent) + WiFi.persistent(false); // disable persistent for esp32 after esp_wifi_start or else saves wont work +#endif _usermode = WIFI_STA; @@ -237,67 +279,76 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { WiFi_autoReconnect(); // set hostname before stating - if((String)_hostname != ""){ - DEBUG_WM(DEBUG_VERBOSE,"Setting hostname:",_hostname); + 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")); +#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 + // 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){ + if (WiFi.status() == WL_CONNECTED) + { connected = true; DEBUG_WM(F("AutoConnect: ESP Already Connected")); setSTAConfig(); } - if(connected || connectWifi("", "") == WL_CONNECTED){ + if (connected || connectWifi("", "") == WL_CONNECTED) + { //connected DEBUG_WM(F("AutoConnect: SUCCESS")); - DEBUG_WM(F("STA IP Address:"),WiFi.localIP()); + 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 + 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) { + if (!_enableConfigPortal) + { return false; } @@ -308,71 +359,88 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { } // CONFIG PORTAL -bool WiFiManager::startAP(){ +bool WiFiManager::startAP() +{ bool ret = true; - DEBUG_WM(F("StartAP with SSID: "),_apName); + DEBUG_WM(F("StartAP with SSID: "), _apName); // do AP callback if set - if ( _apcallback != NULL) { + if (_apcallback != NULL) + { _apcallback(this); } // setup optional soft AP static ip config - if (_ap_static_ip) { + 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!"); + if (!WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn)) + { + DEBUG_WM(DEBUG_ERROR, "[ERROR] softAPConfig failed!"); } } - #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 +#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 - if(_channelSync){ - DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",WiFi.channel()); - } + if (_channelSync) + { + DEBUG_WM(DEBUG_VERBOSE, "Starting AP on channel:", WiFi.channel()); + } // start soft AP with password or anonymous - if (_apPassword != "") { - if(_channelSync){ - ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),WiFi.channel()); - } - else{ - ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str());//password option + if (_apPassword != "") + { + if (_channelSync) + { + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(), WiFi.channel()); } - } else { - DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!")); - if(_channelSync){ - ret = WiFi.softAP(_apName.c_str(),"",WiFi.channel()); - } - else{ + else + { + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str()); //password option + } + } + else + { + DEBUG_WM(DEBUG_VERBOSE, F("AP has anonymous access!")); + if (_channelSync) + { + ret = WiFi.softAP(_apName.c_str(), "", WiFi.channel()); + } + else + { ret = WiFi.softAP(_apName.c_str()); - } + } } - if(_debugLevel > DEBUG_DEV) debugSoftAPConfig(); + if (_debugLevel > DEBUG_DEV) + debugSoftAPConfig(); - if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] There was a problem starting the AP"); + 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 + 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; } @@ -382,8 +450,10 @@ bool WiFiManager::startAP(){ * @access public * @return {[type]} [description] */ -void WiFiManager::startWebPortal() { - if(configPortalActive || webPortalActive) return; +void WiFiManager::startWebPortal() +{ + if (configPortalActive || webPortalActive) + return; setupConfigPortal(); webPortalActive = true; } @@ -393,44 +463,56 @@ void WiFiManager::startWebPortal() { * @access public * @return {[type]} [description] */ -void WiFiManager::stopWebPortal() { - if(!configPortalActive && !webPortalActive) return; - DEBUG_WM(DEBUG_VERBOSE,F("Stopping Web Portal")); +void WiFiManager::stopWebPortal() +{ + if (!configPortalActive && !webPortalActive) + return; + DEBUG_WM(DEBUG_VERBOSE, F("Stopping Web Portal")); webPortalActive = false; stopConfigPortal(); } -boolean WiFiManager::configPortalHasTimeout(){ +boolean WiFiManager::configPortalHasTimeout() +{ - if(_configPortalTimeout == 0 || (_cpClientCheck && (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; + if (_configPortalTimeout == 0 || (_cpClientCheck && (WiFi_softap_num_stations() > 0))) + { + if (millis() - timer > 30000) + { + timer = millis(); + DEBUG_WM(DEBUG_VERBOSE, "NUM CLIENTS: " + (String)WiFi_softap_num_stations()); } - // 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")); - } - } - } - + _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() { +void WiFiManager::setupConfigPortal() +{ DEBUG_WM(F("Starting Web Portal")); @@ -441,32 +523,34 @@ void WiFiManager::setupConfigPortal() { /* 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()); + DEBUG_WM(DEBUG_DEV, "dns server started with ip: ", WiFi.softAPIP()); dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); /* 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_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")); + 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)); - if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan , async + 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 = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); +boolean WiFiManager::startConfigPortal() +{ + String ssid = _wifissidprefix + "_" + String(WIFI_getChipId(), HEX); return startConfigPortal(ssid.c_str(), NULL); } @@ -477,25 +561,30 @@ boolean WiFiManager::startConfigPortal() { * @param {[type]} char const *apPassword [description] * @return {[type]} [description] */ -boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { +boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) +{ _begin(); //setup AP - _apName = apName; // @todo check valid apname ? + _apName = apName; // @todo check valid apname ? _apPassword = apPassword; - - if(_apName == "") _apName = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); - if(!validApPassword()) return false; - + + if (_apName == "") + _apName = _wifissidprefix + "_" + String(WIFI_getChipId(), HEX); + 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` + 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")); + DEBUG_WM(DEBUG_VERBOSE, F("Disabling STA")); } - else { + 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); } @@ -508,26 +597,29 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo _configPortalStart = millis(); // start access point - DEBUG_WM(DEBUG_VERBOSE,F("Enabling AP")); + DEBUG_WM(DEBUG_VERBOSE, F("Enabling AP")); startAP(); WiFiSetCountry(); // init configportal - DEBUG_WM(DEBUG_DEV,F("setupConfigPortal")); + DEBUG_WM(DEBUG_DEV, F("setupConfigPortal")); setupConfigPortal(); - if(!_configPortalIsBlocking){ - DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, non blocking/processing")); + 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...")); + DEBUG_WM(DEBUG_VERBOSE, F("Config Portal Running, blocking, waiting for clients...")); // blocking loop waiting for config - while(1){ + while (1) + { // if timed out or abort, break - if(configPortalHasTimeout() || abort){ - DEBUG_WM(DEBUG_DEV,F("configportal abort")); + if (configPortalHasTimeout() || abort) + { + DEBUG_WM(DEBUG_DEV, F("configportal abort")); stopConfigPortal(); result = abort ? portalAbortResult : portalTimeoutResult; // false, false break; @@ -536,15 +628,16 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo state = processConfigPortal(); // status change, break - if(state != WL_IDLE_STATUS){ - result = (state == WL_CONNECTED); // true if connected - break; + if (state != WL_IDLE_STATUS) + { + result = (state == WL_CONNECTED); // true if connected + break; } yield(); // watchdog } - DEBUG_WM(DEBUG_NOTIFY,F("config portal exiting")); + DEBUG_WM(DEBUG_NOTIFY, F("config portal exiting")); return result; } @@ -553,70 +646,82 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo * @access public * @return {[type]} [description] */ -boolean WiFiManager::process(){ - if(webPortalActive || (configPortalActive && !_configPortalIsBlocking)){ - uint8_t state = processConfigPortal(); - return state == WL_CONNECTED; - } - return false; +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(); +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. + // 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()); + // 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) + { - if ( _savecallback != NULL) { - _savecallback(); - } - stopConfigPortal(); - 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 ( _savecallback != NULL) { + DEBUG_WM(F("Connect to new AP [SUCCESS]")); + DEBUG_WM(F("Got IP Address:")); + DEBUG_WM(WiFi.localIP()); + + if (_savecallback != NULL) + { _savecallback(); } stopConfigPortal(); - 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_CONNECTED; // CONNECT SUCCESS } + DEBUG_WM(DEBUG_ERROR, F("[ERROR] Connect to new AP Failed")); } - return WL_IDLE_STATUS; + 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 (_savecallback != NULL) + { + _savecallback(); + } + stopConfigPortal(); + 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; } /** @@ -624,8 +729,10 @@ uint8_t WiFiManager::processConfigPortal(){ * @access public * @return {[type]} [description] */ -boolean WiFiManager::stopConfigPortal(){ - if(webPortalActive) return false; +boolean WiFiManager::stopConfigPortal() +{ + if (webPortalActive) + return false; //DNS handler dnsServer->processNextRequest(); @@ -640,26 +747,29 @@ boolean WiFiManager::stopConfigPortal(){ WiFi.scanDelete(); // free wifi scan results - if(!configPortalActive) return false; + 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")); + 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")); + if (!ret) + DEBUG_WM(DEBUG_ERROR, F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); delay(1000); - DEBUG_WM(DEBUG_VERBOSE,"restoring usermode",getModeString(_usermode)); + 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){ + 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 Reconnect, was idle"); } - DEBUG_WM(DEBUG_VERBOSE,"wifi status:",getWLStatusString(WiFi.status())); - DEBUG_WM(DEBUG_VERBOSE,"wifi mode:",getModeString(WiFi.getMode())); + DEBUG_WM(DEBUG_VERBOSE, "wifi status:", getWLStatusString(WiFi.status())); + DEBUG_WM(DEBUG_VERBOSE, "wifi mode:", getModeString(WiFi.getMode())); configPortalActive = false; _end(); return ret; @@ -668,53 +778,63 @@ boolean WiFiManager::stopConfigPortal(){ // @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 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 + 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){ + 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 + { + connRes = waitForConnectResult(0); } } - else { + else + { // connect using saved ssid if there is one - if (WiFi_hasAutoConnect()) { + if (WiFi_hasAutoConnect()) + { wifiConnectDefault(); connRes = waitForConnectResult(); } - else { + else + { DEBUG_WM(F("No saved credentials, skipping wifi")); } } - DEBUG_WM(DEBUG_VERBOSE,F("Connection result:"),getWLStatusString(connRes)); + 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 == "") { + if (_tryWPS && connRes != WL_CONNECTED && pass == "") + { startWPS(); // should be connected at the end of WPS connRes = waitForConnectResult(); } #endif - if(connRes != WL_SCAN_COMPLETED){ + if (connRes != WL_SCAN_COMPLETED) + { updateConxResult(connRes); } @@ -728,14 +848,16 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { * @param String pass * @return bool success */ -bool WiFiManager::wifiConnectNew(String ssid, String pass){ +bool WiFiManager::wifiConnectNew(String ssid, String pass) +{ bool ret = false; - DEBUG_WM(F("Connecting to new AP:"),ssid); - WiFi_enableSTA(true,storeSTAmode); // storeSTAmode will also toggle STA on in default opmode (persistent) if true (default) + DEBUG_WM(F("Connecting to new AP:"), ssid); + 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"); + if (!ret) + DEBUG_WM(DEBUG_ERROR, "[ERROR] wifi begin failed"); return ret; } @@ -744,68 +866,84 @@ bool WiFiManager::wifiConnectNew(String ssid, String pass){ * @since dev * @return bool success */ -bool WiFiManager::wifiConnectDefault(){ +bool WiFiManager::wifiConnectDefault() +{ bool ret = false; - DEBUG_WM(F("Connecting to saved AP:"),WiFi_SSID()); - ret = WiFi_enableSTA(true,storeSTAmode); - if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi enableSta failed"); + DEBUG_WM(F("Connecting to saved AP:"), WiFi_SSID()); + 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"); + 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(){ +bool WiFiManager::setSTAConfig() +{ bool ret = true; - if (_sta_static_ip) { - if(_sta_static_dns) { - DEBUG_WM(DEBUG_VERBOSE,F("Custom STA IP/GW/Subnet/DNS")); + if (_sta_static_ip) + { + if (_sta_static_dns) + { + DEBUG_WM(DEBUG_VERBOSE, F("Custom STA IP/GW/Subnet/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")); + 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")); + 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){ +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)); +#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")); +uint8_t WiFiManager::waitForConnectResult() +{ + if (_connectTimeout > 0) + DEBUG_WM(DEBUG_VERBOSE, _connectTimeout, F("ms connectTimeout set")); return waitForConnectResult(_connectTimeout); } @@ -814,23 +952,27 @@ uint8_t WiFiManager::waitForConnectResult() { * @param uint16_t timeout in seconds * @return uint8_t WL Status */ -uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) { - if (timeout == 0){ +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...")); + DEBUG_WM(DEBUG_VERBOSE, timeout, F("ms timeout, waiting for connect...")); uint8_t status = WiFi.status(); - - while(millis() < timeoutmillis) { + + 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) { + if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) + { return status; } - DEBUG_WM (DEBUG_VERBOSE,F(".")); + DEBUG_WM(DEBUG_VERBOSE, F(".")); delay(100); } return status; @@ -838,18 +980,20 @@ uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) { // WPS enabled? https://github.com/esp8266/Arduino/pull/4889 #ifdef NO_EXTRA_4K_HEAP -void WiFiManager::startWPS() { +void WiFiManager::startWPS() +{ DEBUG_WM(F("START WPS")); - #ifdef ESP8266 - WiFi.beginWPSConfig(); - #else - // @todo - #endif +#ifdef ESP8266 + WiFi.beginWPSConfig(); +#else + // @todo +#endif DEBUG_WM(F("END WPS")); } #endif -String WiFiManager::getHTTPHead(String title){ +String WiFiManager::getHTTPHead(String title) +{ String page; page += FPSTR(HTTP_HEAD_START); page.replace(FPSTR(T_v), title); @@ -857,14 +1001,16 @@ String WiFiManager::getHTTPHead(String title){ page += FPSTR(HTTP_STYLE); page += _customHeadElement; - if(_bodyClass != ""){ + if (_bodyClass != "") + { String p = FPSTR(HTTP_HEAD_END); p.replace(FPSTR(T_c), _bodyClass); // add class str page += p; } - else { + else + { page += FPSTR(HTTP_HEAD_END); - } + } return page; } @@ -872,20 +1018,23 @@ String WiFiManager::getHTTPHead(String title){ /** * HTTPD handler for page requests */ -void WiFiManager::handleRequest() { +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 +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 + 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(); @@ -894,8 +1043,9 @@ void WiFiManager::handleRoot() { 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((unsigned)20000,true); // preload wifiscan throttled, async + // server->close(); // testing reliability fix for content length mismatches during mutiple flood hits WiFi_scanNetworks(); // preload wifiscan + if (_preloadwifiscan) + WiFi_scanNetworks((unsigned)20000, 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 @@ -904,13 +1054,15 @@ void WiFiManager::handleRoot() { /** * HTTPD CALLBACK Wifi config page handler */ -void WiFiManager::handleWifi(boolean scan) { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Wifi")); +void WiFiManager::handleWifi(boolean scan) +{ + DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Wifi")); handleRequest(); String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi - if (scan) { + if (scan) + { // DEBUG_WM(DEBUG_DEV,"refresh flag:",server->hasArg(F("refresh"))); - WiFi_scanNetworks(server->hasArg(F("refresh")),false); //wifiscan, force if arg refresh + WiFi_scanNetworks(server->hasArg(F("refresh")), false); //wifiscan, force if arg refresh page += getScanItemOut(); } String pitem = ""; @@ -925,7 +1077,8 @@ void WiFiManager::handleWifi(boolean scan) { page += getStaticOut(); page += FPSTR(HTTP_FORM_WIFI_END); - if(_paramsInWifi && _paramsCount>0){ + if (_paramsInWifi && _paramsCount > 0) + { page += FPSTR(HTTP_FORM_PARAM_HEAD); page += getParamOut(); } @@ -938,14 +1091,15 @@ void WiFiManager::handleWifi(boolean scan) { 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")); + DEBUG_WM(DEBUG_DEV, F("Sent config page")); } /** * HTTPD CALLBACK Wifi param page handler */ -void WiFiManager::handleParam(){ - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Param")); +void WiFiManager::handleParam() +{ + DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Param")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleparam)); // @token titlewifi @@ -963,15 +1117,17 @@ void WiFiManager::handleParam(){ server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); - DEBUG_WM(DEBUG_DEV,F("Sent param page")); + DEBUG_WM(DEBUG_DEV, F("Sent param page")); } +String WiFiManager::getMenuOut() +{ + String page; -String WiFiManager::getMenuOut(){ - String page; - - for(auto menuId :_menuIds ){ - if(((String)menuId == "param") && (_paramsCount == 0)) continue; // no params set, omit params + for (auto menuId : _menuIds) + { + if (((String)menuId == "param") && (_paramsCount == 0)) + continue; // no params set, omit params page += HTTP_PORTAL_MENU[menuId]; } @@ -983,207 +1139,253 @@ String WiFiManager::getMenuOut(){ // WiFi_scanNetworks(force); // } -void WiFiManager::WiFi_scanComplete(int networksFound){ +void WiFiManager::WiFi_scanComplete(int networksFound) +{ _lastscan = millis(); _numNetworks = networksFound; - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC completed"), "in "+(String)(_lastscan - _startscan)+" ms"); - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC found:"),_numNetworks); + DEBUG_WM(DEBUG_VERBOSE, F("WiFi Scan ASYNC completed"), "in " + (String)(_lastscan - _startscan) + " ms"); + DEBUG_WM(DEBUG_VERBOSE, F("WiFi Scan ASYNC found:"), _numNetworks); } -bool WiFiManager::WiFi_scanNetworks(){ - return WiFi_scanNetworks(false,false); +bool WiFiManager::WiFi_scanNetworks() +{ + return WiFi_scanNetworks(false, false); } -bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime,bool async){ - return WiFi_scanNetworks(millis()-_lastscan > cachetime,async); +bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime, bool async) +{ + return WiFi_scanNetworks(millis() - _lastscan > cachetime, async); } -bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime){ - return WiFi_scanNetworks(millis()-_lastscan > cachetime,false); +bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime) +{ + return WiFi_scanNetworks(millis() - _lastscan > cachetime, false); } -bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ - // DEBUG_WM(DEBUG_DEV,"scanNetworks async:",async == true); - // DEBUG_WM(DEBUG_DEV,_numNetworks,(millis()-_lastscan )); - // DEBUG_WM(DEBUG_DEV,"scanNetworks force:",force == true); - if(force || _numNetworks == 0 || (millis()-_lastscan > 60000)){ - int8_t res; - _startscan = millis(); - if(async){ - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); - #ifdef ESP8266 - #ifndef WM_NOASYNC // no async available < 2.4.0 - using namespace std::placeholders; // for `_1` - WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); - #else - res = WiFi.scanNetworks(); - #endif - #else - res = WiFi.scanNetworks(true); - #endif - return false; +bool WiFiManager::WiFi_scanNetworks(bool force, bool async) +{ + // DEBUG_WM(DEBUG_DEV,"scanNetworks async:",async == true); + // DEBUG_WM(DEBUG_DEV,_numNetworks,(millis()-_lastscan )); + // DEBUG_WM(DEBUG_DEV,"scanNetworks force:",force == true); + if (force || _numNetworks == 0 || (millis() - _lastscan > 60000)) + { + int8_t res; + _startscan = millis(); + if (async) + { + DEBUG_WM(DEBUG_VERBOSE, F("WiFi Scan ASYNC started")); +#ifdef ESP8266 +#ifndef WM_NOASYNC // no async available < 2.4.0 + using namespace std::placeholders; // for `_1` + WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete, this, _1)); +#else + res = WiFi.scanNetworks(); +#endif +#else + res = WiFi.scanNetworks(true); +#endif + return false; + } + else + { + res = WiFi.scanNetworks(); + } + if (res == WIFI_SCAN_FAILED) + DEBUG_WM(DEBUG_ERROR, "[ERROR] scan failed"); + else if (res == WIFI_SCAN_RUNNING) + { + DEBUG_WM(DEBUG_ERROR, "[ERROR] scan waiting"); + while (WiFi.scanComplete() == WIFI_SCAN_RUNNING) + { + DEBUG_WM(DEBUG_ERROR, "."); + delay(100); } - else{ - res = WiFi.scanNetworks(); - } - if(res == WIFI_SCAN_FAILED) DEBUG_WM(DEBUG_ERROR,"[ERROR] scan failed"); - else if(res == WIFI_SCAN_RUNNING){ - DEBUG_WM(DEBUG_ERROR,"[ERROR] scan waiting"); - while(WiFi.scanComplete() == WIFI_SCAN_RUNNING){ - DEBUG_WM(DEBUG_ERROR,"."); - delay(100); - } - _numNetworks = WiFi.scanComplete(); - } - else if(res >=0 ) _numNetworks = res; - _lastscan = millis(); - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); - return true; - } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+" ms ago"); - return false; + _numNetworks = WiFi.scanComplete(); + } + else if (res >= 0) + _numNetworks = res; + _lastscan = millis(); + DEBUG_WM(DEBUG_VERBOSE, F("WiFi Scan completed"), "in " + (String)(_lastscan - _startscan) + " ms"); + return true; + } + else + DEBUG_WM(DEBUG_VERBOSE, "Scan is cached", (String)(millis() - _lastscan) + " ms ago"); + return false; } -String WiFiManager::WiFiManager::getScanItemOut(){ - String page; +String WiFiManager::WiFiManager::getScanItemOut() +{ + String page; - if(!_numNetworks) WiFi_scanNetworks(); // scan in case this gets called before any scans + if (!_numNetworks) + WiFi_scanNetworks(); // scan in case this gets called before any scans - int n = _numNetworks; - if (n == 0) { - DEBUG_WM(F("No networks found")); - page += FPSTR(S_nonetworks); // @token nonetworks - } - else { - DEBUG_WM(n,F("networks found")); - //sort networks - int indices[n]; - for (int i = 0; i < n; i++) { - indices[i] = i; - } + int n = _numNetworks; + if (n == 0) + { + DEBUG_WM(F("No networks found")); + page += FPSTR(S_nonetworks); // @token nonetworks + } + else + { + DEBUG_WM(n, F("networks found")); + //sort networks + int indices[n]; + for (int i = 0; i < n; i++) + { + indices[i] = i; + } - // RSSI SORT - for (int i = 0; i < n; i++) { - for (int j = i + 1; j < n; j++) { - if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) { - std::swap(indices[i], indices[j]); - } + // RSSI SORT + for (int i = 0; i < n; i++) + { + for (int j = i + 1; j < n; j++) + { + if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) + { + std::swap(indices[i], indices[j]); } } + } - /* test std:sort + /* test std:sort std::sort(indices, indices + n, [](const int & a, const int & b) -> bool { return WiFi.RSSI(a) > WiFi.RSSI(b); }); */ - // remove duplicates ( must be RSSI sorted ) - if (_removeDuplicateAPs) { - String cssid; - for (int i = 0; i < n; i++) { - if (indices[i] == -1) continue; - cssid = WiFi.SSID(indices[i]); - for (int j = i + 1; j < n; j++) { - if (cssid == WiFi.SSID(indices[j])) { - DEBUG_WM(DEBUG_VERBOSE,F("DUP AP:"),WiFi.SSID(indices[j])); - indices[j] = -1; // set dup aps to index -1 - } + // remove duplicates ( must be RSSI sorted ) + if (_removeDuplicateAPs) + { + String cssid; + for (int i = 0; i < n; i++) + { + if (indices[i] == -1) + continue; + cssid = WiFi.SSID(indices[i]); + for (int j = i + 1; j < n; j++) + { + if (cssid == WiFi.SSID(indices[j])) + { + DEBUG_WM(DEBUG_VERBOSE, F("DUP AP:"), WiFi.SSID(indices[j])); + indices[j] = -1; // set dup aps to index -1 } } } - - // token precheck, to speed up replacements on large ap lists - String HTTP_ITEM_STR = FPSTR(HTTP_ITEM); - - // toggle icons with percentage - HTTP_ITEM_STR.replace("{qp}", FPSTR(HTTP_ITEM_QP)); - HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "" : "h"); - HTTP_ITEM_STR.replace("{qi}", FPSTR(HTTP_ITEM_QI)); - HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "h" : ""); - - // set token precheck flags - bool tok_r = HTTP_ITEM_STR.indexOf(FPSTR(T_r)) > 0; - bool tok_R = HTTP_ITEM_STR.indexOf(FPSTR(T_R)) > 0; - bool tok_e = HTTP_ITEM_STR.indexOf(FPSTR(T_e)) > 0; - bool tok_q = HTTP_ITEM_STR.indexOf(FPSTR(T_q)) > 0; - bool tok_i = HTTP_ITEM_STR.indexOf(FPSTR(T_i)) > 0; - - //display networks in page - for (int i = 0; i < n; i++) { - if (indices[i] == -1) continue; // skip dups - - DEBUG_WM(DEBUG_VERBOSE,F("AP: "),(String)WiFi.RSSI(indices[i]) + " " + (String)WiFi.SSID(indices[i])); - - int rssiperc = getRSSIasQuality(WiFi.RSSI(indices[i])); - uint8_t enc_type = WiFi.encryptionType(indices[i]); - - if (_minimumQuality == -1 || _minimumQuality < rssiperc) { - String item = HTTP_ITEM_STR; - item.replace(FPSTR(T_v), htmlEntities(WiFi.SSID(indices[i]))); // ssid no encoding - if(tok_e) item.replace(FPSTR(T_e), encryptionTypeStr(enc_type)); - if(tok_r) item.replace(FPSTR(T_r), (String)rssiperc); // rssi percentage 0-100 - if(tok_R) item.replace(FPSTR(T_R), (String)WiFi.RSSI(indices[i])); // rssi db - if(tok_q) item.replace(FPSTR(T_q), (String)round(map(rssiperc,0,100,1,4))); //quality icon 1-4 - if(tok_i){ - if (enc_type != WM_WIFIOPEN) { - item.replace(FPSTR(T_i), F("l")); - } else { - item.replace(FPSTR(T_i), ""); - } - } - //DEBUG_WM(item); - page += item; - delay(0); - } else { - DEBUG_WM(DEBUG_VERBOSE,F("Skipping , does not meet _minimumQuality")); - } - - } - page += FPSTR(HTTP_BR); } - return page; -} + // token precheck, to speed up replacements on large ap lists + String HTTP_ITEM_STR = FPSTR(HTTP_ITEM); -String WiFiManager::getIpForm(String id, String title, String value){ - String item = FPSTR(HTTP_FORM_LABEL); - item += FPSTR(HTTP_FORM_PARAM); - item.replace(FPSTR(T_i), id); - item.replace(FPSTR(T_n), id); - item.replace(FPSTR(T_p), FPSTR(T_t)); - // item.replace(FPSTR(T_p), default); - item.replace(FPSTR(T_t), title); - item.replace(FPSTR(T_l), F("15")); - item.replace(FPSTR(T_v), value); - item.replace(FPSTR(T_c), ""); - return item; -} + // toggle icons with percentage + HTTP_ITEM_STR.replace("{qp}", FPSTR(HTTP_ITEM_QP)); + HTTP_ITEM_STR.replace("{h}", _scanDispOptions ? "" : "h"); + HTTP_ITEM_STR.replace("{qi}", FPSTR(HTTP_ITEM_QI)); + HTTP_ITEM_STR.replace("{h}", _scanDispOptions ? "h" : ""); -String WiFiManager::getStaticOut(){ - String page; - if ((_staShowStaticFields || _sta_static_ip) && _staShowStaticFields>=0) { - DEBUG_WM(DEBUG_DEV,"_staShowStaticFields"); - page += FPSTR(HTTP_FORM_STATIC_HEAD); - // @todo how can we get these accurate settings from memory , wifi_get_ip_info does not seem to reveal if struct ip_info is static or not - page += getIpForm(FPSTR(S_ip),FPSTR(S_staticip),(_sta_static_ip ? _sta_static_ip.toString() : "")); // @token staticip - // WiFi.localIP().toString(); - page += getIpForm(FPSTR(S_gw),FPSTR(S_staticgw),(_sta_static_gw ? _sta_static_gw.toString() : "")); // @token staticgw - // WiFi.gatewayIP().toString(); - page += getIpForm(FPSTR(S_sn),FPSTR(S_subnet),(_sta_static_sn ? _sta_static_sn.toString() : "")); // @token subnet - // WiFi.subnetMask().toString(); + // set token precheck flags + bool tok_r = HTTP_ITEM_STR.indexOf(FPSTR(T_r)) > 0; + bool tok_R = HTTP_ITEM_STR.indexOf(FPSTR(T_R)) > 0; + bool tok_e = HTTP_ITEM_STR.indexOf(FPSTR(T_e)) > 0; + bool tok_q = HTTP_ITEM_STR.indexOf(FPSTR(T_q)) > 0; + bool tok_i = HTTP_ITEM_STR.indexOf(FPSTR(T_i)) > 0; + + //display networks in page + for (int i = 0; i < n; i++) + { + if (indices[i] == -1) + continue; // skip dups + + DEBUG_WM(DEBUG_VERBOSE, F("AP: "), (String)WiFi.RSSI(indices[i]) + " " + (String)WiFi.SSID(indices[i])); + + int rssiperc = getRSSIasQuality(WiFi.RSSI(indices[i])); + uint8_t enc_type = WiFi.encryptionType(indices[i]); + + if (_minimumQuality == -1 || _minimumQuality < rssiperc) + { + String item = HTTP_ITEM_STR; + item.replace(FPSTR(T_v), htmlEntities(WiFi.SSID(indices[i]))); // ssid no encoding + if (tok_e) + item.replace(FPSTR(T_e), encryptionTypeStr(enc_type)); + if (tok_r) + item.replace(FPSTR(T_r), (String)rssiperc); // rssi percentage 0-100 + if (tok_R) + item.replace(FPSTR(T_R), (String)WiFi.RSSI(indices[i])); // rssi db + if (tok_q) + item.replace(FPSTR(T_q), (String)round(map(rssiperc, 0, 100, 1, 4))); //quality icon 1-4 + if (tok_i) + { + if (enc_type != WM_WIFIOPEN) + { + item.replace(FPSTR(T_i), F("l")); + } + else + { + item.replace(FPSTR(T_i), ""); + } + } + //DEBUG_WM(item); + page += item; + delay(0); + } + else + { + DEBUG_WM(DEBUG_VERBOSE, F("Skipping , does not meet _minimumQuality")); + } + } + page += FPSTR(HTTP_BR); } - if((_staShowDns || _sta_static_dns) && _staShowDns>=0){ - page += getIpForm(FPSTR(S_dns),FPSTR(S_staticdns),(_sta_static_dns ? _sta_static_dns.toString() : "")); // @token dns - } - - if(page!="") page += FPSTR(HTTP_BR); // @todo remove these, use css - return page; } -String WiFiManager::getParamOut(){ +String WiFiManager::getIpForm(String id, String title, String value) +{ + String item = FPSTR(HTTP_FORM_LABEL); + item += FPSTR(HTTP_FORM_PARAM); + item.replace(FPSTR(T_i), id); + item.replace(FPSTR(T_n), id); + item.replace(FPSTR(T_p), FPSTR(T_t)); + // item.replace(FPSTR(T_p), default); + item.replace(FPSTR(T_t), title); + item.replace(FPSTR(T_l), F("15")); + item.replace(FPSTR(T_v), value); + item.replace(FPSTR(T_c), ""); + return item; +} + +String WiFiManager::getStaticOut() +{ + String page; + if ((_staShowStaticFields || _sta_static_ip) && _staShowStaticFields >= 0) + { + DEBUG_WM(DEBUG_DEV, "_staShowStaticFields"); + page += FPSTR(HTTP_FORM_STATIC_HEAD); + // @todo how can we get these accurate settings from memory , wifi_get_ip_info does not seem to reveal if struct ip_info is static or not + page += getIpForm(FPSTR(S_ip), FPSTR(S_staticip), (_sta_static_ip ? _sta_static_ip.toString() : "")); // @token staticip + // WiFi.localIP().toString(); + page += getIpForm(FPSTR(S_gw), FPSTR(S_staticgw), (_sta_static_gw ? _sta_static_gw.toString() : "")); // @token staticgw + // WiFi.gatewayIP().toString(); + page += getIpForm(FPSTR(S_sn), FPSTR(S_subnet), (_sta_static_sn ? _sta_static_sn.toString() : "")); // @token subnet + // WiFi.subnetMask().toString(); + } + + if ((_staShowDns || _sta_static_dns) && _staShowDns >= 0) + { + page += getIpForm(FPSTR(S_dns), FPSTR(S_staticdns), (_sta_static_dns ? _sta_static_dns.toString() : "")); // @token dns + } + + if (page != "") + page += FPSTR(HTTP_BR); // @todo remove these, use css + + return page; +} + +String WiFiManager::getParamOut() +{ String page; - if(_paramsCount > 0){ + if (_paramsCount > 0) + { String HTTP_PARAM_temp = FPSTR(HTTP_FORM_LABEL); HTTP_PARAM_temp += FPSTR(HTTP_FORM_PARAM); @@ -1198,41 +1400,55 @@ String WiFiManager::getParamOut(){ char parLength[5]; // add the extra parameters to the form - for (int i = 0; i < _paramsCount; i++) { - if (_params[i] == NULL || _params[i]->_length == 0) { - DEBUG_WM(DEBUG_ERROR,"[ERROR] WiFiManagerParameter is out of scope"); + for (int i = 0; i < _paramsCount; i++) + { + if (_params[i] == NULL || _params[i]->_length == 0) + { + DEBUG_WM(DEBUG_ERROR, "[ERROR] WiFiManagerParameter is out of scope"); break; } - // label before or after, this could probably be done via floats however - String pitem; - switch (_params[i]->getLabelPlacement()) { - case WFM_LABEL_BEFORE: - pitem = FPSTR(HTTP_FORM_LABEL); - pitem += FPSTR(HTTP_FORM_PARAM); - break; - case WFM_LABEL_AFTER: - pitem = FPSTR(HTTP_FORM_PARAM); - pitem += FPSTR(HTTP_FORM_LABEL); - break; - default: - // WFM_NO_LABEL - pitem = FPSTR(HTTP_FORM_PARAM); - break; + // label before or after, this could probably be done via floats however + String pitem; + switch (_params[i]->getLabelPlacement()) + { + case WFM_LABEL_BEFORE: + pitem = FPSTR(HTTP_FORM_LABEL); + pitem += FPSTR(HTTP_FORM_PARAM); + break; + case WFM_LABEL_AFTER: + pitem = FPSTR(HTTP_FORM_PARAM); + pitem += FPSTR(HTTP_FORM_LABEL); + break; + default: + // WFM_NO_LABEL + pitem = FPSTR(HTTP_FORM_PARAM); + break; } // if no ID use customhtml for item, else generate from param string - if (_params[i]->getID() != NULL) { - if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); - if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); - if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); - if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); - if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getPlaceholder()); + if (_params[i]->getID() != NULL) + { + if (tok_I) + pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre) + (String)i); + if (tok_i) + pitem.replace(FPSTR(T_i), _params[i]->getID()); + if (tok_n) + pitem.replace(FPSTR(T_n), _params[i]->getID()); + if (tok_p) + pitem.replace(FPSTR(T_p), FPSTR(T_t)); + if (tok_t) + pitem.replace(FPSTR(T_t), _params[i]->getPlaceholder()); snprintf(parLength, 5, "%d", _params[i]->getValueLength()); - if(tok_l)pitem.replace(FPSTR(T_l), parLength); - if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); - if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // meant for additional attributes, not html - } else { + if (tok_l) + pitem.replace(FPSTR(T_l), parLength); + if (tok_v) + pitem.replace(FPSTR(T_v), _params[i]->getValue()); + if (tok_c) + pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // meant for additional attributes, not html + } + else + { pitem = _params[i]->getCustomHTML(); } @@ -1243,14 +1459,15 @@ String WiFiManager::getParamOut(){ return page; } -void WiFiManager::handleWiFiStatus(){ - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi status ")); +void WiFiManager::handleWiFiStatus() +{ + DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP WiFi status ")); handleRequest(); String page; - // String page = "{\"result\":true,\"count\":1}"; - #ifdef JSTEST - page = FPSTR(HTTP_JS); - #endif +// String page = "{\"result\":true,\"count\":1}"; +#ifdef JSTEST + page = FPSTR(HTTP_JS); +#endif server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); } @@ -1258,37 +1475,49 @@ void WiFiManager::handleWiFiStatus(){ /** * HTTPD CALLBACK save form and redirect to WLAN config page again */ -void WiFiManager::handleWifiSave() { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); - DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); +void WiFiManager::handleWifiSave() +{ + DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP WiFi save ")); + DEBUG_WM(DEBUG_DEV, F("Method:"), server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); handleRequest(); + // @todo use new callback for pre saves + if (_presavecallback != NULL) + { + _presavecallback(); + } + //SAVE/connect here _ssid = server->arg(F("s")).c_str(); _pass = server->arg(F("p")).c_str(); - if(_paramsInWifi) doParamSave(); + if (_paramsInWifi) + doParamSave(); - if (server->arg(FPSTR(S_ip)) != "") { + if (server->arg(FPSTR(S_ip)) != "") + { //_sta_static_ip.fromString(server->arg(FPSTR(S_ip)); String ip = server->arg(FPSTR(S_ip)); optionalIPFromString(&_sta_static_ip, ip.c_str()); - DEBUG_WM(DEBUG_DEV,F("static ip:"),ip); + DEBUG_WM(DEBUG_DEV, F("static ip:"), ip); } - if (server->arg(FPSTR(S_gw)) != "") { + if (server->arg(FPSTR(S_gw)) != "") + { String gw = server->arg(FPSTR(S_gw)); optionalIPFromString(&_sta_static_gw, gw.c_str()); - DEBUG_WM(DEBUG_DEV,F("static gateway:"),gw); + DEBUG_WM(DEBUG_DEV, F("static gateway:"), gw); } - if (server->arg(FPSTR(S_sn)) != "") { + if (server->arg(FPSTR(S_sn)) != "") + { String sn = server->arg(FPSTR(S_sn)); optionalIPFromString(&_sta_static_sn, sn.c_str()); - DEBUG_WM(DEBUG_DEV,F("static netmask:"),sn); + DEBUG_WM(DEBUG_DEV, F("static netmask:"), sn); } - if (server->arg(FPSTR(S_dns)) != "") { + if (server->arg(FPSTR(S_dns)) != "") + { String dns = server->arg(FPSTR(S_dns)); optionalIPFromString(&_sta_static_dns, dns.c_str()); - DEBUG_WM(DEBUG_DEV,F("static DNS:"),dns); + DEBUG_WM(DEBUG_DEV, F("static DNS:"), dns); } String page = getHTTPHead(FPSTR(S_titlewifisaved)); // @token titlewifisaved @@ -1299,20 +1528,28 @@ void WiFiManager::handleWifiSave() { server->sendHeader(FPSTR(HTTP_HEAD_CORS), FPSTR(HTTP_HEAD_CORS_ALLOW_ALL)); server->send(200, FPSTR(HTTP_HEAD_CT), page); - DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); + DEBUG_WM(DEBUG_DEV, F("Sent wifi save page")); connect = true; //signal ready to connect/reset process in processConfigPortal } -void WiFiManager::handleParamSave() { - - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); - DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); +void WiFiManager::handleParamSave() +{ + DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP WiFi save ")); + DEBUG_WM(DEBUG_DEV, F("Method:"), server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); handleRequest(); + + // @todo use new callback for pre saves + if (_presavecallback != NULL) + { + _presavecallback(); + } + doParamSave(); // @todo use new callback for paramsaves - if ( _savecallback != NULL) { + if (_savecallback != NULL) + { _savecallback(); } @@ -1323,50 +1560,58 @@ void WiFiManager::handleParamSave() { server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); - DEBUG_WM(DEBUG_DEV,F("Sent param save page")); + DEBUG_WM(DEBUG_DEV, F("Sent param save page")); } -void WiFiManager::doParamSave(){ +void WiFiManager::doParamSave() +{ //parameters - if(_paramsCount > 0){ - DEBUG_WM(DEBUG_VERBOSE,F("Parameters")); - DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); - for (int i = 0; i < _paramsCount; i++) { - if (_params[i] == NULL) { + if (_paramsCount > 0) + { + DEBUG_WM(DEBUG_VERBOSE, F("Parameters")); + DEBUG_WM(DEBUG_VERBOSE, FPSTR(D_HR)); + for (int i = 0; i < _paramsCount; i++) + { + if (_params[i] == NULL) + { break; } //read parameter from server - String name = (String)FPSTR(S_parampre)+(String)i; + String name = (String)FPSTR(S_parampre) + (String)i; String value; - if(server->hasArg(name)) { + if (server->hasArg(name)) + { value = server->arg(name); - } else { + } + else + { value = server->arg(_params[i]->getID()); } //store it in params array - value.toCharArray(_params[i]->_value, _params[i]->_length+1); // length+1 null terminated - DEBUG_WM(DEBUG_VERBOSE,(String)_params[i]->getID() + ":",value); + value.toCharArray(_params[i]->_value, _params[i]->_length + 1); // length+1 null terminated + DEBUG_WM(DEBUG_VERBOSE, (String)_params[i]->getID() + ":", value); } - DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + DEBUG_WM(DEBUG_VERBOSE, FPSTR(D_HR)); } } /** * HTTPD CALLBACK info page */ -void WiFiManager::handleInfo() { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Info")); +void WiFiManager::handleInfo() +{ + DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Info")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo reportStatus(page); uint16_t infos = 0; - //@todo convert to enum or refactor to strings - #ifdef ESP8266 - infos = 27; - String infoids[] = { +//@todo convert to enum or refactor to strings +#ifdef ESP8266 + infos = 27; + String infoids[] = { F("esphead"), F("uptime"), F("chipid"), @@ -1393,12 +1638,11 @@ void WiFiManager::handleInfo() { F("host"), F("stamac"), F("conx"), - F("autoconx") - }; + F("autoconx")}; - #elif defined(ESP32) - infos = 22; - String infoids[] = { +#elif defined(ESP32) + infos = 22; + String infoids[] = { F("esphead"), F("uptime"), F("chipid"), @@ -1420,214 +1664,279 @@ void WiFiManager::handleInfo() { F("dnss"), F("host"), F("stamac"), - F("conx") - }; - #endif + F("conx")}; +#endif - for(size_t i=0; i"); - if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); + if (_showInfoErase) + page += FPSTR(HTTP_ERASEBTN); page += FPSTR(HTTP_HELP); page += FPSTR(HTTP_END); server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); - DEBUG_WM(DEBUG_DEV,F("Sent info page")); + DEBUG_WM(DEBUG_DEV, F("Sent info page")); } -String WiFiManager::getInfoData(String id){ +String WiFiManager::getInfoData(String id) +{ String p; // @todo add versioning - if(id==F("esphead"))p = FPSTR(HTTP_INFO_esphead); - else if(id==F("wifihead"))p = FPSTR(HTTP_INFO_wifihead); - else if(id==F("uptime")){ + if (id == F("esphead")) + p = FPSTR(HTTP_INFO_esphead); + else if (id == F("wifihead")) + p = FPSTR(HTTP_INFO_wifihead); + else if (id == F("uptime")) + { // subject to rollover! p = FPSTR(HTTP_INFO_uptime); - p.replace(FPSTR(T_1),(String)(millis() / 1000 / 60)); - p.replace(FPSTR(T_2),(String)((millis() / 1000) % 60)); + p.replace(FPSTR(T_1), (String)(millis() / 1000 / 60)); + p.replace(FPSTR(T_2), (String)((millis() / 1000) % 60)); } - else if(id==F("chipid")){ + else if (id == F("chipid")) + { p = FPSTR(HTTP_INFO_chipid); - p.replace(FPSTR(T_1),String(WIFI_getChipId(),HEX)); + p.replace(FPSTR(T_1), String(WIFI_getChipId(), HEX)); } - #ifdef ESP32 - else if(id==F("chiprev")){ - p = FPSTR(HTTP_INFO_chiprev); - String rev = (String)ESP.getChipRevision(); - #ifdef _SOC_EFUSE_REG_H_ - String revb = (String)(REG_READ(EFUSE_BLK0_RDATA3_REG) >> (EFUSE_RD_CHIP_VER_RESERVE_S)&&EFUSE_RD_CHIP_VER_RESERVE_V); - p.replace(FPSTR(T_1),rev+"
"+revb); - #else - p.replace(FPSTR(T_1),rev); - #endif +#ifdef ESP32 + else if (id == F("chiprev")) + { + p = FPSTR(HTTP_INFO_chiprev); + String rev = (String)ESP.getChipRevision(); +#ifdef _SOC_EFUSE_REG_H_ + String revb = (String)(REG_READ(EFUSE_BLK0_RDATA3_REG) >> (EFUSE_RD_CHIP_VER_RESERVE_S) && EFUSE_RD_CHIP_VER_RESERVE_V); + p.replace(FPSTR(T_1), rev + "
" + revb); +#else + p.replace(FPSTR(T_1), rev); +#endif } - #endif - #ifdef ESP8266 - else if(id==F("fchipid")){ - p = FPSTR(HTTP_INFO_fchipid); - p.replace(FPSTR(T_1),(String)ESP.getFlashChipId()); +#endif +#ifdef ESP8266 + else if (id == F("fchipid")) + { + p = FPSTR(HTTP_INFO_fchipid); + p.replace(FPSTR(T_1), (String)ESP.getFlashChipId()); } - #endif - else if(id==F("idesize")){ +#endif + else if (id == F("idesize")) + { p = FPSTR(HTTP_INFO_idesize); - p.replace(FPSTR(T_1),(String)ESP.getFlashChipSize()); + p.replace(FPSTR(T_1), (String)ESP.getFlashChipSize()); } - else if(id==F("flashsize")){ - #ifdef ESP8266 - p = FPSTR(HTTP_INFO_flashsize); - p.replace(FPSTR(T_1),(String)ESP.getFlashChipRealSize()); - #endif + else if (id == F("flashsize")) + { +#ifdef ESP8266 + p = FPSTR(HTTP_INFO_flashsize); + p.replace(FPSTR(T_1), (String)ESP.getFlashChipRealSize()); +#endif } - else if(id==F("sdkver")){ + else if (id == F("sdkver")) + { p = FPSTR(HTTP_INFO_sdkver); - #ifdef ESP32 - p.replace(FPSTR(T_1),(String)esp_get_idf_version()); - #else - p.replace(FPSTR(T_1),(String)system_get_sdk_version()); - #endif +#ifdef ESP32 + p.replace(FPSTR(T_1), (String)esp_get_idf_version()); +#else + p.replace(FPSTR(T_1), (String)system_get_sdk_version()); +#endif } - else if(id==F("corever")){ - #ifdef ESP8266 - p = FPSTR(HTTP_INFO_corever); - p.replace(FPSTR(T_1),(String)ESP.getCoreVersion()); - #endif + else if (id == F("corever")) + { +#ifdef ESP8266 + p = FPSTR(HTTP_INFO_corever); + p.replace(FPSTR(T_1), (String)ESP.getCoreVersion()); +#endif } - #ifdef ESP8266 - else if(id==F("bootver")){ - p = FPSTR(HTTP_INFO_bootver); - p.replace(FPSTR(T_1),(String)system_get_boot_version()); +#ifdef ESP8266 + else if (id == F("bootver")) + { + p = FPSTR(HTTP_INFO_bootver); + p.replace(FPSTR(T_1), (String)system_get_boot_version()); } - #endif - else if(id==F("cpufreq")){ +#endif + else if (id == F("cpufreq")) + { p = FPSTR(HTTP_INFO_cpufreq); - p.replace(FPSTR(T_1),(String)ESP.getCpuFreqMHz()); + p.replace(FPSTR(T_1), (String)ESP.getCpuFreqMHz()); } - else if(id==F("freeheap")){ + else if (id == F("freeheap")) + { p = FPSTR(HTTP_INFO_freeheap); - p.replace(FPSTR(T_1),(String)ESP.getFreeHeap()); + p.replace(FPSTR(T_1), (String)ESP.getFreeHeap()); } - #ifdef ESP8266 - else if(id==F("memsketch")){ +#ifdef ESP8266 + else if (id == F("memsketch")) + { p = FPSTR(HTTP_INFO_memsketch); - p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); - p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + p.replace(FPSTR(T_1), (String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2), (String)(ESP.getSketchSize() + ESP.getFreeSketchSpace())); } - #endif - #ifdef ESP8266 - else if(id==F("memsmeter")){ +#endif +#ifdef ESP8266 + else if (id == F("memsmeter")) + { p = FPSTR(HTTP_INFO_memsmeter); - p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); - p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + p.replace(FPSTR(T_1), (String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2), (String)(ESP.getSketchSize() + ESP.getFreeSketchSpace())); } - #endif - else if(id==F("lastreset")){ - #ifdef ESP8266 - p = FPSTR(HTTP_INFO_lastreset); - p.replace(FPSTR(T_1),(String)ESP.getResetReason()); - #elif defined(ESP32) && defined(_ROM_RTC_H_) - // requires #include - p = FPSTR(HTTP_INFO_lastreset); - for(int i=0;i<2;i++){ - int reason = rtc_get_reset_reason(i); - String tok = (String)T_ss+(String)(i+1)+(String)T_es; - switch (reason) - { - //@todo move to array - case 1 : p.replace(tok,F("Vbat power on reset"));break; - case 3 : p.replace(tok,F("Software reset digital core"));break; - case 4 : p.replace(tok,F("Legacy watch dog reset digital core"));break; - case 5 : p.replace(tok,F("Deep Sleep reset digital core"));break; - case 6 : p.replace(tok,F("Reset by SLC module, reset digital core"));break; - case 7 : p.replace(tok,F("Timer Group0 Watch dog reset digital core"));break; - case 8 : p.replace(tok,F("Timer Group1 Watch dog reset digital core"));break; - case 9 : p.replace(tok,F("RTC Watch dog Reset digital core"));break; - case 10 : p.replace(tok,F("Instrusion tested to reset CPU"));break; - case 11 : p.replace(tok,F("Time Group reset CPU"));break; - case 12 : p.replace(tok,F("Software reset CPU"));break; - case 13 : p.replace(tok,F("RTC Watch dog Reset CPU"));break; - case 14 : p.replace(tok,F("for APP CPU, reseted by PRO CPU"));break; - case 15 : p.replace(tok,F("Reset when the vdd voltage is not stable"));break; - case 16 : p.replace(tok,F("RTC Watch dog reset digital core and rtc module"));break; - default : p.replace(tok,F("NO_MEAN")); - } +#endif + else if (id == F("lastreset")) + { +#ifdef ESP8266 + p = FPSTR(HTTP_INFO_lastreset); + p.replace(FPSTR(T_1), (String)ESP.getResetReason()); +#elif defined(ESP32) && defined(_ROM_RTC_H_) + // requires #include + p = FPSTR(HTTP_INFO_lastreset); + for (int i = 0; i < 2; i++) + { + int reason = rtc_get_reset_reason(i); + String tok = (String)T_ss + (String)(i + 1) + (String)T_es; + switch (reason) + { + //@todo move to array + case 1: + p.replace(tok, F("Vbat power on reset")); + break; + case 3: + p.replace(tok, F("Software reset digital core")); + break; + case 4: + p.replace(tok, F("Legacy watch dog reset digital core")); + break; + case 5: + p.replace(tok, F("Deep Sleep reset digital core")); + break; + case 6: + p.replace(tok, F("Reset by SLC module, reset digital core")); + break; + case 7: + p.replace(tok, F("Timer Group0 Watch dog reset digital core")); + break; + case 8: + p.replace(tok, F("Timer Group1 Watch dog reset digital core")); + break; + case 9: + p.replace(tok, F("RTC Watch dog Reset digital core")); + break; + case 10: + p.replace(tok, F("Instrusion tested to reset CPU")); + break; + case 11: + p.replace(tok, F("Time Group reset CPU")); + break; + case 12: + p.replace(tok, F("Software reset CPU")); + break; + case 13: + p.replace(tok, F("RTC Watch dog Reset CPU")); + break; + case 14: + p.replace(tok, F("for APP CPU, reseted by PRO CPU")); + break; + case 15: + p.replace(tok, F("Reset when the vdd voltage is not stable")); + break; + case 16: + p.replace(tok, F("RTC Watch dog reset digital core and rtc module")); + break; + default: + p.replace(tok, F("NO_MEAN")); } - #endif + } +#endif } - else if(id==F("apip")){ + else if (id == F("apip")) + { p = FPSTR(HTTP_INFO_apip); - p.replace(FPSTR(T_1),WiFi.softAPIP().toString()); + p.replace(FPSTR(T_1), WiFi.softAPIP().toString()); } - else if(id==F("apmac")){ + else if (id == F("apmac")) + { p = FPSTR(HTTP_INFO_apmac); - p.replace(FPSTR(T_1),(String)WiFi.softAPmacAddress()); + p.replace(FPSTR(T_1), (String)WiFi.softAPmacAddress()); } - #ifdef ESP32 - else if(id==F("aphost")){ - p = FPSTR(HTTP_INFO_aphost); - p.replace(FPSTR(T_1),WiFi.softAPgetHostname()); +#ifdef ESP32 + else if (id == F("aphost")) + { + p = FPSTR(HTTP_INFO_aphost); + p.replace(FPSTR(T_1), WiFi.softAPgetHostname()); } - #endif - else if(id==F("apssid")){ +#endif + else if (id == F("apssid")) + { p = FPSTR(HTTP_INFO_apssid); - p.replace(FPSTR(T_1),htmlEntities((String)WiFi_SSID())); + p.replace(FPSTR(T_1), htmlEntities((String)WiFi_SSID())); } - else if(id==F("apbssid")){ + else if (id == F("apbssid")) + { p = FPSTR(HTTP_INFO_apbssid); - p.replace(FPSTR(T_1),(String)WiFi.BSSIDstr()); + p.replace(FPSTR(T_1), (String)WiFi.BSSIDstr()); } - else if(id==F("staip")){ + else if (id == F("staip")) + { p = FPSTR(HTTP_INFO_staip); - p.replace(FPSTR(T_1),WiFi.localIP().toString()); + p.replace(FPSTR(T_1), WiFi.localIP().toString()); } - else if(id==F("stagw")){ + else if (id == F("stagw")) + { p = FPSTR(HTTP_INFO_stagw); - p.replace(FPSTR(T_1),WiFi.gatewayIP().toString()); + p.replace(FPSTR(T_1), WiFi.gatewayIP().toString()); } - else if(id==F("stasub")){ + else if (id == F("stasub")) + { p = FPSTR(HTTP_INFO_stasub); - p.replace(FPSTR(T_1),WiFi.subnetMask().toString()); + p.replace(FPSTR(T_1), WiFi.subnetMask().toString()); } - else if(id==F("dnss")){ + else if (id == F("dnss")) + { p = FPSTR(HTTP_INFO_dnss); - p.replace(FPSTR(T_1),WiFi.dnsIP().toString()); + p.replace(FPSTR(T_1), WiFi.dnsIP().toString()); } - else if(id==F("host")){ + else if (id == F("host")) + { p = FPSTR(HTTP_INFO_host); - #ifdef ESP32 - p.replace(FPSTR(T_1),WiFi.getHostname()); - #else - p.replace(FPSTR(T_1),WiFi.hostname()); - #endif +#ifdef ESP32 + p.replace(FPSTR(T_1), WiFi.getHostname()); +#else + p.replace(FPSTR(T_1), WiFi.hostname()); +#endif } - else if(id==F("stamac")){ + else if (id == F("stamac")) + { p = FPSTR(HTTP_INFO_stamac); - p.replace(FPSTR(T_1),WiFi.macAddress()); + p.replace(FPSTR(T_1), WiFi.macAddress()); } - else if(id==F("conx")){ + else if (id == F("conx")) + { p = FPSTR(HTTP_INFO_conx); - p.replace(FPSTR(T_1),WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); + p.replace(FPSTR(T_1), WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); } - #ifdef ESP8266 - else if(id==F("autoconx")){ +#ifdef ESP8266 + else if (id == F("autoconx")) + { p = FPSTR(HTTP_INFO_autoconx); - p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); + p.replace(FPSTR(T_1), WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); } - #endif +#endif return p; } /** * HTTPD CALLBACK root or redirect to captive portal */ -void WiFiManager::handleExit() { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Exit")); +void WiFiManager::handleExit() +{ + DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Exit")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleexit)); // @token titleexit - page += FPSTR(S_exiting); // @token exiting + page += FPSTR(S_exiting); // @token exiting server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); abort = true; @@ -1636,11 +1945,12 @@ void WiFiManager::handleExit() { /** * HTTPD CALLBACK reset page */ -void WiFiManager::handleReset() { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Reset")); +void WiFiManager::handleReset() +{ + DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Reset")); handleRequest(); String page = getHTTPHead(FPSTR(S_titlereset)); //@token titlereset - page += FPSTR(S_resetting); //@token resetting + page += FPSTR(S_resetting); //@token resetting page += FPSTR(HTTP_END); server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); @@ -1658,53 +1968,60 @@ void WiFiManager::handleReset() { // void WiFiManager::handleErase() { // handleErase(false); // } -void WiFiManager::handleErase(boolean opt) { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Erase")); +void WiFiManager::handleErase(boolean opt) +{ + DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Erase")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase bool ret = erase(opt); - if(ret) page += FPSTR(S_resetting); // @token resetting - else { + if (ret) + page += FPSTR(S_resetting); // @token resetting + else + { page += FPSTR(S_error); // @token erroroccur - DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFi EraseConfig failed")); + DEBUG_WM(DEBUG_ERROR, F("[ERROR] WiFi EraseConfig failed")); } page += FPSTR(HTTP_END); server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); - if(ret){ + if (ret) + { delay(2000); - DEBUG_WM(F("RESETTING ESP")); - reboot(); - } + DEBUG_WM(F("RESETTING ESP")); + reboot(); + } } /** * HTTPD CALLBACK 404 */ -void WiFiManager::handleNotFound() { - if (captivePortal()) return; // If captive portal redirect instead of displaying the page +void WiFiManager::handleNotFound() +{ + if (captivePortal()) + return; // If captive portal redirect instead of displaying the page handleRequest(); String message = FPSTR(S_notfound); // @token notfound - message += FPSTR(S_uri); // @token uri + message += FPSTR(S_uri); // @token uri message += server->uri(); message += FPSTR(S_method); // @token method - message += ( server->method() == HTTP_GET ) ? FPSTR(S_GET) : FPSTR(S_POST); + message += (server->method() == HTTP_GET) ? FPSTR(S_GET) : FPSTR(S_POST); message += FPSTR(S_args); // @token args message += server->args(); message += F("\n"); - for ( uint8_t i = 0; i < server->args(); i++ ) { - message += " " + server->argName ( i ) + ": " + server->arg ( i ) + "\n"; + for (uint8_t i = 0; i < server->args(); i++) + { + message += " " + server->argName(i) + ": " + server->arg(i) + "\n"; } server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); server->sendHeader(F("Pragma"), F("no-cache")); server->sendHeader(F("Expires"), F("-1")); server->sendHeader(FPSTR(HTTP_HEAD_CL), String(message.length())); - server->send ( 404, FPSTR(HTTP_HEAD_CT2), message ); + server->send(404, FPSTR(HTTP_HEAD_CT2), message); } /** @@ -1712,70 +2029,84 @@ void WiFiManager::handleNotFound() { * Redirect to captive portal if we got a request for another domain. * Return true in that case so the page handler do not try to handle the request again. */ -boolean WiFiManager::captivePortal() { - DEBUG_WM(DEBUG_DEV,"-> " + server->hostHeader()); - - if(!_enableCaptivePortal) return false; // skip redirections +boolean WiFiManager::captivePortal() +{ + DEBUG_WM(DEBUG_DEV, "-> " + server->hostHeader()); - if (!isIp(server->hostHeader())) { - DEBUG_WM(DEBUG_VERBOSE,F("<- Request redirected to captive portal")); + if (!_enableCaptivePortal) + return false; // skip redirections + + if (!isIp(server->hostHeader())) + { + DEBUG_WM(DEBUG_VERBOSE, F("<- Request redirected to captive portal")); server->sendHeader(F("Location"), (String)F("http://") + toStringIp(server->client().localIP()), true); - server->send ( 302, FPSTR(HTTP_HEAD_CT2), ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. - server->client().stop(); // Stop is needed because we sent no content length + server->send(302, FPSTR(HTTP_HEAD_CT2), ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + server->client().stop(); // Stop is needed because we sent no content length return true; } return false; } -void WiFiManager::stopCaptivePortal(){ - _enableCaptivePortal= false; +void WiFiManager::stopCaptivePortal() +{ + _enableCaptivePortal = false; // @todo maybe disable configportaltimeout(optional), or just provide callback for user } -void WiFiManager::handleClose(){ +void WiFiManager::handleClose() +{ stopCaptivePortal(); - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP close")); + DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP close")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleclose)); // @token titleclose - page += FPSTR(S_closing); // @token closing + page += FPSTR(S_closing); // @token closing server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); } -void WiFiManager::reportStatus(String &page){ +void WiFiManager::reportStatus(String &page) +{ updateConxResult(WiFi.status()); String str; - if (WiFi_SSID() != ""){ - if (WiFi.status()==WL_CONNECTED){ + if (WiFi_SSID() != "") + { + if (WiFi.status() == WL_CONNECTED) + { str = FPSTR(HTTP_STATUS_ON); - str.replace(FPSTR(T_i),WiFi.localIP().toString()); - str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + str.replace(FPSTR(T_i), WiFi.localIP().toString()); + str.replace(FPSTR(T_v), htmlEntities(WiFi_SSID())); } - else { + else + { str = FPSTR(HTTP_STATUS_OFF); - str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); - if(_lastconxresult == WL_STATION_WRONG_PASSWORD){ + str.replace(FPSTR(T_v), htmlEntities(WiFi_SSID())); + if (_lastconxresult == WL_STATION_WRONG_PASSWORD) + { // wrong password - str.replace(FPSTR(T_c),"D"); // class - str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFPW)); + str.replace(FPSTR(T_c), "D"); // class + str.replace(FPSTR(T_r), FPSTR(HTTP_STATUS_OFFPW)); } - else if(_lastconxresult == WL_NO_SSID_AVAIL){ + else if (_lastconxresult == WL_NO_SSID_AVAIL) + { // connect failed, or ap not found - str.replace(FPSTR(T_c),"D"); - str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFNOAP)); + str.replace(FPSTR(T_c), "D"); + str.replace(FPSTR(T_r), FPSTR(HTTP_STATUS_OFFNOAP)); } - else if(_lastconxresult == WL_CONNECT_FAILED){ + else if (_lastconxresult == WL_CONNECT_FAILED) + { // connect failed - str.replace(FPSTR(T_c),"D"); - str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFFAIL)); + str.replace(FPSTR(T_c), "D"); + str.replace(FPSTR(T_r), FPSTR(HTTP_STATUS_OFFFAIL)); + } + else + { + str.replace(FPSTR(T_c), ""); + str.replace(FPSTR(T_r), ""); } - else{ - str.replace(FPSTR(T_c),""); - str.replace(FPSTR(T_r),""); - } } } - else { + else + { str = FPSTR(HTTP_STATUS_NONE); } page += str; @@ -1795,11 +2126,13 @@ void WiFiManager::reportStatus(String &page){ * @since $dev * @return bool success */ -bool WiFiManager::disconnect(){ - if(WiFi.status() != WL_CONNECTED){ - DEBUG_WM(DEBUG_VERBOSE,"Disconnecting: Not connected"); +bool WiFiManager::disconnect() +{ + if (WiFi.status() != WL_CONNECTED) + { + DEBUG_WM(DEBUG_VERBOSE, "Disconnecting: Not connected"); return false; - } + } DEBUG_WM("Disconnecting"); return WiFi_Disconnect(); } @@ -1808,7 +2141,8 @@ bool WiFiManager::disconnect(){ * reboot the device * @access public */ -void WiFiManager::reboot(){ +void WiFiManager::reboot() +{ DEBUG_WM("Restarting"); ESP.restart(); } @@ -1817,28 +2151,31 @@ void WiFiManager::reboot(){ * reboot the device * @access public */ -bool WiFiManager::erase(){ +bool WiFiManager::erase() +{ return erase(false); } -bool WiFiManager::erase(bool opt){ +bool WiFiManager::erase(bool opt) +{ DEBUG_WM("Erasing"); - #if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) - // if opt true, do nvs erase - if(opt){ - DEBUG_WM("Erasing NVS"); - int err; - esp_err_t err; - err = nvs_flash_init(); - DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_init: ",err!=ESP_OK ? (String)err : "Success"); - err = nvs_flash_erase(); - DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_erase: ", err!=ESP_OK ? (String)err : "Success"); - return err == ESP_OK; - } - #else - (void)opt; - #endif +#if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) + // if opt true, do nvs erase + if (opt) + { + DEBUG_WM("Erasing NVS"); + int err; + esp_err_t err; + err = nvs_flash_init(); + DEBUG_WM(DEBUG_VERBOSE, "nvs_flash_init: ", err != ESP_OK ? (String)err : "Success"); + err = nvs_flash_erase(); + DEBUG_WM(DEBUG_VERBOSE, "nvs_flash_erase: ", err != ESP_OK ? (String)err : "Success"); + return err == ESP_OK; + } +#else + (void)opt; +#endif return WiFi_eraseConfig(); } @@ -1848,17 +2185,18 @@ bool WiFiManager::erase(bool opt){ * ERASES STA CREDENTIALS * @access public */ -void WiFiManager::resetSettings() { +void WiFiManager::resetSettings() +{ DEBUG_WM(F("SETTINGS ERASED")); - WiFi_enableSTA(true,true); // must be sta to disconnect erase - - #ifdef ESP32 - WiFi.disconnect(true,true); - #else - WiFi.persistent(true); - WiFi.disconnect(true); - WiFi.persistent(false); - #endif + WiFi_enableSTA(true, true); // must be sta to disconnect erase + +#ifdef ESP32 + WiFi.disconnect(true, true); +#else + WiFi.persistent(true); + WiFi.disconnect(true); + WiFi.persistent(false); +#endif } // SETTERS @@ -1868,7 +2206,8 @@ void WiFiManager::resetSettings() { * @access public * @param {[type]} unsigned long seconds [description] */ -void WiFiManager::setTimeout(unsigned long seconds) { +void WiFiManager::setTimeout(unsigned long seconds) +{ setConfigPortalTimeout(seconds); } @@ -1877,7 +2216,8 @@ void WiFiManager::setTimeout(unsigned long seconds) { * @access public * @param {[type]} unsigned long seconds [description] */ -void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { +void WiFiManager::setConfigPortalTimeout(unsigned long seconds) +{ _configPortalTimeout = seconds * 1000; } @@ -1886,7 +2226,8 @@ void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { * @access public * @param {[type]} unsigned long seconds [description] */ -void WiFiManager::setConnectTimeout(unsigned long seconds) { +void WiFiManager::setConnectTimeout(unsigned long seconds) +{ _connectTimeout = seconds * 1000; } @@ -1895,7 +2236,8 @@ void WiFiManager::setConnectTimeout(unsigned long seconds) { * @access public * @param {[type]} unsigned long seconds [description] */ -void WiFiManager::setSaveConnectTimeout(unsigned long seconds) { +void WiFiManager::setSaveConnectTimeout(unsigned long seconds) +{ _saveTimeout = seconds * 1000; } @@ -1904,7 +2246,8 @@ void WiFiManager::setSaveConnectTimeout(unsigned long seconds) { * @access public * @param {[type]} boolean debug [description] */ -void WiFiManager::setDebugOutput(boolean debug) { +void WiFiManager::setDebugOutput(boolean debug) +{ _debug = debug; } @@ -1915,7 +2258,8 @@ void WiFiManager::setDebugOutput(boolean debug) { * @param {[type]} IPAddress gw [description] * @param {[type]} IPAddress sn [description] */ -void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { +void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) +{ _ap_static_ip = ip; _ap_static_gw = gw; _ap_static_sn = sn; @@ -1928,7 +2272,8 @@ void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) * @param {[type]} IPAddress gw [description] * @param {[type]} IPAddress sn [description] */ -void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) +{ _sta_static_ip = ip; _sta_static_gw = gw; _sta_static_sn = sn; @@ -1943,8 +2288,9 @@ void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) * @param {[type]} IPAddress sn [description] * @param {[type]} IPAddress dns [description] */ -void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns) { - setSTAStaticIPConfig(ip,gw,sn); +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns) +{ + setSTAStaticIPConfig(ip, gw, sn); _sta_static_dns = dns; } @@ -1953,7 +2299,8 @@ void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, * @access public * @param {[type]} int quality [description] */ -void WiFiManager::setMinimumSignalQuality(int quality) { +void WiFiManager::setMinimumSignalQuality(int quality) +{ _minimumQuality = quality; } @@ -1962,7 +2309,8 @@ void WiFiManager::setMinimumSignalQuality(int quality) { * @access public * @param {[type]} boolean shouldBreak [description] */ -void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { +void WiFiManager::setBreakAfterConfig(boolean shouldBreak) +{ _shouldBreakAfterConfig = shouldBreak; } @@ -1971,27 +2319,41 @@ void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { * @access public * @param {[type]} void (*func)(WiFiManager* myWiFiManager) [description] */ -void WiFiManager::setAPCallback( std::function func ) { +void WiFiManager::setAPCallback(std::function func) +{ _apcallback = func; } - + /** * setSaveConfigCallback, set a save config callback after closing configportal * @todo only calls if configportal stopped * @access public * @param {[type]} void (*func)(void) [description] */ -void WiFiManager::setSaveConfigCallback( std::function func ) { +void WiFiManager::setSaveConfigCallback(std::function func) +{ _savecallback = func; } +/** + * setSaveConfigCallback, set a save config callback after closing configportal + * @todo only calls if configportal stopped + * @access public + * @param {[type]} void (*func)(void) [description] + */ +void WiFiManager::setPreSaveConfigCallback(std::function func) +{ + _presavecallback = func; +} + /** * set custom head html * custom element will be added to head, eg. new style tag etc. * @access public * @param char element */ -void WiFiManager::setCustomHeadElement(const char* element) { +void WiFiManager::setCustomHeadElement(const char *element) +{ _customHeadElement = element; } @@ -2002,7 +2364,8 @@ void WiFiManager::setCustomHeadElement(const char* element) { * @access public * @param boolean removeDuplicates [true] */ -void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) { +void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) +{ _removeDuplicateAPs = removeDuplicates; } @@ -2014,7 +2377,8 @@ void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) { * @access public * @param boolean shoudlBlock [false] */ -void WiFiManager::setConfigPortalBlocking(boolean shoudlBlock) { +void WiFiManager::setConfigPortalBlocking(boolean shoudlBlock) +{ _configPortalIsBlocking = shoudlBlock; } @@ -2026,9 +2390,11 @@ void WiFiManager::setConfigPortalBlocking(boolean shoudlBlock) { * @access public * @param boolean persistent [true] */ -void WiFiManager::setRestorePersistent(boolean persistent) { +void WiFiManager::setRestorePersistent(boolean persistent) +{ _userpersistent = persistent; - if(!persistent) DEBUG_WM(F("persistent is off")); + if (!persistent) + DEBUG_WM(F("persistent is off")); } /** @@ -2038,9 +2404,12 @@ void WiFiManager::setRestorePersistent(boolean persistent) { * @access public * @param boolean alwaysShow [false] */ -void WiFiManager::setShowStaticFields(boolean alwaysShow){ - if(_disableIpFields) _staShowStaticFields = alwaysShow ? 1 : -1; - else _staShowStaticFields = alwaysShow ? 1 : 0; +void WiFiManager::setShowStaticFields(boolean alwaysShow) +{ + if (_disableIpFields) + _staShowStaticFields = alwaysShow ? 1 : -1; + else + _staShowStaticFields = alwaysShow ? 1 : 0; } /** @@ -2050,8 +2419,10 @@ void WiFiManager::setShowStaticFields(boolean alwaysShow){ * @access public * @param boolean alwaysShow [false] */ -void WiFiManager::setShowDnsFields(boolean alwaysShow){ - if(_disableIpFields) _staShowDns = alwaysShow ? 1 : -1; +void WiFiManager::setShowDnsFields(boolean alwaysShow) +{ + if (_disableIpFields) + _staShowDns = alwaysShow ? 1 : -1; _staShowDns = alwaysShow ? 1 : 0; } @@ -2063,7 +2434,8 @@ void WiFiManager::setShowDnsFields(boolean alwaysShow){ * @access public * @param boolean enabled [true] */ -void WiFiManager::setCaptivePortalEnable(boolean enabled){ +void WiFiManager::setCaptivePortalEnable(boolean enabled) +{ _enableCaptivePortal = enabled; } @@ -2076,7 +2448,8 @@ void WiFiManager::setCaptivePortalEnable(boolean enabled){ * @access public * @param boolean enabled [true] */ -void WiFiManager::setWiFiAutoReconnect(boolean enabled){ +void WiFiManager::setWiFiAutoReconnect(boolean enabled) +{ _wifiAutoReconnect = enabled; } @@ -2088,7 +2461,8 @@ void WiFiManager::setWiFiAutoReconnect(boolean enabled){ * @access public * @param boolean enabled [false] */ -void WiFiManager::setCaptivePortalClientCheck(boolean enabled){ +void WiFiManager::setCaptivePortalClientCheck(boolean enabled) +{ _cpClientCheck = enabled; } @@ -2099,7 +2473,8 @@ void WiFiManager::setCaptivePortalClientCheck(boolean enabled){ * @access public * @param boolean enabled [true] */ -void WiFiManager::setWebPortalClientCheck(boolean enabled){ +void WiFiManager::setWebPortalClientCheck(boolean enabled) +{ _webClientCheck = enabled; } @@ -2109,7 +2484,8 @@ void WiFiManager::setWebPortalClientCheck(boolean enabled){ * @access public * @param boolean enabled [false] */ -void WiFiManager::setScanDispPerc(boolean enabled){ +void WiFiManager::setScanDispPerc(boolean enabled) +{ _scanDispOptions = enabled; } @@ -2122,10 +2498,9 @@ void WiFiManager::setScanDispPerc(boolean enabled){ */ void WiFiManager::setEnableConfigPortal(boolean enable) { - _enableConfigPortal = enable; + _enableConfigPortal = enable; } - /** * set the hostname (dhcp client id) * @since $dev @@ -2133,7 +2508,8 @@ void WiFiManager::setEnableConfigPortal(boolean enable) * @param char* hostname 32 character hostname to use for sta+ap in esp32, sta in esp8266 * @return bool false if hostname is not valid */ -bool WiFiManager::setHostname(const char * hostname){ +bool WiFiManager::setHostname(const char *hostname) +{ //@todo max length 32 _hostname = hostname; return true; @@ -2143,7 +2519,8 @@ bool WiFiManager::setHostname(const char * hostname){ * toggle showing erase wifi config button on info page * @param boolean enabled */ -void WiFiManager::setShowInfoErase(boolean enabled){ +void WiFiManager::setShowInfoErase(boolean enabled) +{ _showInfoErase = enabled; } @@ -2156,13 +2533,18 @@ void WiFiManager::setShowInfoErase(boolean enabled){ * @since $dev * @param uint8_t menu[] array of menu ids */ -void WiFiManager::setMenu(const char * menu[], uint8_t size){ +void WiFiManager::setMenu(const char *menu[], uint8_t size) +{ // DEBUG_WM(DEBUG_VERBOSE,"setmenu array"); _menuIds.clear(); - for(size_t i = 0; i < size; i++){ - for(size_t j = 0; j < _nummenutokens; j++){ - if(menu[i] == _menutokens[j]){ - if((String)menu[i] == "param") _paramsInWifi = false; // param auto flag + for (size_t i = 0; i < size; i++) + { + for (size_t j = 0; j < _nummenutokens; j++) + { + if (menu[i] == _menutokens[j]) + { + if ((String)menu[i] == "param") + _paramsInWifi = false; // param auto flag _menuIds.push_back(j); } } @@ -2179,13 +2561,18 @@ void WiFiManager::setMenu(const char * menu[], uint8_t size){ * @shiftIncrement $dev * @param {[type]} std::vector& menu [description] */ -void WiFiManager::setMenu(std::vector& menu){ +void WiFiManager::setMenu(std::vector &menu) +{ // DEBUG_WM(DEBUG_VERBOSE,"setmenu vector"); _menuIds.clear(); - for(auto menuitem : menu ){ - for(size_t j = 0; j < _nummenutokens; j++){ - if(menuitem == _menutokens[j]){ - if((String)menuitem == "param") _paramsInWifi = false; // param auto flag + for (auto menuitem : menu) + { + for (size_t j = 0; j < _nummenutokens; j++) + { + if (menuitem == _menutokens[j]) + { + if ((String)menuitem == "param") + _paramsInWifi = false; // param auto flag _menuIds.push_back(j); } } @@ -2193,7 +2580,6 @@ void WiFiManager::setMenu(std::vector& menu){ // DEBUG_WM(getMenuOut()); } - // GETTERS /** @@ -2202,7 +2588,8 @@ void WiFiManager::setMenu(std::vector& menu){ * @access public * @return String the configportal ap name */ -String WiFiManager::getConfigPortalSSID() { +String WiFiManager::getConfigPortalSSID() +{ return _apName; } @@ -2214,7 +2601,8 @@ String WiFiManager::getConfigPortalSSID() { * @access public * @return bool return wl_status codes */ -uint8_t WiFiManager::getLastConxResult(){ +uint8_t WiFiManager::getLastConxResult() +{ return _lastconxresult; } @@ -2224,7 +2612,8 @@ uint8_t WiFiManager::getLastConxResult(){ * @access public * @return bool true if a saved ap config exists */ -bool WiFiManager::getWiFiIsSaved(){ +bool WiFiManager::getWiFiIsSaved() +{ return WiFi_hasAutoConnect(); } @@ -2233,7 +2622,8 @@ bool WiFiManager::getWiFiIsSaved(){ * @since $dev * @param String cc country code, must be defined in WiFiSetCountry, US, JP, CN */ -void WiFiManager::setCountry(String cc){ +void WiFiManager::setCountry(String cc) +{ _wificountry = cc; } @@ -2241,41 +2631,51 @@ void WiFiManager::setCountry(String cc){ * setClass * @param String str body class string */ -void WiFiManager::setClass(String str){ +void WiFiManager::setClass(String str) +{ _bodyClass = str; } - + // HELPERS // DEBUG // @todo fix DEBUG_WM(0,0); template -void WiFiManager::DEBUG_WM(Generic text) { - DEBUG_WM(DEBUG_NOTIFY,text,""); +void WiFiManager::DEBUG_WM(Generic text) +{ + DEBUG_WM(DEBUG_NOTIFY, text, ""); } template -void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text) { - if(_debugLevel >= level) DEBUG_WM(level,text,""); +void WiFiManager::DEBUG_WM(wm_debuglevel_t level, Generic text) +{ + if (_debugLevel >= level) + DEBUG_WM(level, text, ""); } template -void WiFiManager::DEBUG_WM(Generic text,Genericb textb) { - DEBUG_WM(DEBUG_NOTIFY,text,textb); +void WiFiManager::DEBUG_WM(Generic text, Genericb textb) +{ + DEBUG_WM(DEBUG_NOTIFY, text, textb); } template -void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { - if(!_debug || _debugLevel < level) return; +void WiFiManager::DEBUG_WM(wm_debuglevel_t level, Generic text, Genericb textb) +{ + if (!_debug || _debugLevel < level) + return; - if(_debugLevel >= DEBUG_MAX){ + if (_debugLevel >= DEBUG_MAX) + { _debugPort.print("MEM: "); _debugPort.println((String)ESP.getFreeHeap()); } _debugPort.print("*WM: "); - if(_debugLevel == DEBUG_DEV) _debugPort.print("["+(String)level+"] "); + if (_debugLevel == DEBUG_DEV) + _debugPort.print("[" + (String)level + "] "); _debugPort.print(text); - if(textb){ + if (textb) + { _debugPort.print(" "); _debugPort.print(textb); } @@ -2287,27 +2687,28 @@ void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { * @access public * @return {[type]} [description] */ -void WiFiManager::debugSoftAPConfig(){ - #ifdef ESP8266 - softap_config config; - wifi_softap_get_config(&config); - #elif defined(ESP32) - wifi_config_t conf_config; - esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK - wifi_ap_config_t config = conf_config.ap; - #endif +void WiFiManager::debugSoftAPConfig() +{ +#ifdef ESP8266 + softap_config config; + wifi_softap_get_config(&config); +#elif defined(ESP32) + wifi_config_t conf_config; + esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK + wifi_ap_config_t config = conf_config.ap; +#endif - DEBUG_WM(F("SoftAP Configuration")); - DEBUG_WM(FPSTR(D_HR)); - DEBUG_WM(F("ssid: "),(char *) config.ssid); - DEBUG_WM(F("password: "),(char *) config.password); - DEBUG_WM(F("ssid_len: "),config.ssid_len); - DEBUG_WM(F("channel: "),config.channel); - DEBUG_WM(F("authmode: "),config.authmode); - DEBUG_WM(F("ssid_hidden: "),config.ssid_hidden); - DEBUG_WM(F("max_connection: "),config.max_connection); - DEBUG_WM(F("beacon_interval: "),(String)config.beacon_interval + "(ms)"); - DEBUG_WM(FPSTR(D_HR)); + DEBUG_WM(F("SoftAP Configuration")); + DEBUG_WM(FPSTR(D_HR)); + DEBUG_WM(F("ssid: "), (char *)config.ssid); + DEBUG_WM(F("password: "), (char *)config.password); + DEBUG_WM(F("ssid_len: "), config.ssid_len); + DEBUG_WM(F("channel: "), config.channel); + DEBUG_WM(F("authmode: "), config.authmode); + DEBUG_WM(F("ssid_hidden: "), config.ssid_hidden); + DEBUG_WM(F("max_connection: "), config.max_connection); + DEBUG_WM(F("beacon_interval: "), (String)config.beacon_interval + "(ms)"); + DEBUG_WM(FPSTR(D_HR)); } /** @@ -2315,38 +2716,48 @@ void WiFiManager::debugSoftAPConfig(){ * @access public * @return {[type]} [description] */ -void WiFiManager::debugPlatformInfo(){ - #ifdef ESP8266 - system_print_meminfo(); - DEBUG_WM(F("getCoreVersion(): "),ESP.getCoreVersion()); - DEBUG_WM(F("system_get_sdk_version(): "),system_get_sdk_version()); - DEBUG_WM(F("system_get_boot_version():"),system_get_boot_version()); - DEBUG_WM(F("getFreeHeap(): "),(String)ESP.getFreeHeap()); - #elif defined(ESP32) - size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); - DEBUG_WM("Free heap: ", freeHeap); - DEBUG_WM("ESP-IDF version: ", esp_get_idf_version()); - #endif +void WiFiManager::debugPlatformInfo() +{ +#ifdef ESP8266 + system_print_meminfo(); + DEBUG_WM(F("getCoreVersion(): "), ESP.getCoreVersion()); + DEBUG_WM(F("system_get_sdk_version(): "), system_get_sdk_version()); + DEBUG_WM(F("system_get_boot_version():"), system_get_boot_version()); + DEBUG_WM(F("getFreeHeap(): "), (String)ESP.getFreeHeap()); +#elif defined(ESP32) + size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); + DEBUG_WM("Free heap: ", freeHeap); + DEBUG_WM("ESP-IDF version: ", esp_get_idf_version()); +#endif } -int WiFiManager::getRSSIasQuality(int RSSI) { +int WiFiManager::getRSSIasQuality(int RSSI) +{ int quality = 0; - if (RSSI <= -100) { + if (RSSI <= -100) + { quality = 0; - } else if (RSSI >= -50) { + } + else if (RSSI >= -50) + { quality = 100; - } else { + } + else + { quality = 2 * (RSSI + 100); } return quality; } /** Is this an IP? */ -boolean WiFiManager::isIp(String str) { - for (size_t i = 0; i < str.length(); i++) { +boolean WiFiManager::isIp(String str) +{ + for (size_t i = 0; i < str.length(); i++) + { int c = str.charAt(i); - if (c != '.' && (c < '0' || c > '9')) { + if (c != '.' && (c < '0' || c > '9')) + { return false; } } @@ -2354,25 +2765,31 @@ boolean WiFiManager::isIp(String str) { } /** IP to String? */ -String WiFiManager::toStringIp(IPAddress ip) { +String WiFiManager::toStringIp(IPAddress ip) +{ String res = ""; - for (int i = 0; i < 3; i++) { + for (int i = 0; i < 3; i++) + { res += String((ip >> (8 * i)) & 0xFF) + "."; } res += String(((ip >> 8 * 3)) & 0xFF); return res; } -boolean WiFiManager::validApPassword(){ +boolean WiFiManager::validApPassword() +{ // check that ap password is valid, return false - if (_apPassword == NULL) _apPassword = ""; - if (_apPassword != "") { - if (_apPassword.length() < 8 || _apPassword.length() > 63) { + if (_apPassword == NULL) + _apPassword = ""; + if (_apPassword != "") + { + if (_apPassword.length() < 8 || _apPassword.length() > 63) + { DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); _apPassword = ""; return false; // @todo FATAL or fallback to empty ? } - DEBUG_WM(DEBUG_VERBOSE,F("AccessPoint set password is VALID")); + DEBUG_WM(DEBUG_VERBOSE, F("AccessPoint set password is VALID")); DEBUG_WM(_apPassword); } return true; @@ -2384,16 +2801,17 @@ boolean WiFiManager::validApPassword(){ * @param string str string to replace entities * @return string encoded string */ -String WiFiManager::htmlEntities(String str) { - str.replace("&","&"); - str.replace("<","<"); - str.replace(">",">"); +String WiFiManager::htmlEntities(String str) +{ + str.replace("&", "&"); + str.replace("<", "<"); + str.replace(">", ">"); // str.replace("'","'"); // str.replace("\"","""); // str.replace("/": "/"); // str.replace("`": "`"); // str.replace("=": "="); -return str; + return str; } /** @@ -2402,191 +2820,240 @@ return str; * @param {[type]} uint8_t status [description] * @return {[type]} [description] */ -String WiFiManager::getWLStatusString(uint8_t status){ - if(status <= 7) return WIFI_STA_STATUS[status]; +String WiFiManager::getWLStatusString(uint8_t status) +{ + if (status <= 7) + return WIFI_STA_STATUS[status]; return FPSTR(S_NA); } -String WiFiManager::encryptionTypeStr(uint8_t authmode) { +String WiFiManager::encryptionTypeStr(uint8_t authmode) +{ // DEBUG_WM("enc_tye: ",authmode); return AUTH_MODE_NAMES[authmode]; } -String WiFiManager::getModeString(uint8_t mode){ - if(mode <= 3) return WIFI_MODES[mode]; +String WiFiManager::getModeString(uint8_t mode) +{ + if (mode <= 3) + return WIFI_MODES[mode]; return FPSTR(S_NA); } -bool WiFiManager::WiFiSetCountry(){ +bool WiFiManager::WiFiSetCountry() +{ bool ret = false; - #ifdef ESP32 +#ifdef ESP32 // @todo check if wifi is init, no idea how, doesnt seem to be exposed - if(_wificountry == "") return ret; // skip not set - else if(WiFi.getMode() == WIFI_MODE_NULL); // exception if wifi not init! - else if(_wificountry == "US") ret = esp_wifi_set_country(&WM_COUNTRY_US) == ESP_OK; - else if(_wificountry == "JP") ret = esp_wifi_set_country(&WM_COUNTRY_JP) == ESP_OK; - else if(_wificountry == "CN") ret = esp_wifi_set_country(&WM_COUNTRY_CN) == ESP_OK; - else DEBUG_WM(DEBUG_ERROR,"[ERROR] country code not found"); - - if(ret) DEBUG_WM(DEBUG_VERBOSE,"esp_wifi_set_country: " + _wificountry); - else DEBUG_WM(DEBUG_ERROR,"[ERROR] esp_wifi_set_country failed"); - #endif + if (_wificountry == "") + return ret; // skip not set + else if (WiFi.getMode() == WIFI_MODE_NULL) + ; // exception if wifi not init! + else if (_wificountry == "US") + ret = esp_wifi_set_country(&WM_COUNTRY_US) == ESP_OK; + else if (_wificountry == "JP") + ret = esp_wifi_set_country(&WM_COUNTRY_JP) == ESP_OK; + else if (_wificountry == "CN") + ret = esp_wifi_set_country(&WM_COUNTRY_CN) == ESP_OK; + else + DEBUG_WM(DEBUG_ERROR, "[ERROR] country code not found"); + + if (ret) + DEBUG_WM(DEBUG_VERBOSE, "esp_wifi_set_country: " + _wificountry); + else + DEBUG_WM(DEBUG_ERROR, "[ERROR] esp_wifi_set_country failed"); +#endif return ret; } - -// set mode ignores WiFi.persistent -bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { - bool ret; - #ifdef ESP8266 - if((wifi_get_opmode() == (uint8) m ) && !persistent) { - return true; - } - ETS_UART_INTR_DISABLE(); - if(persistent) ret = wifi_set_opmode(m); - else ret = wifi_set_opmode_current(m); - ETS_UART_INTR_ENABLE(); - return ret; - #elif defined(ESP32) - if(persistent && esp32persistent) WiFi.persistent(true); - ret = WiFi.mode(m); // @todo persistent check persistant mode , NI - if(persistent && esp32persistent) WiFi.persistent(false); - return ret; - #endif +// set mode ignores WiFi.persistent +bool WiFiManager::WiFi_Mode(WiFiMode_t m, bool persistent) +{ + bool ret; +#ifdef ESP8266 + if ((wifi_get_opmode() == (uint8)m) && !persistent) + { + return true; + } + ETS_UART_INTR_DISABLE(); + if (persistent) + ret = wifi_set_opmode(m); + else + ret = wifi_set_opmode_current(m); + ETS_UART_INTR_ENABLE(); + return ret; +#elif defined(ESP32) + if (persistent && esp32persistent) + WiFi.persistent(true); + ret = WiFi.mode(m); // @todo persistent check persistant mode , NI + if (persistent && esp32persistent) + WiFi.persistent(false); + return ret; +#endif } -bool WiFiManager::WiFi_Mode(WiFiMode_t m) { - return WiFi_Mode(m,false); +bool WiFiManager::WiFi_Mode(WiFiMode_t m) +{ + return WiFi_Mode(m, false); } // sta disconnect without persistent -bool WiFiManager::WiFi_Disconnect() { - #ifdef ESP8266 - if((WiFi.getMode() & WIFI_STA) != 0) { - bool ret; - DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); - ETS_UART_INTR_DISABLE(); // @todo probably not needed - ret = wifi_station_disconnect(); - ETS_UART_INTR_ENABLE(); - return ret; - } - #elif defined(ESP32) - DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); - return WiFi.disconnect(); // not persistent atm - #endif - return false; +bool WiFiManager::WiFi_Disconnect() +{ +#ifdef ESP8266 + if ((WiFi.getMode() & WIFI_STA) != 0) + { + bool ret; + DEBUG_WM(DEBUG_DEV, F("WIFI station disconnect")); + ETS_UART_INTR_DISABLE(); // @todo probably not needed + ret = wifi_station_disconnect(); + ETS_UART_INTR_ENABLE(); + return ret; + } +#elif defined(ESP32) + DEBUG_WM(DEBUG_DEV, F("WIFI station disconnect")); + return WiFi.disconnect(); // not persistent atm +#endif + return false; } // toggle STA without persistent -bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { - DEBUG_WM(DEBUG_DEV,F("WiFi station enable")); - #ifdef ESP8266 - WiFiMode_t newMode; - WiFiMode_t currentMode = WiFi.getMode(); - bool isEnabled = (currentMode & WIFI_STA) != 0; - if(enable) newMode = (WiFiMode_t)(currentMode | WIFI_STA); - else newMode = (WiFiMode_t)(currentMode & (~WIFI_STA)); +bool WiFiManager::WiFi_enableSTA(bool enable, bool persistent) +{ + DEBUG_WM(DEBUG_DEV, F("WiFi station enable")); +#ifdef ESP8266 + WiFiMode_t newMode; + WiFiMode_t currentMode = WiFi.getMode(); + bool isEnabled = (currentMode & WIFI_STA) != 0; + if (enable) + newMode = (WiFiMode_t)(currentMode | WIFI_STA); + else + newMode = (WiFiMode_t)(currentMode & (~WIFI_STA)); - if((isEnabled != enable) || persistent) { - if(enable) { - if(persistent) DEBUG_WM(DEBUG_DEV,F("enableSTA PERSISTENT ON")); - return WiFi_Mode(newMode,persistent); - } else { - return WiFi_Mode(newMode,persistent); - } - } else { - return true; - } - #elif defined(ESP32) - bool ret; - if(persistent && esp32persistent) WiFi.persistent(true); - ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform - if(persistent && esp32persistent) WiFi.persistent(false); - return ret; - #endif + if ((isEnabled != enable) || persistent) + { + if (enable) + { + if (persistent) + DEBUG_WM(DEBUG_DEV, F("enableSTA PERSISTENT ON")); + return WiFi_Mode(newMode, persistent); + } + else + { + return WiFi_Mode(newMode, persistent); + } + } + else + { + return true; + } +#elif defined(ESP32) + bool ret; + if (persistent && esp32persistent) + WiFi.persistent(true); + ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform + if (persistent && esp32persistent) + WiFi.persistent(false); + return ret; +#endif } -bool WiFiManager::WiFi_enableSTA(bool enable) { - return WiFi_enableSTA(enable,false); +bool WiFiManager::WiFi_enableSTA(bool enable) +{ + return WiFi_enableSTA(enable, false); } -bool WiFiManager::WiFi_eraseConfig() { - #ifdef ESP8266 - #ifndef WM_FIXERASECONFIG - return ESP.eraseConfig(); - #else - // erase config BUG replacement - // https://github.com/esp8266/Arduino/pull/3635 - const size_t cfgSize = 0x4000; - size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; +bool WiFiManager::WiFi_eraseConfig() +{ +#ifdef ESP8266 +#ifndef WM_FIXERASECONFIG + return ESP.eraseConfig(); +#else + // erase config BUG replacement + // https://github.com/esp8266/Arduino/pull/3635 + const size_t cfgSize = 0x4000; + size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; - for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) { - if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) { - return false; - } - } - return true; - #endif - #elif defined(ESP32) - bool ret; - WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! - WiFi.persistent(true); - ret = WiFi.disconnect(true,true); - WiFi.persistent(false); - return ret; - #endif + for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) + { + if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) + { + return false; + } + } + return true; +#endif +#elif defined(ESP32) + bool ret; + WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! + WiFi.persistent(true); + ret = WiFi.disconnect(true, true); + WiFi.persistent(false); + return ret; +#endif } -uint8_t WiFiManager::WiFi_softap_num_stations(){ - #ifdef ESP8266 - return wifi_softap_get_station_num(); - #elif defined(ESP32) - return WiFi.softAPgetStationNum(); - #endif +uint8_t WiFiManager::WiFi_softap_num_stations() +{ +#ifdef ESP8266 + return wifi_softap_get_station_num(); +#elif defined(ESP32) + return WiFi.softAPgetStationNum(); +#endif } -bool WiFiManager::WiFi_hasAutoConnect(){ +bool WiFiManager::WiFi_hasAutoConnect() +{ return WiFi_SSID() != ""; } -String WiFiManager::WiFi_SSID(){ - #ifdef ESP8266 - return WiFi.SSID(); - #elif defined(ESP32) - //@todo , workaround only when not connected - wifi_config_t conf; - esp_wifi_get_config(WIFI_IF_STA, &conf); - return String(reinterpret_cast(conf.sta.ssid)); - #endif +String WiFiManager::WiFi_SSID() +{ +#ifdef ESP8266 + return WiFi.SSID(); +#elif defined(ESP32) + //@todo , workaround only when not connected + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.ssid)); +#endif } #ifdef ESP32 -void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ - DEBUG_WM(DEBUG_VERBOSE,"[EVENT]",event); - if(event == SYSTEM_EVENT_STA_DISCONNECTED){ - DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON:",info.disconnected.reason); - if(info.disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.disconnected.reason == WIFI_REASON_AUTH_FAIL){ - _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail - } else _lastconxresulttmp = WiFi.status(); - if(info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON: NO_AP_FOUND"); - #ifdef esp32autoreconnect - DEBUG_WM(DEBUG_VERBOSE,"[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); - WiFi.reconnect(); - #endif +void WiFiManager::WiFiEvent(WiFiEvent_t event, system_event_info_t info) +{ + DEBUG_WM(DEBUG_VERBOSE, "[EVENT]", event); + if (event == SYSTEM_EVENT_STA_DISCONNECTED) + { + DEBUG_WM(DEBUG_VERBOSE, "[EVENT] WIFI_REASON:", info.disconnected.reason); + if (info.disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.disconnected.reason == WIFI_REASON_AUTH_FAIL) + { + _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail + } + else + _lastconxresulttmp = WiFi.status(); + if (info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) + DEBUG_WM(DEBUG_VERBOSE, "[EVENT] WIFI_REASON: NO_AP_FOUND"); +#ifdef esp32autoreconnect + DEBUG_WM(DEBUG_VERBOSE, "[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); + WiFi.reconnect(); +#endif } - else if(event == SYSTEM_EVENT_SCAN_DONE){ + else if (event == SYSTEM_EVENT_SCAN_DONE) + { uint16_t scans = WiFi.scanComplete(); WiFi_scanComplete(scans); } } #endif -void WiFiManager::WiFi_autoReconnect(){ - #ifdef ESP8266 - WiFi.setAutoReconnect(_wifiAutoReconnect); - #elif defined(ESP32) - // if(_wifiAutoReconnect){ - DEBUG_WM(DEBUG_VERBOSE,"ESP32 event handler enabled"); - using namespace std::placeholders; - WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); - // } - #endif +void WiFiManager::WiFi_autoReconnect() +{ +#ifdef ESP8266 + WiFi.setAutoReconnect(_wifiAutoReconnect); +#elif defined(ESP32) + // if(_wifiAutoReconnect){ + DEBUG_WM(DEBUG_VERBOSE, "ESP32 event handler enabled"); + using namespace std::placeholders; + WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent, this, _1, _2)); + // } +#endif } diff --git a/WiFiManager.h b/WiFiManager.h index fa18c1c..025ed54 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -193,6 +193,8 @@ class WiFiManager void setAPCallback( std::function func ); //called when settings have been changed and connection was successful void setSaveConfigCallback( std::function func ); + //called when settings before have been changed and connection was successful + void setPreSaveConfigCallback( std::function func ); //adds a custom parameter, returns false on failure bool addParameter(WiFiManagerParameter *p); //if this is set, it will exit after config, even if connection is unsuccessful. @@ -461,6 +463,7 @@ class WiFiManager // callbacks std::function _apcallback; std::function _savecallback; + std::function _presavecallback; template auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { From f9d1c9bd6f46502455b97a92b5d797a7d529a275 Mon Sep 17 00:00:00 2001 From: ayeah Date: Mon, 17 Sep 2018 01:19:18 +0700 Subject: [PATCH 112/146] reformat --- WiFiManager.cpp | 2614 ++++++++++++++++++++--------------------------- 1 file changed, 1084 insertions(+), 1530 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 9fd7539..85cc3df 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -22,103 +22,84 @@ uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS; * -------------------------------------------------------------------------------- **/ -WiFiManagerParameter::WiFiManagerParameter(const char *custom) -{ - _id = NULL; - _placeholder = NULL; - _length = 1; - _value = NULL; +WiFiManagerParameter::WiFiManagerParameter(const char *custom) { + _id = NULL; + _placeholder = NULL; + _length = 1; + _value = NULL; _labelPlacement = WFM_LABEL_BEFORE; - _customHTML = custom; + _customHTML = custom; } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder) -{ +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder) { init(id, placeholder, "", 0, "", WFM_LABEL_BEFORE); } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length) -{ +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length) { init(id, placeholder, defaultValue, length, "", WFM_LABEL_BEFORE); } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom) -{ +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom) { init(id, placeholder, defaultValue, length, custom, WFM_LABEL_BEFORE); } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) -{ +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) { init(id, placeholder, defaultValue, length, custom, labelPlacement); } -void WiFiManagerParameter::init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) -{ - _id = id; - _placeholder = placeholder; +void WiFiManagerParameter::init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) { + _id = id; + _placeholder = placeholder; _labelPlacement = labelPlacement; - _customHTML = custom; - setValue(defaultValue, length); + _customHTML = custom; + setValue(defaultValue,length); } -WiFiManagerParameter::~WiFiManagerParameter() -{ - if (_value != NULL) - { +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 + _length=0; // setting length 0, ideally the entire parameter should be removed, or added to wifimanager scope so it follows } -void WiFiManagerParameter::setValue(const char *defaultValue, int length) -{ - if (!_id) - { +void WiFiManagerParameter::setValue(const char *defaultValue, int length) { + if(!_id){ // Serial.println("cannot set value of this parameter"); return; } - _length = length; + _length = length; int deflength = strlen(defaultValue); // length actual - // use the defult length if it's longer, + // use the defult length if it's longer, // @todo consider it might be useful to fail, so user knows they were wrong - if (_length < length) - { + if(_length < length){ // Serial.println("defaultValue length mismatch"); _length = deflength; } _value = new char[_length + 1]; - for (int i = 0; i < _length + 1; i++) - { + for (int i = 0; i < _length + 1; i++) { _value[i] = 0; } - if (defaultValue != NULL) - { + if (defaultValue != NULL) { strncpy(_value, defaultValue, _length); _value[_length] = '\0'; // explicit null } } -const char *WiFiManagerParameter::getValue() -{ +const char* WiFiManagerParameter::getValue() { return _value; } -const char *WiFiManagerParameter::getID() -{ +const char* WiFiManagerParameter::getID() { return _id; } -const char *WiFiManagerParameter::getPlaceholder() -{ +const char* WiFiManagerParameter::getPlaceholder() { return _placeholder; } -int WiFiManagerParameter::getValueLength() -{ +int WiFiManagerParameter::getValueLength() { return _length; } -int WiFiManagerParameter::getLabelPlacement() -{ +int WiFiManagerParameter::getLabelPlacement() { return _labelPlacement; } -const char *WiFiManagerParameter::getCustomHTML() -{ +const char* WiFiManagerParameter::getCustomHTML() { return _customHTML; } @@ -127,54 +108,45 @@ const char *WiFiManagerParameter::getCustomHTML() * @access public * @param {[type]} WiFiManagerParameter *p [description] */ -bool WiFiManager::addParameter(WiFiManagerParameter *p) -{ +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"); + 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 *)); + 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) - { + 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(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) - { + if (new_params != NULL) { _params = new_params; - } - else - { - DEBUG_WM(DEBUG_ERROR, "[ERROR] failed to realloc params, size not increased!"); + } 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()); + + DEBUG_WM(DEBUG_VERBOSE,"Added Parameter:",p->getID()); return true; } @@ -185,62 +157,51 @@ bool WiFiManager::addParameter(WiFiManagerParameter *p) **/ // constructors -WiFiManager::WiFiManager(Stream &consolePort) : _debugPort(consolePort) -{ +WiFiManager::WiFiManager(Stream& consolePort):_debugPort(consolePort){ WiFiManagerInit(); } -WiFiManager::WiFiManager() : WiFiManager(Serial) -{ +WiFiManager::WiFiManager():WiFiManager(Serial) { } -void WiFiManager::WiFiManagerInit() -{ +void WiFiManager::WiFiManagerInit(){ setMenu(_menuIdsDefault); - if (_debug && _debugLevel > DEBUG_DEV) - debugPlatformInfo(); + if(_debug && _debugLevel > DEBUG_DEV) debugPlatformInfo(); _max_params = WIFI_MANAGER_MAX_PARAMS; } // destructor -WiFiManager::~WiFiManager() -{ +WiFiManager::~WiFiManager() { _end(); // parameters // @todo belongs to wifimanagerparameter - if (_params != NULL) - { - DEBUG_WM(DEBUG_DEV, F("freeing allocated params!")); + if (_params != NULL){ + DEBUG_WM(DEBUG_DEV,F("freeing allocated params!")); free(_params); _params = NULL; } - DEBUG_WM(DEBUG_DEV, F("unloading")); + DEBUG_WM(DEBUG_DEV,F("unloading")); } -void WiFiManager::_begin() -{ - if (_hasBegun) - return; +void WiFiManager::_begin(){ + if(_hasBegun) return; _usermode = WiFi.getMode(); -#ifndef ESP32 + #ifndef ESP32 WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites -#endif + #endif } -void WiFiManager::_end() -{ - if (_userpersistent) - WiFi.persistent(true); // reenable persistent, there is no getter we rely on _userpersistent +void WiFiManager::_end(){ + 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 = _wifissidprefix + "_" + String(WIFI_getChipId(), HEX); +boolean WiFiManager::autoConnect() { + String ssid = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); return autoConnect(ssid.c_str(), NULL); } @@ -251,25 +212,22 @@ boolean WiFiManager::autoConnect() * @param {[type]} char const *apPassword [description] * @return {[type]} [description] */ -boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) -{ +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)) - { + if(!WiFi.enableSTA(true)){ // handle failure mode Brownout detector etc. - DEBUG_WM(DEBUG_ERROR, "[FATAL] Unable to enable wifi!"); + 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 + #ifdef ESP32 + if(esp32persistent) WiFi.persistent(false); // disable persistent for esp32 after esp_wifi_start or else saves wont work + #endif _usermode = WIFI_STA; @@ -279,76 +237,67 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) WiFi_autoReconnect(); // set hostname before stating - if ((String)_hostname != "") - { - DEBUG_WM(DEBUG_VERBOSE, "Setting hostname:", _hostname); + 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")); + #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 + // 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) - { + if (WiFi.status() == WL_CONNECTED){ connected = true; DEBUG_WM(F("AutoConnect: ESP Already Connected")); setSTAConfig(); } - if (connected || connectWifi("", "") == WL_CONNECTED) - { + if(connected || connectWifi("", "") == WL_CONNECTED){ //connected DEBUG_WM(F("AutoConnect: SUCCESS")); - DEBUG_WM(F("STA IP Address:"), WiFi.localIP()); + 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 + 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) - { + if (!_enableConfigPortal) { return false; } @@ -359,88 +308,71 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) } // CONFIG PORTAL -bool WiFiManager::startAP() -{ +bool WiFiManager::startAP(){ bool ret = true; - DEBUG_WM(F("StartAP with SSID: "), _apName); + DEBUG_WM(F("StartAP with SSID: "),_apName); // do AP callback if set - if (_apcallback != NULL) - { + if ( _apcallback != NULL) { _apcallback(this); } // setup optional soft AP static ip config - if (_ap_static_ip) - { + 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!"); + if(!WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn)){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] softAPConfig failed!"); } } -#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 + #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 - if (_channelSync) - { - DEBUG_WM(DEBUG_VERBOSE, "Starting AP on channel:", WiFi.channel()); - } + if(_channelSync){ + DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",WiFi.channel()); + } // start soft AP with password or anonymous - if (_apPassword != "") - { - if (_channelSync) - { - ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(), WiFi.channel()); + if (_apPassword != "") { + if(_channelSync){ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),WiFi.channel()); + } + else{ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str());//password option } - else - { - ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str()); //password option - } - } - else - { - DEBUG_WM(DEBUG_VERBOSE, F("AP has anonymous access!")); - if (_channelSync) - { - ret = WiFi.softAP(_apName.c_str(), "", WiFi.channel()); - } - else - { + } else { + DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!")); + if(_channelSync){ + ret = WiFi.softAP(_apName.c_str(),"",WiFi.channel()); + } + else{ ret = WiFi.softAP(_apName.c_str()); - } + } } - if (_debugLevel > DEBUG_DEV) - debugSoftAPConfig(); + if(_debugLevel > DEBUG_DEV) debugSoftAPConfig(); - if (!ret) - DEBUG_WM(DEBUG_ERROR, "[ERROR] There was a problem starting the AP"); + 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()); + 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 + // 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; } @@ -450,10 +382,8 @@ bool WiFiManager::startAP() * @access public * @return {[type]} [description] */ -void WiFiManager::startWebPortal() -{ - if (configPortalActive || webPortalActive) - return; +void WiFiManager::startWebPortal() { + if(configPortalActive || webPortalActive) return; setupConfigPortal(); webPortalActive = true; } @@ -463,56 +393,44 @@ void WiFiManager::startWebPortal() * @access public * @return {[type]} [description] */ -void WiFiManager::stopWebPortal() -{ - if (!configPortalActive && !webPortalActive) - return; - DEBUG_WM(DEBUG_VERBOSE, F("Stopping Web Portal")); +void WiFiManager::stopWebPortal() { + if(!configPortalActive && !webPortalActive) return; + DEBUG_WM(DEBUG_VERBOSE,F("Stopping Web Portal")); webPortalActive = false; stopConfigPortal(); } -boolean WiFiManager::configPortalHasTimeout() -{ +boolean WiFiManager::configPortalHasTimeout(){ - if (_configPortalTimeout == 0 || (_cpClientCheck && (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) - { + if(_configPortalTimeout == 0 || (_cpClientCheck && (WiFi_softap_num_stations() > 0))){ + if(millis() - timer > 30000){ timer = millis(); - DEBUG_WM(DEBUG_VERBOSE, F("Portal Timeout In"), (String)((_configPortalStart + _configPortalTimeout - millis()) / 1000) + (String)F(" seconds")); + 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; + return false; } -void WiFiManager::setupConfigPortal() -{ +void WiFiManager::setupConfigPortal() { DEBUG_WM(F("Starting Web Portal")); @@ -523,34 +441,32 @@ void WiFiManager::setupConfigPortal() /* 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()); + DEBUG_WM(DEBUG_DEV,"dns server started with ip: ",WiFi.softAPIP()); dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); /* 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_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->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")); + DEBUG_WM(DEBUG_VERBOSE,F("HTTP server started")); - if (_preloadwifiscan) - WiFi_scanNetworks(true, true); // preload wifiscan , async + if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan , async } -boolean WiFiManager::startConfigPortal() -{ - String ssid = _wifissidprefix + "_" + String(WIFI_getChipId(), HEX); +boolean WiFiManager::startConfigPortal() { + String ssid = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); return startConfigPortal(ssid.c_str(), NULL); } @@ -561,30 +477,25 @@ boolean WiFiManager::startConfigPortal() * @param {[type]} char const *apPassword [description] * @return {[type]} [description] */ -boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) -{ +boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { _begin(); //setup AP - _apName = apName; // @todo check valid apname ? + _apName = apName; // @todo check valid apname ? _apPassword = apPassword; - - if (_apName == "") - _apName = _wifissidprefix + "_" + String(WIFI_getChipId(), HEX); - if (!validApPassword()) - return false; - + + if(_apName == "") _apName = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); + 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` + 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")); + DEBUG_WM(DEBUG_VERBOSE,F("Disabling STA")); } - else - { + 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); } @@ -597,29 +508,26 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswor _configPortalStart = millis(); // start access point - DEBUG_WM(DEBUG_VERBOSE, F("Enabling AP")); + DEBUG_WM(DEBUG_VERBOSE,F("Enabling AP")); startAP(); WiFiSetCountry(); // init configportal - DEBUG_WM(DEBUG_DEV, F("setupConfigPortal")); + DEBUG_WM(DEBUG_DEV,F("setupConfigPortal")); setupConfigPortal(); - if (!_configPortalIsBlocking) - { - DEBUG_WM(DEBUG_VERBOSE, F("Config Portal Running, non blocking/processing")); + 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...")); + DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, blocking, waiting for clients...")); // blocking loop waiting for config - while (1) - { + while(1){ // if timed out or abort, break - if (configPortalHasTimeout() || abort) - { - DEBUG_WM(DEBUG_DEV, F("configportal abort")); + if(configPortalHasTimeout() || abort){ + DEBUG_WM(DEBUG_DEV,F("configportal abort")); stopConfigPortal(); result = abort ? portalAbortResult : portalTimeoutResult; // false, false break; @@ -628,16 +536,15 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswor state = processConfigPortal(); // status change, break - if (state != WL_IDLE_STATUS) - { - result = (state == WL_CONNECTED); // true if connected - break; + if(state != WL_IDLE_STATUS){ + result = (state == WL_CONNECTED); // true if connected + break; } yield(); // watchdog } - DEBUG_WM(DEBUG_NOTIFY, F("config portal exiting")); + DEBUG_WM(DEBUG_NOTIFY,F("config portal exiting")); return result; } @@ -646,82 +553,70 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswor * @access public * @return {[type]} [description] */ -boolean WiFiManager::process() -{ - if (webPortalActive || (configPortalActive && !_configPortalIsBlocking)) - { - uint8_t state = processConfigPortal(); - return state == WL_CONNECTED; - } - return false; +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(); +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. + // 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) - { + // 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()); - DEBUG_WM(F("Connect to new AP [SUCCESS]")); - DEBUG_WM(F("Got IP Address:")); - DEBUG_WM(WiFi.localIP()); - - if (_savecallback != NULL) - { + if ( _savecallback != NULL) { + _savecallback(); + } + stopConfigPortal(); + 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 ( _savecallback != NULL) { _savecallback(); } stopConfigPortal(); - return WL_CONNECTED; // CONNECT SUCCESS + 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")); } - 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 (_savecallback != NULL) - { - _savecallback(); - } - stopConfigPortal(); - 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; + return WL_IDLE_STATUS; } /** @@ -729,10 +624,8 @@ uint8_t WiFiManager::processConfigPortal() * @access public * @return {[type]} [description] */ -boolean WiFiManager::stopConfigPortal() -{ - if (webPortalActive) - return false; +boolean WiFiManager::stopConfigPortal(){ + if(webPortalActive) return false; //DNS handler dnsServer->processNextRequest(); @@ -747,29 +640,26 @@ boolean WiFiManager::stopConfigPortal() WiFi.scanDelete(); // free wifi scan results - if (!configPortalActive) - return false; + 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")); + 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")); + if(!ret)DEBUG_WM(DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); delay(1000); - DEBUG_WM(DEBUG_VERBOSE, "restoring usermode", getModeString(_usermode)); + 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) - { + 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 Reconnect, was idle"); } - DEBUG_WM(DEBUG_VERBOSE, "wifi status:", getWLStatusString(WiFi.status())); - DEBUG_WM(DEBUG_VERBOSE, "wifi mode:", getModeString(WiFi.getMode())); + DEBUG_WM(DEBUG_VERBOSE,"wifi status:",getWLStatusString(WiFi.status())); + DEBUG_WM(DEBUG_VERBOSE,"wifi mode:",getModeString(WiFi.getMode())); configPortalActive = false; _end(); return ret; @@ -778,63 +668,53 @@ boolean WiFiManager::stopConfigPortal() // @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 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 + 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) - { + 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 { + connRes = waitForConnectResult(0); } } - else - { + else { // connect using saved ssid if there is one - if (WiFi_hasAutoConnect()) - { + if (WiFi_hasAutoConnect()) { wifiConnectDefault(); connRes = waitForConnectResult(); } - else - { + else { DEBUG_WM(F("No saved credentials, skipping wifi")); } } - DEBUG_WM(DEBUG_VERBOSE, F("Connection result:"), getWLStatusString(connRes)); + 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 == "") - { + if (_tryWPS && connRes != WL_CONNECTED && pass == "") { startWPS(); // should be connected at the end of WPS connRes = waitForConnectResult(); } #endif - if (connRes != WL_SCAN_COMPLETED) - { + if(connRes != WL_SCAN_COMPLETED){ updateConxResult(connRes); } @@ -848,16 +728,14 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) * @param String pass * @return bool success */ -bool WiFiManager::wifiConnectNew(String ssid, String pass) -{ +bool WiFiManager::wifiConnectNew(String ssid, String pass){ bool ret = false; - DEBUG_WM(F("Connecting to new AP:"), ssid); - WiFi_enableSTA(true, storeSTAmode); // storeSTAmode will also toggle STA on in default opmode (persistent) if true (default) + DEBUG_WM(F("Connecting to new AP:"),ssid); + 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"); + if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed"); return ret; } @@ -866,84 +744,68 @@ bool WiFiManager::wifiConnectNew(String ssid, String pass) * @since dev * @return bool success */ -bool WiFiManager::wifiConnectDefault() -{ +bool WiFiManager::wifiConnectDefault(){ bool ret = false; - DEBUG_WM(F("Connecting to saved AP:"), WiFi_SSID()); - ret = WiFi_enableSTA(true, storeSTAmode); - if (!ret) - DEBUG_WM(DEBUG_ERROR, "[ERROR] wifi enableSta failed"); + DEBUG_WM(F("Connecting to saved AP:"),WiFi_SSID()); + 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"); + 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() -{ +bool WiFiManager::setSTAConfig(){ bool ret = true; - if (_sta_static_ip) - { - if (_sta_static_dns) - { - DEBUG_WM(DEBUG_VERBOSE, F("Custom STA IP/GW/Subnet/DNS")); + if (_sta_static_ip) { + if(_sta_static_dns) { + DEBUG_WM(DEBUG_VERBOSE,F("Custom STA IP/GW/Subnet/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")); + 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")); + 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) -{ +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)); + #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")); + +uint8_t WiFiManager::waitForConnectResult() { + if(_connectTimeout > 0) DEBUG_WM(DEBUG_VERBOSE,_connectTimeout,F("ms connectTimeout set")); return waitForConnectResult(_connectTimeout); } @@ -952,27 +814,23 @@ uint8_t WiFiManager::waitForConnectResult() * @param uint16_t timeout in seconds * @return uint8_t WL Status */ -uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) -{ - if (timeout == 0) - { +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...")); + DEBUG_WM(DEBUG_VERBOSE,timeout,F("ms timeout, waiting for connect...")); uint8_t status = WiFi.status(); - - while (millis() < timeoutmillis) - { + + 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) - { + if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) { return status; } - DEBUG_WM(DEBUG_VERBOSE, F(".")); + DEBUG_WM (DEBUG_VERBOSE,F(".")); delay(100); } return status; @@ -980,20 +838,18 @@ uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) // WPS enabled? https://github.com/esp8266/Arduino/pull/4889 #ifdef NO_EXTRA_4K_HEAP -void WiFiManager::startWPS() -{ +void WiFiManager::startWPS() { DEBUG_WM(F("START WPS")); -#ifdef ESP8266 - WiFi.beginWPSConfig(); -#else - // @todo -#endif + #ifdef ESP8266 + WiFi.beginWPSConfig(); + #else + // @todo + #endif DEBUG_WM(F("END WPS")); } #endif -String WiFiManager::getHTTPHead(String title) -{ +String WiFiManager::getHTTPHead(String title){ String page; page += FPSTR(HTTP_HEAD_START); page.replace(FPSTR(T_v), title); @@ -1001,16 +857,14 @@ String WiFiManager::getHTTPHead(String title) page += FPSTR(HTTP_STYLE); page += _customHeadElement; - if (_bodyClass != "") - { + if(_bodyClass != ""){ String p = FPSTR(HTTP_HEAD_END); p.replace(FPSTR(T_c), _bodyClass); // add class str page += p; } - else - { + else { page += FPSTR(HTTP_HEAD_END); - } + } return page; } @@ -1018,23 +872,20 @@ String WiFiManager::getHTTPHead(String title) /** * HTTPD handler for page requests */ -void WiFiManager::handleRequest() -{ +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 +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 + 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(); @@ -1043,9 +894,8 @@ void WiFiManager::handleRoot() 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((unsigned)20000, true); // preload wifiscan throttled, async + // server->close(); // testing reliability fix for content length mismatches during mutiple flood hits WiFi_scanNetworks(); // preload wifiscan + if(_preloadwifiscan) WiFi_scanNetworks((unsigned)20000,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 @@ -1054,15 +904,13 @@ void WiFiManager::handleRoot() /** * HTTPD CALLBACK Wifi config page handler */ -void WiFiManager::handleWifi(boolean scan) -{ - DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Wifi")); +void WiFiManager::handleWifi(boolean scan) { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Wifi")); handleRequest(); String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi - if (scan) - { + if (scan) { // DEBUG_WM(DEBUG_DEV,"refresh flag:",server->hasArg(F("refresh"))); - WiFi_scanNetworks(server->hasArg(F("refresh")), false); //wifiscan, force if arg refresh + WiFi_scanNetworks(server->hasArg(F("refresh")),false); //wifiscan, force if arg refresh page += getScanItemOut(); } String pitem = ""; @@ -1077,8 +925,7 @@ void WiFiManager::handleWifi(boolean scan) page += getStaticOut(); page += FPSTR(HTTP_FORM_WIFI_END); - if (_paramsInWifi && _paramsCount > 0) - { + if(_paramsInWifi && _paramsCount>0){ page += FPSTR(HTTP_FORM_PARAM_HEAD); page += getParamOut(); } @@ -1091,15 +938,14 @@ void WiFiManager::handleWifi(boolean scan) 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")); + DEBUG_WM(DEBUG_DEV,F("Sent config page")); } /** * HTTPD CALLBACK Wifi param page handler */ -void WiFiManager::handleParam() -{ - DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Param")); +void WiFiManager::handleParam(){ + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Param")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleparam)); // @token titlewifi @@ -1117,17 +963,15 @@ void WiFiManager::handleParam() server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); - DEBUG_WM(DEBUG_DEV, F("Sent param page")); + DEBUG_WM(DEBUG_DEV,F("Sent param page")); } -String WiFiManager::getMenuOut() -{ - String page; - for (auto menuId : _menuIds) - { - if (((String)menuId == "param") && (_paramsCount == 0)) - continue; // no params set, omit params +String WiFiManager::getMenuOut(){ + String page; + + for(auto menuId :_menuIds ){ + if(((String)menuId == "param") && (_paramsCount == 0)) continue; // no params set, omit params page += HTTP_PORTAL_MENU[menuId]; } @@ -1139,253 +983,207 @@ String WiFiManager::getMenuOut() // WiFi_scanNetworks(force); // } -void WiFiManager::WiFi_scanComplete(int networksFound) -{ +void WiFiManager::WiFi_scanComplete(int networksFound){ _lastscan = millis(); _numNetworks = networksFound; - DEBUG_WM(DEBUG_VERBOSE, F("WiFi Scan ASYNC completed"), "in " + (String)(_lastscan - _startscan) + " ms"); - DEBUG_WM(DEBUG_VERBOSE, F("WiFi Scan ASYNC found:"), _numNetworks); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC completed"), "in "+(String)(_lastscan - _startscan)+" ms"); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC found:"),_numNetworks); } -bool WiFiManager::WiFi_scanNetworks() -{ - return WiFi_scanNetworks(false, false); +bool WiFiManager::WiFi_scanNetworks(){ + return WiFi_scanNetworks(false,false); } -bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime, bool async) -{ - return WiFi_scanNetworks(millis() - _lastscan > cachetime, async); +bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime,bool async){ + return WiFi_scanNetworks(millis()-_lastscan > cachetime,async); } -bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime) -{ - return WiFi_scanNetworks(millis() - _lastscan > cachetime, false); +bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime){ + return WiFi_scanNetworks(millis()-_lastscan > cachetime,false); } -bool WiFiManager::WiFi_scanNetworks(bool force, bool async) -{ - // DEBUG_WM(DEBUG_DEV,"scanNetworks async:",async == true); - // DEBUG_WM(DEBUG_DEV,_numNetworks,(millis()-_lastscan )); - // DEBUG_WM(DEBUG_DEV,"scanNetworks force:",force == true); - if (force || _numNetworks == 0 || (millis() - _lastscan > 60000)) - { - int8_t res; - _startscan = millis(); - if (async) - { - DEBUG_WM(DEBUG_VERBOSE, F("WiFi Scan ASYNC started")); -#ifdef ESP8266 -#ifndef WM_NOASYNC // no async available < 2.4.0 - using namespace std::placeholders; // for `_1` - WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete, this, _1)); -#else - res = WiFi.scanNetworks(); -#endif -#else - res = WiFi.scanNetworks(true); -#endif - return false; - } - else - { - res = WiFi.scanNetworks(); - } - if (res == WIFI_SCAN_FAILED) - DEBUG_WM(DEBUG_ERROR, "[ERROR] scan failed"); - else if (res == WIFI_SCAN_RUNNING) - { - DEBUG_WM(DEBUG_ERROR, "[ERROR] scan waiting"); - while (WiFi.scanComplete() == WIFI_SCAN_RUNNING) - { - DEBUG_WM(DEBUG_ERROR, "."); - delay(100); +bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ + // DEBUG_WM(DEBUG_DEV,"scanNetworks async:",async == true); + // DEBUG_WM(DEBUG_DEV,_numNetworks,(millis()-_lastscan )); + // DEBUG_WM(DEBUG_DEV,"scanNetworks force:",force == true); + if(force || _numNetworks == 0 || (millis()-_lastscan > 60000)){ + int8_t res; + _startscan = millis(); + if(async){ + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); + #ifdef ESP8266 + #ifndef WM_NOASYNC // no async available < 2.4.0 + using namespace std::placeholders; // for `_1` + WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); + #else + res = WiFi.scanNetworks(); + #endif + #else + res = WiFi.scanNetworks(true); + #endif + return false; } - _numNetworks = WiFi.scanComplete(); - } - else if (res >= 0) - _numNetworks = res; - _lastscan = millis(); - DEBUG_WM(DEBUG_VERBOSE, F("WiFi Scan completed"), "in " + (String)(_lastscan - _startscan) + " ms"); - return true; - } - else - DEBUG_WM(DEBUG_VERBOSE, "Scan is cached", (String)(millis() - _lastscan) + " ms ago"); - return false; + else{ + res = WiFi.scanNetworks(); + } + if(res == WIFI_SCAN_FAILED) DEBUG_WM(DEBUG_ERROR,"[ERROR] scan failed"); + else if(res == WIFI_SCAN_RUNNING){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] scan waiting"); + while(WiFi.scanComplete() == WIFI_SCAN_RUNNING){ + DEBUG_WM(DEBUG_ERROR,"."); + delay(100); + } + _numNetworks = WiFi.scanComplete(); + } + else if(res >=0 ) _numNetworks = res; + _lastscan = millis(); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); + return true; + } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+" ms ago"); + return false; } -String WiFiManager::WiFiManager::getScanItemOut() -{ - String page; +String WiFiManager::WiFiManager::getScanItemOut(){ + String page; - if (!_numNetworks) - WiFi_scanNetworks(); // scan in case this gets called before any scans + if(!_numNetworks) WiFi_scanNetworks(); // scan in case this gets called before any scans - int n = _numNetworks; - if (n == 0) - { - DEBUG_WM(F("No networks found")); - page += FPSTR(S_nonetworks); // @token nonetworks - } - else - { - DEBUG_WM(n, F("networks found")); - //sort networks - int indices[n]; - for (int i = 0; i < n; i++) - { - indices[i] = i; - } + int n = _numNetworks; + if (n == 0) { + DEBUG_WM(F("No networks found")); + page += FPSTR(S_nonetworks); // @token nonetworks + } + else { + DEBUG_WM(n,F("networks found")); + //sort networks + int indices[n]; + for (int i = 0; i < n; i++) { + indices[i] = i; + } - // RSSI SORT - for (int i = 0; i < n; i++) - { - for (int j = i + 1; j < n; j++) - { - if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) - { - std::swap(indices[i], indices[j]); + // RSSI SORT + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) { + std::swap(indices[i], indices[j]); + } } } - } - /* test std:sort + /* test std:sort std::sort(indices, indices + n, [](const int & a, const int & b) -> bool { return WiFi.RSSI(a) > WiFi.RSSI(b); }); */ - // remove duplicates ( must be RSSI sorted ) - if (_removeDuplicateAPs) - { - String cssid; - for (int i = 0; i < n; i++) - { - if (indices[i] == -1) - continue; - cssid = WiFi.SSID(indices[i]); - for (int j = i + 1; j < n; j++) - { - if (cssid == WiFi.SSID(indices[j])) - { - DEBUG_WM(DEBUG_VERBOSE, F("DUP AP:"), WiFi.SSID(indices[j])); - indices[j] = -1; // set dup aps to index -1 + // remove duplicates ( must be RSSI sorted ) + if (_removeDuplicateAPs) { + String cssid; + for (int i = 0; i < n; i++) { + if (indices[i] == -1) continue; + cssid = WiFi.SSID(indices[i]); + for (int j = i + 1; j < n; j++) { + if (cssid == WiFi.SSID(indices[j])) { + DEBUG_WM(DEBUG_VERBOSE,F("DUP AP:"),WiFi.SSID(indices[j])); + indices[j] = -1; // set dup aps to index -1 + } } } } - } - // token precheck, to speed up replacements on large ap lists - String HTTP_ITEM_STR = FPSTR(HTTP_ITEM); + // token precheck, to speed up replacements on large ap lists + String HTTP_ITEM_STR = FPSTR(HTTP_ITEM); - // toggle icons with percentage - HTTP_ITEM_STR.replace("{qp}", FPSTR(HTTP_ITEM_QP)); - HTTP_ITEM_STR.replace("{h}", _scanDispOptions ? "" : "h"); - HTTP_ITEM_STR.replace("{qi}", FPSTR(HTTP_ITEM_QI)); - HTTP_ITEM_STR.replace("{h}", _scanDispOptions ? "h" : ""); + // toggle icons with percentage + HTTP_ITEM_STR.replace("{qp}", FPSTR(HTTP_ITEM_QP)); + HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "" : "h"); + HTTP_ITEM_STR.replace("{qi}", FPSTR(HTTP_ITEM_QI)); + HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "h" : ""); + + // set token precheck flags + bool tok_r = HTTP_ITEM_STR.indexOf(FPSTR(T_r)) > 0; + bool tok_R = HTTP_ITEM_STR.indexOf(FPSTR(T_R)) > 0; + bool tok_e = HTTP_ITEM_STR.indexOf(FPSTR(T_e)) > 0; + bool tok_q = HTTP_ITEM_STR.indexOf(FPSTR(T_q)) > 0; + bool tok_i = HTTP_ITEM_STR.indexOf(FPSTR(T_i)) > 0; + + //display networks in page + for (int i = 0; i < n; i++) { + if (indices[i] == -1) continue; // skip dups - // set token precheck flags - bool tok_r = HTTP_ITEM_STR.indexOf(FPSTR(T_r)) > 0; - bool tok_R = HTTP_ITEM_STR.indexOf(FPSTR(T_R)) > 0; - bool tok_e = HTTP_ITEM_STR.indexOf(FPSTR(T_e)) > 0; - bool tok_q = HTTP_ITEM_STR.indexOf(FPSTR(T_q)) > 0; - bool tok_i = HTTP_ITEM_STR.indexOf(FPSTR(T_i)) > 0; + DEBUG_WM(DEBUG_VERBOSE,F("AP: "),(String)WiFi.RSSI(indices[i]) + " " + (String)WiFi.SSID(indices[i])); - //display networks in page - for (int i = 0; i < n; i++) - { - if (indices[i] == -1) - continue; // skip dups + int rssiperc = getRSSIasQuality(WiFi.RSSI(indices[i])); + uint8_t enc_type = WiFi.encryptionType(indices[i]); - DEBUG_WM(DEBUG_VERBOSE, F("AP: "), (String)WiFi.RSSI(indices[i]) + " " + (String)WiFi.SSID(indices[i])); - - int rssiperc = getRSSIasQuality(WiFi.RSSI(indices[i])); - uint8_t enc_type = WiFi.encryptionType(indices[i]); - - if (_minimumQuality == -1 || _minimumQuality < rssiperc) - { - String item = HTTP_ITEM_STR; - item.replace(FPSTR(T_v), htmlEntities(WiFi.SSID(indices[i]))); // ssid no encoding - if (tok_e) - item.replace(FPSTR(T_e), encryptionTypeStr(enc_type)); - if (tok_r) - item.replace(FPSTR(T_r), (String)rssiperc); // rssi percentage 0-100 - if (tok_R) - item.replace(FPSTR(T_R), (String)WiFi.RSSI(indices[i])); // rssi db - if (tok_q) - item.replace(FPSTR(T_q), (String)round(map(rssiperc, 0, 100, 1, 4))); //quality icon 1-4 - if (tok_i) - { - if (enc_type != WM_WIFIOPEN) - { - item.replace(FPSTR(T_i), F("l")); - } - else - { - item.replace(FPSTR(T_i), ""); + if (_minimumQuality == -1 || _minimumQuality < rssiperc) { + String item = HTTP_ITEM_STR; + item.replace(FPSTR(T_v), htmlEntities(WiFi.SSID(indices[i]))); // ssid no encoding + if(tok_e) item.replace(FPSTR(T_e), encryptionTypeStr(enc_type)); + if(tok_r) item.replace(FPSTR(T_r), (String)rssiperc); // rssi percentage 0-100 + if(tok_R) item.replace(FPSTR(T_R), (String)WiFi.RSSI(indices[i])); // rssi db + if(tok_q) item.replace(FPSTR(T_q), (String)round(map(rssiperc,0,100,1,4))); //quality icon 1-4 + if(tok_i){ + if (enc_type != WM_WIFIOPEN) { + item.replace(FPSTR(T_i), F("l")); + } else { + item.replace(FPSTR(T_i), ""); + } } + //DEBUG_WM(item); + page += item; + delay(0); + } else { + DEBUG_WM(DEBUG_VERBOSE,F("Skipping , does not meet _minimumQuality")); } - //DEBUG_WM(item); - page += item; - delay(0); - } - else - { - DEBUG_WM(DEBUG_VERBOSE, F("Skipping , does not meet _minimumQuality")); + } + page += FPSTR(HTTP_BR); } - page += FPSTR(HTTP_BR); - } - return page; + return page; } -String WiFiManager::getIpForm(String id, String title, String value) -{ - String item = FPSTR(HTTP_FORM_LABEL); - item += FPSTR(HTTP_FORM_PARAM); - item.replace(FPSTR(T_i), id); - item.replace(FPSTR(T_n), id); - item.replace(FPSTR(T_p), FPSTR(T_t)); - // item.replace(FPSTR(T_p), default); - item.replace(FPSTR(T_t), title); - item.replace(FPSTR(T_l), F("15")); - item.replace(FPSTR(T_v), value); - item.replace(FPSTR(T_c), ""); - return item; +String WiFiManager::getIpForm(String id, String title, String value){ + String item = FPSTR(HTTP_FORM_LABEL); + item += FPSTR(HTTP_FORM_PARAM); + item.replace(FPSTR(T_i), id); + item.replace(FPSTR(T_n), id); + item.replace(FPSTR(T_p), FPSTR(T_t)); + // item.replace(FPSTR(T_p), default); + item.replace(FPSTR(T_t), title); + item.replace(FPSTR(T_l), F("15")); + item.replace(FPSTR(T_v), value); + item.replace(FPSTR(T_c), ""); + return item; } -String WiFiManager::getStaticOut() -{ +String WiFiManager::getStaticOut(){ String page; - if ((_staShowStaticFields || _sta_static_ip) && _staShowStaticFields >= 0) - { - DEBUG_WM(DEBUG_DEV, "_staShowStaticFields"); + if ((_staShowStaticFields || _sta_static_ip) && _staShowStaticFields>=0) { + DEBUG_WM(DEBUG_DEV,"_staShowStaticFields"); page += FPSTR(HTTP_FORM_STATIC_HEAD); // @todo how can we get these accurate settings from memory , wifi_get_ip_info does not seem to reveal if struct ip_info is static or not - page += getIpForm(FPSTR(S_ip), FPSTR(S_staticip), (_sta_static_ip ? _sta_static_ip.toString() : "")); // @token staticip + page += getIpForm(FPSTR(S_ip),FPSTR(S_staticip),(_sta_static_ip ? _sta_static_ip.toString() : "")); // @token staticip // WiFi.localIP().toString(); - page += getIpForm(FPSTR(S_gw), FPSTR(S_staticgw), (_sta_static_gw ? _sta_static_gw.toString() : "")); // @token staticgw + page += getIpForm(FPSTR(S_gw),FPSTR(S_staticgw),(_sta_static_gw ? _sta_static_gw.toString() : "")); // @token staticgw // WiFi.gatewayIP().toString(); - page += getIpForm(FPSTR(S_sn), FPSTR(S_subnet), (_sta_static_sn ? _sta_static_sn.toString() : "")); // @token subnet + page += getIpForm(FPSTR(S_sn),FPSTR(S_subnet),(_sta_static_sn ? _sta_static_sn.toString() : "")); // @token subnet // WiFi.subnetMask().toString(); } - if ((_staShowDns || _sta_static_dns) && _staShowDns >= 0) - { - page += getIpForm(FPSTR(S_dns), FPSTR(S_staticdns), (_sta_static_dns ? _sta_static_dns.toString() : "")); // @token dns + if((_staShowDns || _sta_static_dns) && _staShowDns>=0){ + page += getIpForm(FPSTR(S_dns),FPSTR(S_staticdns),(_sta_static_dns ? _sta_static_dns.toString() : "")); // @token dns } - if (page != "") - page += FPSTR(HTTP_BR); // @todo remove these, use css + if(page!="") page += FPSTR(HTTP_BR); // @todo remove these, use css return page; } -String WiFiManager::getParamOut() -{ +String WiFiManager::getParamOut(){ String page; - if (_paramsCount > 0) - { + if(_paramsCount > 0){ String HTTP_PARAM_temp = FPSTR(HTTP_FORM_LABEL); HTTP_PARAM_temp += FPSTR(HTTP_FORM_PARAM); @@ -1400,55 +1198,41 @@ String WiFiManager::getParamOut() char parLength[5]; // add the extra parameters to the form - for (int i = 0; i < _paramsCount; i++) - { - if (_params[i] == NULL || _params[i]->_length == 0) - { - DEBUG_WM(DEBUG_ERROR, "[ERROR] WiFiManagerParameter is out of scope"); + for (int i = 0; i < _paramsCount; i++) { + if (_params[i] == NULL || _params[i]->_length == 0) { + DEBUG_WM(DEBUG_ERROR,"[ERROR] WiFiManagerParameter is out of scope"); break; } - // label before or after, this could probably be done via floats however - String pitem; - switch (_params[i]->getLabelPlacement()) - { - case WFM_LABEL_BEFORE: - pitem = FPSTR(HTTP_FORM_LABEL); - pitem += FPSTR(HTTP_FORM_PARAM); - break; - case WFM_LABEL_AFTER: - pitem = FPSTR(HTTP_FORM_PARAM); - pitem += FPSTR(HTTP_FORM_LABEL); - break; - default: - // WFM_NO_LABEL - pitem = FPSTR(HTTP_FORM_PARAM); - break; + // label before or after, this could probably be done via floats however + String pitem; + switch (_params[i]->getLabelPlacement()) { + case WFM_LABEL_BEFORE: + pitem = FPSTR(HTTP_FORM_LABEL); + pitem += FPSTR(HTTP_FORM_PARAM); + break; + case WFM_LABEL_AFTER: + pitem = FPSTR(HTTP_FORM_PARAM); + pitem += FPSTR(HTTP_FORM_LABEL); + break; + default: + // WFM_NO_LABEL + pitem = FPSTR(HTTP_FORM_PARAM); + break; } // if no ID use customhtml for item, else generate from param string - if (_params[i]->getID() != NULL) - { - if (tok_I) - pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre) + (String)i); - if (tok_i) - pitem.replace(FPSTR(T_i), _params[i]->getID()); - if (tok_n) - pitem.replace(FPSTR(T_n), _params[i]->getID()); - if (tok_p) - pitem.replace(FPSTR(T_p), FPSTR(T_t)); - if (tok_t) - pitem.replace(FPSTR(T_t), _params[i]->getPlaceholder()); + if (_params[i]->getID() != NULL) { + if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); + if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); + if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); + if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); + if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getPlaceholder()); snprintf(parLength, 5, "%d", _params[i]->getValueLength()); - if (tok_l) - pitem.replace(FPSTR(T_l), parLength); - if (tok_v) - pitem.replace(FPSTR(T_v), _params[i]->getValue()); - if (tok_c) - pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // meant for additional attributes, not html - } - else - { + if(tok_l)pitem.replace(FPSTR(T_l), parLength); + if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); + if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // meant for additional attributes, not html + } else { pitem = _params[i]->getCustomHTML(); } @@ -1459,15 +1243,14 @@ String WiFiManager::getParamOut() return page; } -void WiFiManager::handleWiFiStatus() -{ - DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP WiFi status ")); +void WiFiManager::handleWiFiStatus(){ + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi status ")); handleRequest(); String page; -// String page = "{\"result\":true,\"count\":1}"; -#ifdef JSTEST - page = FPSTR(HTTP_JS); -#endif + // String page = "{\"result\":true,\"count\":1}"; + #ifdef JSTEST + page = FPSTR(HTTP_JS); + #endif server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); } @@ -1475,15 +1258,13 @@ void WiFiManager::handleWiFiStatus() /** * HTTPD CALLBACK save form and redirect to WLAN config page again */ -void WiFiManager::handleWifiSave() -{ - DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP WiFi save ")); - DEBUG_WM(DEBUG_DEV, F("Method:"), server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); +void WiFiManager::handleWifiSave() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); + DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); handleRequest(); - // @todo use new callback for pre saves - if (_presavecallback != NULL) - { + // @todo use new callback for before paramsaves + if ( _presavecallback != NULL) { _presavecallback(); } @@ -1491,33 +1272,28 @@ void WiFiManager::handleWifiSave() _ssid = server->arg(F("s")).c_str(); _pass = server->arg(F("p")).c_str(); - if (_paramsInWifi) - doParamSave(); + if(_paramsInWifi) doParamSave(); - if (server->arg(FPSTR(S_ip)) != "") - { + if (server->arg(FPSTR(S_ip)) != "") { //_sta_static_ip.fromString(server->arg(FPSTR(S_ip)); String ip = server->arg(FPSTR(S_ip)); optionalIPFromString(&_sta_static_ip, ip.c_str()); - DEBUG_WM(DEBUG_DEV, F("static ip:"), ip); + DEBUG_WM(DEBUG_DEV,F("static ip:"),ip); } - if (server->arg(FPSTR(S_gw)) != "") - { + if (server->arg(FPSTR(S_gw)) != "") { String gw = server->arg(FPSTR(S_gw)); optionalIPFromString(&_sta_static_gw, gw.c_str()); - DEBUG_WM(DEBUG_DEV, F("static gateway:"), gw); + DEBUG_WM(DEBUG_DEV,F("static gateway:"),gw); } - if (server->arg(FPSTR(S_sn)) != "") - { + if (server->arg(FPSTR(S_sn)) != "") { String sn = server->arg(FPSTR(S_sn)); optionalIPFromString(&_sta_static_sn, sn.c_str()); - DEBUG_WM(DEBUG_DEV, F("static netmask:"), sn); + DEBUG_WM(DEBUG_DEV,F("static netmask:"),sn); } - if (server->arg(FPSTR(S_dns)) != "") - { + if (server->arg(FPSTR(S_dns)) != "") { String dns = server->arg(FPSTR(S_dns)); optionalIPFromString(&_sta_static_dns, dns.c_str()); - DEBUG_WM(DEBUG_DEV, F("static DNS:"), dns); + DEBUG_WM(DEBUG_DEV,F("static DNS:"),dns); } String page = getHTTPHead(FPSTR(S_titlewifisaved)); // @token titlewifisaved @@ -1528,28 +1304,26 @@ void WiFiManager::handleWifiSave() server->sendHeader(FPSTR(HTTP_HEAD_CORS), FPSTR(HTTP_HEAD_CORS_ALLOW_ALL)); server->send(200, FPSTR(HTTP_HEAD_CT), page); - DEBUG_WM(DEBUG_DEV, F("Sent wifi save page")); + DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); connect = true; //signal ready to connect/reset process in processConfigPortal } -void WiFiManager::handleParamSave() -{ - DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP WiFi save ")); - DEBUG_WM(DEBUG_DEV, F("Method:"), server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); +void WiFiManager::handleParamSave() { + + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); + DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); handleRequest(); - // @todo use new callback for pre saves - if (_presavecallback != NULL) - { + // @todo use new callback for before paramsaves + if ( _presavecallback != NULL) { _presavecallback(); } doParamSave(); // @todo use new callback for paramsaves - if (_savecallback != NULL) - { + if ( _savecallback != NULL) { _savecallback(); } @@ -1560,58 +1334,50 @@ void WiFiManager::handleParamSave() server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); - DEBUG_WM(DEBUG_DEV, F("Sent param save page")); + DEBUG_WM(DEBUG_DEV,F("Sent param save page")); } -void WiFiManager::doParamSave() -{ +void WiFiManager::doParamSave(){ //parameters - if (_paramsCount > 0) - { - DEBUG_WM(DEBUG_VERBOSE, F("Parameters")); - DEBUG_WM(DEBUG_VERBOSE, FPSTR(D_HR)); - for (int i = 0; i < _paramsCount; i++) - { - if (_params[i] == NULL) - { + if(_paramsCount > 0){ + DEBUG_WM(DEBUG_VERBOSE,F("Parameters")); + DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + for (int i = 0; i < _paramsCount; i++) { + if (_params[i] == NULL) { break; } //read parameter from server - String name = (String)FPSTR(S_parampre) + (String)i; + String name = (String)FPSTR(S_parampre)+(String)i; String value; - if (server->hasArg(name)) - { + if(server->hasArg(name)) { value = server->arg(name); - } - else - { + } else { value = server->arg(_params[i]->getID()); } //store it in params array - value.toCharArray(_params[i]->_value, _params[i]->_length + 1); // length+1 null terminated - DEBUG_WM(DEBUG_VERBOSE, (String)_params[i]->getID() + ":", value); + value.toCharArray(_params[i]->_value, _params[i]->_length+1); // length+1 null terminated + DEBUG_WM(DEBUG_VERBOSE,(String)_params[i]->getID() + ":",value); } - DEBUG_WM(DEBUG_VERBOSE, FPSTR(D_HR)); + DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); } } /** * HTTPD CALLBACK info page */ -void WiFiManager::handleInfo() -{ - DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Info")); +void WiFiManager::handleInfo() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Info")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo reportStatus(page); uint16_t infos = 0; -//@todo convert to enum or refactor to strings -#ifdef ESP8266 - infos = 27; - String infoids[] = { + //@todo convert to enum or refactor to strings + #ifdef ESP8266 + infos = 27; + String infoids[] = { F("esphead"), F("uptime"), F("chipid"), @@ -1638,11 +1404,12 @@ void WiFiManager::handleInfo() F("host"), F("stamac"), F("conx"), - F("autoconx")}; + F("autoconx") + }; -#elif defined(ESP32) - infos = 22; - String infoids[] = { + #elif defined(ESP32) + infos = 22; + String infoids[] = { F("esphead"), F("uptime"), F("chipid"), @@ -1664,279 +1431,214 @@ void WiFiManager::handleInfo() F("dnss"), F("host"), F("stamac"), - F("conx")}; -#endif + F("conx") + }; + #endif - for (size_t i = 0; i < infos; i++) - { - if (infoids[i] != NULL) - page += getInfoData(infoids[i]); + for(size_t i=0; i"); - if (_showInfoErase) - page += FPSTR(HTTP_ERASEBTN); + if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); page += FPSTR(HTTP_HELP); page += FPSTR(HTTP_END); server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); - DEBUG_WM(DEBUG_DEV, F("Sent info page")); + DEBUG_WM(DEBUG_DEV,F("Sent info page")); } -String WiFiManager::getInfoData(String id) -{ +String WiFiManager::getInfoData(String id){ String p; // @todo add versioning - if (id == F("esphead")) - p = FPSTR(HTTP_INFO_esphead); - else if (id == F("wifihead")) - p = FPSTR(HTTP_INFO_wifihead); - else if (id == F("uptime")) - { + if(id==F("esphead"))p = FPSTR(HTTP_INFO_esphead); + else if(id==F("wifihead"))p = FPSTR(HTTP_INFO_wifihead); + else if(id==F("uptime")){ // subject to rollover! p = FPSTR(HTTP_INFO_uptime); - p.replace(FPSTR(T_1), (String)(millis() / 1000 / 60)); - p.replace(FPSTR(T_2), (String)((millis() / 1000) % 60)); + p.replace(FPSTR(T_1),(String)(millis() / 1000 / 60)); + p.replace(FPSTR(T_2),(String)((millis() / 1000) % 60)); } - else if (id == F("chipid")) - { + else if(id==F("chipid")){ p = FPSTR(HTTP_INFO_chipid); - p.replace(FPSTR(T_1), String(WIFI_getChipId(), HEX)); + p.replace(FPSTR(T_1),String(WIFI_getChipId(),HEX)); } -#ifdef ESP32 - else if (id == F("chiprev")) - { - p = FPSTR(HTTP_INFO_chiprev); - String rev = (String)ESP.getChipRevision(); -#ifdef _SOC_EFUSE_REG_H_ - String revb = (String)(REG_READ(EFUSE_BLK0_RDATA3_REG) >> (EFUSE_RD_CHIP_VER_RESERVE_S) && EFUSE_RD_CHIP_VER_RESERVE_V); - p.replace(FPSTR(T_1), rev + "
" + revb); -#else - p.replace(FPSTR(T_1), rev); -#endif + #ifdef ESP32 + else if(id==F("chiprev")){ + p = FPSTR(HTTP_INFO_chiprev); + String rev = (String)ESP.getChipRevision(); + #ifdef _SOC_EFUSE_REG_H_ + String revb = (String)(REG_READ(EFUSE_BLK0_RDATA3_REG) >> (EFUSE_RD_CHIP_VER_RESERVE_S)&&EFUSE_RD_CHIP_VER_RESERVE_V); + p.replace(FPSTR(T_1),rev+"
"+revb); + #else + p.replace(FPSTR(T_1),rev); + #endif } -#endif -#ifdef ESP8266 - else if (id == F("fchipid")) - { - p = FPSTR(HTTP_INFO_fchipid); - p.replace(FPSTR(T_1), (String)ESP.getFlashChipId()); + #endif + #ifdef ESP8266 + else if(id==F("fchipid")){ + p = FPSTR(HTTP_INFO_fchipid); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipId()); } -#endif - else if (id == F("idesize")) - { + #endif + else if(id==F("idesize")){ p = FPSTR(HTTP_INFO_idesize); - p.replace(FPSTR(T_1), (String)ESP.getFlashChipSize()); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipSize()); } - else if (id == F("flashsize")) - { -#ifdef ESP8266 - p = FPSTR(HTTP_INFO_flashsize); - p.replace(FPSTR(T_1), (String)ESP.getFlashChipRealSize()); -#endif + else if(id==F("flashsize")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_flashsize); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipRealSize()); + #endif } - else if (id == F("sdkver")) - { + else if(id==F("sdkver")){ p = FPSTR(HTTP_INFO_sdkver); -#ifdef ESP32 - p.replace(FPSTR(T_1), (String)esp_get_idf_version()); -#else - p.replace(FPSTR(T_1), (String)system_get_sdk_version()); -#endif + #ifdef ESP32 + p.replace(FPSTR(T_1),(String)esp_get_idf_version()); + #else + p.replace(FPSTR(T_1),(String)system_get_sdk_version()); + #endif } - else if (id == F("corever")) - { -#ifdef ESP8266 - p = FPSTR(HTTP_INFO_corever); - p.replace(FPSTR(T_1), (String)ESP.getCoreVersion()); -#endif + else if(id==F("corever")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_corever); + p.replace(FPSTR(T_1),(String)ESP.getCoreVersion()); + #endif } -#ifdef ESP8266 - else if (id == F("bootver")) - { - p = FPSTR(HTTP_INFO_bootver); - p.replace(FPSTR(T_1), (String)system_get_boot_version()); + #ifdef ESP8266 + else if(id==F("bootver")){ + p = FPSTR(HTTP_INFO_bootver); + p.replace(FPSTR(T_1),(String)system_get_boot_version()); } -#endif - else if (id == F("cpufreq")) - { + #endif + else if(id==F("cpufreq")){ p = FPSTR(HTTP_INFO_cpufreq); - p.replace(FPSTR(T_1), (String)ESP.getCpuFreqMHz()); + p.replace(FPSTR(T_1),(String)ESP.getCpuFreqMHz()); } - else if (id == F("freeheap")) - { + else if(id==F("freeheap")){ p = FPSTR(HTTP_INFO_freeheap); - p.replace(FPSTR(T_1), (String)ESP.getFreeHeap()); + p.replace(FPSTR(T_1),(String)ESP.getFreeHeap()); } -#ifdef ESP8266 - else if (id == F("memsketch")) - { + #ifdef ESP8266 + else if(id==F("memsketch")){ p = FPSTR(HTTP_INFO_memsketch); - p.replace(FPSTR(T_1), (String)(ESP.getSketchSize())); - p.replace(FPSTR(T_2), (String)(ESP.getSketchSize() + ESP.getFreeSketchSpace())); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); } -#endif -#ifdef ESP8266 - else if (id == F("memsmeter")) - { + #endif + #ifdef ESP8266 + else if(id==F("memsmeter")){ p = FPSTR(HTTP_INFO_memsmeter); - p.replace(FPSTR(T_1), (String)(ESP.getSketchSize())); - p.replace(FPSTR(T_2), (String)(ESP.getSketchSize() + ESP.getFreeSketchSpace())); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); } -#endif - else if (id == F("lastreset")) - { -#ifdef ESP8266 - p = FPSTR(HTTP_INFO_lastreset); - p.replace(FPSTR(T_1), (String)ESP.getResetReason()); -#elif defined(ESP32) && defined(_ROM_RTC_H_) - // requires #include - p = FPSTR(HTTP_INFO_lastreset); - for (int i = 0; i < 2; i++) - { - int reason = rtc_get_reset_reason(i); - String tok = (String)T_ss + (String)(i + 1) + (String)T_es; - switch (reason) - { - //@todo move to array - case 1: - p.replace(tok, F("Vbat power on reset")); - break; - case 3: - p.replace(tok, F("Software reset digital core")); - break; - case 4: - p.replace(tok, F("Legacy watch dog reset digital core")); - break; - case 5: - p.replace(tok, F("Deep Sleep reset digital core")); - break; - case 6: - p.replace(tok, F("Reset by SLC module, reset digital core")); - break; - case 7: - p.replace(tok, F("Timer Group0 Watch dog reset digital core")); - break; - case 8: - p.replace(tok, F("Timer Group1 Watch dog reset digital core")); - break; - case 9: - p.replace(tok, F("RTC Watch dog Reset digital core")); - break; - case 10: - p.replace(tok, F("Instrusion tested to reset CPU")); - break; - case 11: - p.replace(tok, F("Time Group reset CPU")); - break; - case 12: - p.replace(tok, F("Software reset CPU")); - break; - case 13: - p.replace(tok, F("RTC Watch dog Reset CPU")); - break; - case 14: - p.replace(tok, F("for APP CPU, reseted by PRO CPU")); - break; - case 15: - p.replace(tok, F("Reset when the vdd voltage is not stable")); - break; - case 16: - p.replace(tok, F("RTC Watch dog reset digital core and rtc module")); - break; - default: - p.replace(tok, F("NO_MEAN")); + #endif + else if(id==F("lastreset")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_lastreset); + p.replace(FPSTR(T_1),(String)ESP.getResetReason()); + #elif defined(ESP32) && defined(_ROM_RTC_H_) + // requires #include + p = FPSTR(HTTP_INFO_lastreset); + for(int i=0;i<2;i++){ + int reason = rtc_get_reset_reason(i); + String tok = (String)T_ss+(String)(i+1)+(String)T_es; + switch (reason) + { + //@todo move to array + case 1 : p.replace(tok,F("Vbat power on reset"));break; + case 3 : p.replace(tok,F("Software reset digital core"));break; + case 4 : p.replace(tok,F("Legacy watch dog reset digital core"));break; + case 5 : p.replace(tok,F("Deep Sleep reset digital core"));break; + case 6 : p.replace(tok,F("Reset by SLC module, reset digital core"));break; + case 7 : p.replace(tok,F("Timer Group0 Watch dog reset digital core"));break; + case 8 : p.replace(tok,F("Timer Group1 Watch dog reset digital core"));break; + case 9 : p.replace(tok,F("RTC Watch dog Reset digital core"));break; + case 10 : p.replace(tok,F("Instrusion tested to reset CPU"));break; + case 11 : p.replace(tok,F("Time Group reset CPU"));break; + case 12 : p.replace(tok,F("Software reset CPU"));break; + case 13 : p.replace(tok,F("RTC Watch dog Reset CPU"));break; + case 14 : p.replace(tok,F("for APP CPU, reseted by PRO CPU"));break; + case 15 : p.replace(tok,F("Reset when the vdd voltage is not stable"));break; + case 16 : p.replace(tok,F("RTC Watch dog reset digital core and rtc module"));break; + default : p.replace(tok,F("NO_MEAN")); + } } - } -#endif + #endif } - else if (id == F("apip")) - { + else if(id==F("apip")){ p = FPSTR(HTTP_INFO_apip); - p.replace(FPSTR(T_1), WiFi.softAPIP().toString()); + p.replace(FPSTR(T_1),WiFi.softAPIP().toString()); } - else if (id == F("apmac")) - { + else if(id==F("apmac")){ p = FPSTR(HTTP_INFO_apmac); - p.replace(FPSTR(T_1), (String)WiFi.softAPmacAddress()); + p.replace(FPSTR(T_1),(String)WiFi.softAPmacAddress()); } -#ifdef ESP32 - else if (id == F("aphost")) - { - p = FPSTR(HTTP_INFO_aphost); - p.replace(FPSTR(T_1), WiFi.softAPgetHostname()); + #ifdef ESP32 + else if(id==F("aphost")){ + p = FPSTR(HTTP_INFO_aphost); + p.replace(FPSTR(T_1),WiFi.softAPgetHostname()); } -#endif - else if (id == F("apssid")) - { + #endif + else if(id==F("apssid")){ p = FPSTR(HTTP_INFO_apssid); - p.replace(FPSTR(T_1), htmlEntities((String)WiFi_SSID())); + p.replace(FPSTR(T_1),htmlEntities((String)WiFi_SSID())); } - else if (id == F("apbssid")) - { + else if(id==F("apbssid")){ p = FPSTR(HTTP_INFO_apbssid); - p.replace(FPSTR(T_1), (String)WiFi.BSSIDstr()); + p.replace(FPSTR(T_1),(String)WiFi.BSSIDstr()); } - else if (id == F("staip")) - { + else if(id==F("staip")){ p = FPSTR(HTTP_INFO_staip); - p.replace(FPSTR(T_1), WiFi.localIP().toString()); + p.replace(FPSTR(T_1),WiFi.localIP().toString()); } - else if (id == F("stagw")) - { + else if(id==F("stagw")){ p = FPSTR(HTTP_INFO_stagw); - p.replace(FPSTR(T_1), WiFi.gatewayIP().toString()); + p.replace(FPSTR(T_1),WiFi.gatewayIP().toString()); } - else if (id == F("stasub")) - { + else if(id==F("stasub")){ p = FPSTR(HTTP_INFO_stasub); - p.replace(FPSTR(T_1), WiFi.subnetMask().toString()); + p.replace(FPSTR(T_1),WiFi.subnetMask().toString()); } - else if (id == F("dnss")) - { + else if(id==F("dnss")){ p = FPSTR(HTTP_INFO_dnss); - p.replace(FPSTR(T_1), WiFi.dnsIP().toString()); + p.replace(FPSTR(T_1),WiFi.dnsIP().toString()); } - else if (id == F("host")) - { + else if(id==F("host")){ p = FPSTR(HTTP_INFO_host); -#ifdef ESP32 - p.replace(FPSTR(T_1), WiFi.getHostname()); -#else - p.replace(FPSTR(T_1), WiFi.hostname()); -#endif + #ifdef ESP32 + p.replace(FPSTR(T_1),WiFi.getHostname()); + #else + p.replace(FPSTR(T_1),WiFi.hostname()); + #endif } - else if (id == F("stamac")) - { + else if(id==F("stamac")){ p = FPSTR(HTTP_INFO_stamac); - p.replace(FPSTR(T_1), WiFi.macAddress()); + p.replace(FPSTR(T_1),WiFi.macAddress()); } - else if (id == F("conx")) - { + else if(id==F("conx")){ p = FPSTR(HTTP_INFO_conx); - p.replace(FPSTR(T_1), WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); + p.replace(FPSTR(T_1),WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); } -#ifdef ESP8266 - else if (id == F("autoconx")) - { + #ifdef ESP8266 + else if(id==F("autoconx")){ p = FPSTR(HTTP_INFO_autoconx); - p.replace(FPSTR(T_1), WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); + p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); } -#endif + #endif return p; } /** * HTTPD CALLBACK root or redirect to captive portal */ -void WiFiManager::handleExit() -{ - DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Exit")); +void WiFiManager::handleExit() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Exit")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleexit)); // @token titleexit - page += FPSTR(S_exiting); // @token exiting + page += FPSTR(S_exiting); // @token exiting server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); abort = true; @@ -1945,12 +1647,11 @@ void WiFiManager::handleExit() /** * HTTPD CALLBACK reset page */ -void WiFiManager::handleReset() -{ - DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Reset")); +void WiFiManager::handleReset() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Reset")); handleRequest(); String page = getHTTPHead(FPSTR(S_titlereset)); //@token titlereset - page += FPSTR(S_resetting); //@token resetting + page += FPSTR(S_resetting); //@token resetting page += FPSTR(HTTP_END); server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); @@ -1968,60 +1669,53 @@ void WiFiManager::handleReset() // void WiFiManager::handleErase() { // handleErase(false); // } -void WiFiManager::handleErase(boolean opt) -{ - DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP Erase")); +void WiFiManager::handleErase(boolean opt) { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Erase")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase bool ret = erase(opt); - if (ret) - page += FPSTR(S_resetting); // @token resetting - else - { + if(ret) page += FPSTR(S_resetting); // @token resetting + else { page += FPSTR(S_error); // @token erroroccur - DEBUG_WM(DEBUG_ERROR, F("[ERROR] WiFi EraseConfig failed")); + DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFi EraseConfig failed")); } page += FPSTR(HTTP_END); server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); - if (ret) - { + if(ret){ delay(2000); - DEBUG_WM(F("RESETTING ESP")); - reboot(); - } + DEBUG_WM(F("RESETTING ESP")); + reboot(); + } } /** * HTTPD CALLBACK 404 */ -void WiFiManager::handleNotFound() -{ - if (captivePortal()) - return; // If captive portal redirect instead of displaying the page +void WiFiManager::handleNotFound() { + if (captivePortal()) return; // If captive portal redirect instead of displaying the page handleRequest(); String message = FPSTR(S_notfound); // @token notfound - message += FPSTR(S_uri); // @token uri + message += FPSTR(S_uri); // @token uri message += server->uri(); message += FPSTR(S_method); // @token method - message += (server->method() == HTTP_GET) ? FPSTR(S_GET) : FPSTR(S_POST); + message += ( server->method() == HTTP_GET ) ? FPSTR(S_GET) : FPSTR(S_POST); message += FPSTR(S_args); // @token args message += server->args(); message += F("\n"); - for (uint8_t i = 0; i < server->args(); i++) - { - message += " " + server->argName(i) + ": " + server->arg(i) + "\n"; + for ( uint8_t i = 0; i < server->args(); i++ ) { + message += " " + server->argName ( i ) + ": " + server->arg ( i ) + "\n"; } server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); server->sendHeader(F("Pragma"), F("no-cache")); server->sendHeader(F("Expires"), F("-1")); server->sendHeader(FPSTR(HTTP_HEAD_CL), String(message.length())); - server->send(404, FPSTR(HTTP_HEAD_CT2), message); + server->send ( 404, FPSTR(HTTP_HEAD_CT2), message ); } /** @@ -2029,84 +1723,70 @@ void WiFiManager::handleNotFound() * Redirect to captive portal if we got a request for another domain. * Return true in that case so the page handler do not try to handle the request again. */ -boolean WiFiManager::captivePortal() -{ - DEBUG_WM(DEBUG_DEV, "-> " + server->hostHeader()); +boolean WiFiManager::captivePortal() { + DEBUG_WM(DEBUG_DEV,"-> " + server->hostHeader()); + + if(!_enableCaptivePortal) return false; // skip redirections - if (!_enableCaptivePortal) - return false; // skip redirections - - if (!isIp(server->hostHeader())) - { - DEBUG_WM(DEBUG_VERBOSE, F("<- Request redirected to captive portal")); + if (!isIp(server->hostHeader())) { + DEBUG_WM(DEBUG_VERBOSE,F("<- Request redirected to captive portal")); server->sendHeader(F("Location"), (String)F("http://") + toStringIp(server->client().localIP()), true); - server->send(302, FPSTR(HTTP_HEAD_CT2), ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. - server->client().stop(); // Stop is needed because we sent no content length + server->send ( 302, FPSTR(HTTP_HEAD_CT2), ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + server->client().stop(); // Stop is needed because we sent no content length return true; } return false; } -void WiFiManager::stopCaptivePortal() -{ - _enableCaptivePortal = false; +void WiFiManager::stopCaptivePortal(){ + _enableCaptivePortal= false; // @todo maybe disable configportaltimeout(optional), or just provide callback for user } -void WiFiManager::handleClose() -{ +void WiFiManager::handleClose(){ stopCaptivePortal(); - DEBUG_WM(DEBUG_VERBOSE, F("<- HTTP close")); + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP close")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleclose)); // @token titleclose - page += FPSTR(S_closing); // @token closing + page += FPSTR(S_closing); // @token closing server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); } -void WiFiManager::reportStatus(String &page) -{ +void WiFiManager::reportStatus(String &page){ updateConxResult(WiFi.status()); String str; - if (WiFi_SSID() != "") - { - if (WiFi.status() == WL_CONNECTED) - { + if (WiFi_SSID() != ""){ + if (WiFi.status()==WL_CONNECTED){ str = FPSTR(HTTP_STATUS_ON); - str.replace(FPSTR(T_i), WiFi.localIP().toString()); - str.replace(FPSTR(T_v), htmlEntities(WiFi_SSID())); + str.replace(FPSTR(T_i),WiFi.localIP().toString()); + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); } - else - { + else { str = FPSTR(HTTP_STATUS_OFF); - str.replace(FPSTR(T_v), htmlEntities(WiFi_SSID())); - if (_lastconxresult == WL_STATION_WRONG_PASSWORD) - { + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + if(_lastconxresult == WL_STATION_WRONG_PASSWORD){ // wrong password - str.replace(FPSTR(T_c), "D"); // class - str.replace(FPSTR(T_r), FPSTR(HTTP_STATUS_OFFPW)); + str.replace(FPSTR(T_c),"D"); // class + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFPW)); } - else if (_lastconxresult == WL_NO_SSID_AVAIL) - { + else if(_lastconxresult == WL_NO_SSID_AVAIL){ // connect failed, or ap not found - str.replace(FPSTR(T_c), "D"); - str.replace(FPSTR(T_r), FPSTR(HTTP_STATUS_OFFNOAP)); + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFNOAP)); } - else if (_lastconxresult == WL_CONNECT_FAILED) - { + else if(_lastconxresult == WL_CONNECT_FAILED){ // connect failed - str.replace(FPSTR(T_c), "D"); - str.replace(FPSTR(T_r), FPSTR(HTTP_STATUS_OFFFAIL)); - } - else - { - str.replace(FPSTR(T_c), ""); - str.replace(FPSTR(T_r), ""); + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFFAIL)); } + else{ + str.replace(FPSTR(T_c),""); + str.replace(FPSTR(T_r),""); + } } } - else - { + else { str = FPSTR(HTTP_STATUS_NONE); } page += str; @@ -2126,13 +1806,11 @@ void WiFiManager::reportStatus(String &page) * @since $dev * @return bool success */ -bool WiFiManager::disconnect() -{ - if (WiFi.status() != WL_CONNECTED) - { - DEBUG_WM(DEBUG_VERBOSE, "Disconnecting: Not connected"); +bool WiFiManager::disconnect(){ + if(WiFi.status() != WL_CONNECTED){ + DEBUG_WM(DEBUG_VERBOSE,"Disconnecting: Not connected"); return false; - } + } DEBUG_WM("Disconnecting"); return WiFi_Disconnect(); } @@ -2141,8 +1819,7 @@ bool WiFiManager::disconnect() * reboot the device * @access public */ -void WiFiManager::reboot() -{ +void WiFiManager::reboot(){ DEBUG_WM("Restarting"); ESP.restart(); } @@ -2151,31 +1828,28 @@ void WiFiManager::reboot() * reboot the device * @access public */ -bool WiFiManager::erase() -{ +bool WiFiManager::erase(){ return erase(false); } -bool WiFiManager::erase(bool opt) -{ +bool WiFiManager::erase(bool opt){ DEBUG_WM("Erasing"); -#if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) - // if opt true, do nvs erase - if (opt) - { - DEBUG_WM("Erasing NVS"); - int err; - esp_err_t err; - err = nvs_flash_init(); - DEBUG_WM(DEBUG_VERBOSE, "nvs_flash_init: ", err != ESP_OK ? (String)err : "Success"); - err = nvs_flash_erase(); - DEBUG_WM(DEBUG_VERBOSE, "nvs_flash_erase: ", err != ESP_OK ? (String)err : "Success"); - return err == ESP_OK; - } -#else - (void)opt; -#endif + #if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) + // if opt true, do nvs erase + if(opt){ + DEBUG_WM("Erasing NVS"); + int err; + esp_err_t err; + err = nvs_flash_init(); + DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_init: ",err!=ESP_OK ? (String)err : "Success"); + err = nvs_flash_erase(); + DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_erase: ", err!=ESP_OK ? (String)err : "Success"); + return err == ESP_OK; + } + #else + (void)opt; + #endif return WiFi_eraseConfig(); } @@ -2185,18 +1859,17 @@ bool WiFiManager::erase(bool opt) * ERASES STA CREDENTIALS * @access public */ -void WiFiManager::resetSettings() -{ +void WiFiManager::resetSettings() { DEBUG_WM(F("SETTINGS ERASED")); - WiFi_enableSTA(true, true); // must be sta to disconnect erase - -#ifdef ESP32 - WiFi.disconnect(true, true); -#else - WiFi.persistent(true); - WiFi.disconnect(true); - WiFi.persistent(false); -#endif + WiFi_enableSTA(true,true); // must be sta to disconnect erase + + #ifdef ESP32 + WiFi.disconnect(true,true); + #else + WiFi.persistent(true); + WiFi.disconnect(true); + WiFi.persistent(false); + #endif } // SETTERS @@ -2206,8 +1879,7 @@ void WiFiManager::resetSettings() * @access public * @param {[type]} unsigned long seconds [description] */ -void WiFiManager::setTimeout(unsigned long seconds) -{ +void WiFiManager::setTimeout(unsigned long seconds) { setConfigPortalTimeout(seconds); } @@ -2216,8 +1888,7 @@ void WiFiManager::setTimeout(unsigned long seconds) * @access public * @param {[type]} unsigned long seconds [description] */ -void WiFiManager::setConfigPortalTimeout(unsigned long seconds) -{ +void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { _configPortalTimeout = seconds * 1000; } @@ -2226,8 +1897,7 @@ void WiFiManager::setConfigPortalTimeout(unsigned long seconds) * @access public * @param {[type]} unsigned long seconds [description] */ -void WiFiManager::setConnectTimeout(unsigned long seconds) -{ +void WiFiManager::setConnectTimeout(unsigned long seconds) { _connectTimeout = seconds * 1000; } @@ -2236,8 +1906,7 @@ void WiFiManager::setConnectTimeout(unsigned long seconds) * @access public * @param {[type]} unsigned long seconds [description] */ -void WiFiManager::setSaveConnectTimeout(unsigned long seconds) -{ +void WiFiManager::setSaveConnectTimeout(unsigned long seconds) { _saveTimeout = seconds * 1000; } @@ -2246,8 +1915,7 @@ void WiFiManager::setSaveConnectTimeout(unsigned long seconds) * @access public * @param {[type]} boolean debug [description] */ -void WiFiManager::setDebugOutput(boolean debug) -{ +void WiFiManager::setDebugOutput(boolean debug) { _debug = debug; } @@ -2258,8 +1926,7 @@ void WiFiManager::setDebugOutput(boolean debug) * @param {[type]} IPAddress gw [description] * @param {[type]} IPAddress sn [description] */ -void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) -{ +void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { _ap_static_ip = ip; _ap_static_gw = gw; _ap_static_sn = sn; @@ -2272,8 +1939,7 @@ void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) * @param {[type]} IPAddress gw [description] * @param {[type]} IPAddress sn [description] */ -void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) -{ +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { _sta_static_ip = ip; _sta_static_gw = gw; _sta_static_sn = sn; @@ -2288,9 +1954,8 @@ void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) * @param {[type]} IPAddress sn [description] * @param {[type]} IPAddress dns [description] */ -void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns) -{ - setSTAStaticIPConfig(ip, gw, sn); +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns) { + setSTAStaticIPConfig(ip,gw,sn); _sta_static_dns = dns; } @@ -2299,8 +1964,7 @@ void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, * @access public * @param {[type]} int quality [description] */ -void WiFiManager::setMinimumSignalQuality(int quality) -{ +void WiFiManager::setMinimumSignalQuality(int quality) { _minimumQuality = quality; } @@ -2309,8 +1973,7 @@ void WiFiManager::setMinimumSignalQuality(int quality) * @access public * @param {[type]} boolean shouldBreak [description] */ -void WiFiManager::setBreakAfterConfig(boolean shouldBreak) -{ +void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { _shouldBreakAfterConfig = shouldBreak; } @@ -2319,30 +1982,27 @@ void WiFiManager::setBreakAfterConfig(boolean shouldBreak) * @access public * @param {[type]} void (*func)(WiFiManager* myWiFiManager) [description] */ -void WiFiManager::setAPCallback(std::function func) -{ +void WiFiManager::setAPCallback( std::function func ) { _apcallback = func; } - + /** * setSaveConfigCallback, set a save config callback after closing configportal * @todo only calls if configportal stopped * @access public * @param {[type]} void (*func)(void) [description] */ -void WiFiManager::setSaveConfigCallback(std::function func) -{ +void WiFiManager::setSaveConfigCallback( std::function func ) { _savecallback = func; } /** - * setSaveConfigCallback, set a save config callback after closing configportal + * setPreSaveConfigCallback, set a pre save config callback after closing configportal * @todo only calls if configportal stopped * @access public * @param {[type]} void (*func)(void) [description] */ -void WiFiManager::setPreSaveConfigCallback(std::function func) -{ +void WiFiManager::setPreSaveConfigCallback( std::function func ) { _presavecallback = func; } @@ -2352,8 +2012,7 @@ void WiFiManager::setPreSaveConfigCallback(std::function func) * @access public * @param char element */ -void WiFiManager::setCustomHeadElement(const char *element) -{ +void WiFiManager::setCustomHeadElement(const char* element) { _customHeadElement = element; } @@ -2364,8 +2023,7 @@ void WiFiManager::setCustomHeadElement(const char *element) * @access public * @param boolean removeDuplicates [true] */ -void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) -{ +void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) { _removeDuplicateAPs = removeDuplicates; } @@ -2377,8 +2035,7 @@ void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) * @access public * @param boolean shoudlBlock [false] */ -void WiFiManager::setConfigPortalBlocking(boolean shoudlBlock) -{ +void WiFiManager::setConfigPortalBlocking(boolean shoudlBlock) { _configPortalIsBlocking = shoudlBlock; } @@ -2390,11 +2047,9 @@ void WiFiManager::setConfigPortalBlocking(boolean shoudlBlock) * @access public * @param boolean persistent [true] */ -void WiFiManager::setRestorePersistent(boolean persistent) -{ +void WiFiManager::setRestorePersistent(boolean persistent) { _userpersistent = persistent; - if (!persistent) - DEBUG_WM(F("persistent is off")); + if(!persistent) DEBUG_WM(F("persistent is off")); } /** @@ -2404,12 +2059,9 @@ void WiFiManager::setRestorePersistent(boolean persistent) * @access public * @param boolean alwaysShow [false] */ -void WiFiManager::setShowStaticFields(boolean alwaysShow) -{ - if (_disableIpFields) - _staShowStaticFields = alwaysShow ? 1 : -1; - else - _staShowStaticFields = alwaysShow ? 1 : 0; +void WiFiManager::setShowStaticFields(boolean alwaysShow){ + if(_disableIpFields) _staShowStaticFields = alwaysShow ? 1 : -1; + else _staShowStaticFields = alwaysShow ? 1 : 0; } /** @@ -2419,10 +2071,8 @@ void WiFiManager::setShowStaticFields(boolean alwaysShow) * @access public * @param boolean alwaysShow [false] */ -void WiFiManager::setShowDnsFields(boolean alwaysShow) -{ - if (_disableIpFields) - _staShowDns = alwaysShow ? 1 : -1; +void WiFiManager::setShowDnsFields(boolean alwaysShow){ + if(_disableIpFields) _staShowDns = alwaysShow ? 1 : -1; _staShowDns = alwaysShow ? 1 : 0; } @@ -2434,8 +2084,7 @@ void WiFiManager::setShowDnsFields(boolean alwaysShow) * @access public * @param boolean enabled [true] */ -void WiFiManager::setCaptivePortalEnable(boolean enabled) -{ +void WiFiManager::setCaptivePortalEnable(boolean enabled){ _enableCaptivePortal = enabled; } @@ -2448,8 +2097,7 @@ void WiFiManager::setCaptivePortalEnable(boolean enabled) * @access public * @param boolean enabled [true] */ -void WiFiManager::setWiFiAutoReconnect(boolean enabled) -{ +void WiFiManager::setWiFiAutoReconnect(boolean enabled){ _wifiAutoReconnect = enabled; } @@ -2461,8 +2109,7 @@ void WiFiManager::setWiFiAutoReconnect(boolean enabled) * @access public * @param boolean enabled [false] */ -void WiFiManager::setCaptivePortalClientCheck(boolean enabled) -{ +void WiFiManager::setCaptivePortalClientCheck(boolean enabled){ _cpClientCheck = enabled; } @@ -2473,8 +2120,7 @@ void WiFiManager::setCaptivePortalClientCheck(boolean enabled) * @access public * @param boolean enabled [true] */ -void WiFiManager::setWebPortalClientCheck(boolean enabled) -{ +void WiFiManager::setWebPortalClientCheck(boolean enabled){ _webClientCheck = enabled; } @@ -2484,8 +2130,7 @@ void WiFiManager::setWebPortalClientCheck(boolean enabled) * @access public * @param boolean enabled [false] */ -void WiFiManager::setScanDispPerc(boolean enabled) -{ +void WiFiManager::setScanDispPerc(boolean enabled){ _scanDispOptions = enabled; } @@ -2498,9 +2143,10 @@ void WiFiManager::setScanDispPerc(boolean enabled) */ void WiFiManager::setEnableConfigPortal(boolean enable) { - _enableConfigPortal = enable; + _enableConfigPortal = enable; } + /** * set the hostname (dhcp client id) * @since $dev @@ -2508,8 +2154,7 @@ void WiFiManager::setEnableConfigPortal(boolean enable) * @param char* hostname 32 character hostname to use for sta+ap in esp32, sta in esp8266 * @return bool false if hostname is not valid */ -bool WiFiManager::setHostname(const char *hostname) -{ +bool WiFiManager::setHostname(const char * hostname){ //@todo max length 32 _hostname = hostname; return true; @@ -2519,8 +2164,7 @@ bool WiFiManager::setHostname(const char *hostname) * toggle showing erase wifi config button on info page * @param boolean enabled */ -void WiFiManager::setShowInfoErase(boolean enabled) -{ +void WiFiManager::setShowInfoErase(boolean enabled){ _showInfoErase = enabled; } @@ -2533,18 +2177,13 @@ void WiFiManager::setShowInfoErase(boolean enabled) * @since $dev * @param uint8_t menu[] array of menu ids */ -void WiFiManager::setMenu(const char *menu[], uint8_t size) -{ +void WiFiManager::setMenu(const char * menu[], uint8_t size){ // DEBUG_WM(DEBUG_VERBOSE,"setmenu array"); _menuIds.clear(); - for (size_t i = 0; i < size; i++) - { - for (size_t j = 0; j < _nummenutokens; j++) - { - if (menu[i] == _menutokens[j]) - { - if ((String)menu[i] == "param") - _paramsInWifi = false; // param auto flag + for(size_t i = 0; i < size; i++){ + for(size_t j = 0; j < _nummenutokens; j++){ + if(menu[i] == _menutokens[j]){ + if((String)menu[i] == "param") _paramsInWifi = false; // param auto flag _menuIds.push_back(j); } } @@ -2561,18 +2200,13 @@ void WiFiManager::setMenu(const char *menu[], uint8_t size) * @shiftIncrement $dev * @param {[type]} std::vector& menu [description] */ -void WiFiManager::setMenu(std::vector &menu) -{ +void WiFiManager::setMenu(std::vector& menu){ // DEBUG_WM(DEBUG_VERBOSE,"setmenu vector"); _menuIds.clear(); - for (auto menuitem : menu) - { - for (size_t j = 0; j < _nummenutokens; j++) - { - if (menuitem == _menutokens[j]) - { - if ((String)menuitem == "param") - _paramsInWifi = false; // param auto flag + for(auto menuitem : menu ){ + for(size_t j = 0; j < _nummenutokens; j++){ + if(menuitem == _menutokens[j]){ + if((String)menuitem == "param") _paramsInWifi = false; // param auto flag _menuIds.push_back(j); } } @@ -2580,6 +2214,7 @@ void WiFiManager::setMenu(std::vector &menu) // DEBUG_WM(getMenuOut()); } + // GETTERS /** @@ -2588,8 +2223,7 @@ void WiFiManager::setMenu(std::vector &menu) * @access public * @return String the configportal ap name */ -String WiFiManager::getConfigPortalSSID() -{ +String WiFiManager::getConfigPortalSSID() { return _apName; } @@ -2601,8 +2235,7 @@ String WiFiManager::getConfigPortalSSID() * @access public * @return bool return wl_status codes */ -uint8_t WiFiManager::getLastConxResult() -{ +uint8_t WiFiManager::getLastConxResult(){ return _lastconxresult; } @@ -2612,8 +2245,7 @@ uint8_t WiFiManager::getLastConxResult() * @access public * @return bool true if a saved ap config exists */ -bool WiFiManager::getWiFiIsSaved() -{ +bool WiFiManager::getWiFiIsSaved(){ return WiFi_hasAutoConnect(); } @@ -2622,8 +2254,7 @@ bool WiFiManager::getWiFiIsSaved() * @since $dev * @param String cc country code, must be defined in WiFiSetCountry, US, JP, CN */ -void WiFiManager::setCountry(String cc) -{ +void WiFiManager::setCountry(String cc){ _wificountry = cc; } @@ -2631,51 +2262,41 @@ void WiFiManager::setCountry(String cc) * setClass * @param String str body class string */ -void WiFiManager::setClass(String str) -{ +void WiFiManager::setClass(String str){ _bodyClass = str; } - + // HELPERS // DEBUG // @todo fix DEBUG_WM(0,0); template -void WiFiManager::DEBUG_WM(Generic text) -{ - DEBUG_WM(DEBUG_NOTIFY, text, ""); +void WiFiManager::DEBUG_WM(Generic text) { + DEBUG_WM(DEBUG_NOTIFY,text,""); } template -void WiFiManager::DEBUG_WM(wm_debuglevel_t level, Generic text) -{ - if (_debugLevel >= level) - DEBUG_WM(level, text, ""); +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text) { + if(_debugLevel >= level) DEBUG_WM(level,text,""); } template -void WiFiManager::DEBUG_WM(Generic text, Genericb textb) -{ - DEBUG_WM(DEBUG_NOTIFY, text, textb); +void WiFiManager::DEBUG_WM(Generic text,Genericb textb) { + DEBUG_WM(DEBUG_NOTIFY,text,textb); } template -void WiFiManager::DEBUG_WM(wm_debuglevel_t level, Generic text, Genericb textb) -{ - if (!_debug || _debugLevel < level) - return; +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { + if(!_debug || _debugLevel < level) return; - if (_debugLevel >= DEBUG_MAX) - { + if(_debugLevel >= DEBUG_MAX){ _debugPort.print("MEM: "); _debugPort.println((String)ESP.getFreeHeap()); } _debugPort.print("*WM: "); - if (_debugLevel == DEBUG_DEV) - _debugPort.print("[" + (String)level + "] "); + if(_debugLevel == DEBUG_DEV) _debugPort.print("["+(String)level+"] "); _debugPort.print(text); - if (textb) - { + if(textb){ _debugPort.print(" "); _debugPort.print(textb); } @@ -2687,28 +2308,27 @@ void WiFiManager::DEBUG_WM(wm_debuglevel_t level, Generic text, Genericb textb) * @access public * @return {[type]} [description] */ -void WiFiManager::debugSoftAPConfig() -{ -#ifdef ESP8266 - softap_config config; - wifi_softap_get_config(&config); -#elif defined(ESP32) - wifi_config_t conf_config; - esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK - wifi_ap_config_t config = conf_config.ap; -#endif +void WiFiManager::debugSoftAPConfig(){ + #ifdef ESP8266 + softap_config config; + wifi_softap_get_config(&config); + #elif defined(ESP32) + wifi_config_t conf_config; + esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK + wifi_ap_config_t config = conf_config.ap; + #endif - DEBUG_WM(F("SoftAP Configuration")); - DEBUG_WM(FPSTR(D_HR)); - DEBUG_WM(F("ssid: "), (char *)config.ssid); - DEBUG_WM(F("password: "), (char *)config.password); - DEBUG_WM(F("ssid_len: "), config.ssid_len); - DEBUG_WM(F("channel: "), config.channel); - DEBUG_WM(F("authmode: "), config.authmode); - DEBUG_WM(F("ssid_hidden: "), config.ssid_hidden); - DEBUG_WM(F("max_connection: "), config.max_connection); - DEBUG_WM(F("beacon_interval: "), (String)config.beacon_interval + "(ms)"); - DEBUG_WM(FPSTR(D_HR)); + DEBUG_WM(F("SoftAP Configuration")); + DEBUG_WM(FPSTR(D_HR)); + DEBUG_WM(F("ssid: "),(char *) config.ssid); + DEBUG_WM(F("password: "),(char *) config.password); + DEBUG_WM(F("ssid_len: "),config.ssid_len); + DEBUG_WM(F("channel: "),config.channel); + DEBUG_WM(F("authmode: "),config.authmode); + DEBUG_WM(F("ssid_hidden: "),config.ssid_hidden); + DEBUG_WM(F("max_connection: "),config.max_connection); + DEBUG_WM(F("beacon_interval: "),(String)config.beacon_interval + "(ms)"); + DEBUG_WM(FPSTR(D_HR)); } /** @@ -2716,48 +2336,38 @@ void WiFiManager::debugSoftAPConfig() * @access public * @return {[type]} [description] */ -void WiFiManager::debugPlatformInfo() -{ -#ifdef ESP8266 - system_print_meminfo(); - DEBUG_WM(F("getCoreVersion(): "), ESP.getCoreVersion()); - DEBUG_WM(F("system_get_sdk_version(): "), system_get_sdk_version()); - DEBUG_WM(F("system_get_boot_version():"), system_get_boot_version()); - DEBUG_WM(F("getFreeHeap(): "), (String)ESP.getFreeHeap()); -#elif defined(ESP32) - size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); - DEBUG_WM("Free heap: ", freeHeap); - DEBUG_WM("ESP-IDF version: ", esp_get_idf_version()); -#endif +void WiFiManager::debugPlatformInfo(){ + #ifdef ESP8266 + system_print_meminfo(); + DEBUG_WM(F("getCoreVersion(): "),ESP.getCoreVersion()); + DEBUG_WM(F("system_get_sdk_version(): "),system_get_sdk_version()); + DEBUG_WM(F("system_get_boot_version():"),system_get_boot_version()); + DEBUG_WM(F("getFreeHeap(): "),(String)ESP.getFreeHeap()); + #elif defined(ESP32) + size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); + DEBUG_WM("Free heap: ", freeHeap); + DEBUG_WM("ESP-IDF version: ", esp_get_idf_version()); + #endif } -int WiFiManager::getRSSIasQuality(int RSSI) -{ +int WiFiManager::getRSSIasQuality(int RSSI) { int quality = 0; - if (RSSI <= -100) - { + if (RSSI <= -100) { quality = 0; - } - else if (RSSI >= -50) - { + } else if (RSSI >= -50) { quality = 100; - } - else - { + } else { quality = 2 * (RSSI + 100); } return quality; } /** Is this an IP? */ -boolean WiFiManager::isIp(String str) -{ - for (size_t i = 0; i < str.length(); i++) - { +boolean WiFiManager::isIp(String str) { + for (size_t i = 0; i < str.length(); i++) { int c = str.charAt(i); - if (c != '.' && (c < '0' || c > '9')) - { + if (c != '.' && (c < '0' || c > '9')) { return false; } } @@ -2765,31 +2375,25 @@ boolean WiFiManager::isIp(String str) } /** IP to String? */ -String WiFiManager::toStringIp(IPAddress ip) -{ +String WiFiManager::toStringIp(IPAddress ip) { String res = ""; - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { res += String((ip >> (8 * i)) & 0xFF) + "."; } res += String(((ip >> 8 * 3)) & 0xFF); return res; } -boolean WiFiManager::validApPassword() -{ +boolean WiFiManager::validApPassword(){ // check that ap password is valid, return false - if (_apPassword == NULL) - _apPassword = ""; - if (_apPassword != "") - { - if (_apPassword.length() < 8 || _apPassword.length() > 63) - { + if (_apPassword == NULL) _apPassword = ""; + if (_apPassword != "") { + if (_apPassword.length() < 8 || _apPassword.length() > 63) { DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); _apPassword = ""; return false; // @todo FATAL or fallback to empty ? } - DEBUG_WM(DEBUG_VERBOSE, F("AccessPoint set password is VALID")); + DEBUG_WM(DEBUG_VERBOSE,F("AccessPoint set password is VALID")); DEBUG_WM(_apPassword); } return true; @@ -2801,17 +2405,16 @@ boolean WiFiManager::validApPassword() * @param string str string to replace entities * @return string encoded string */ -String WiFiManager::htmlEntities(String str) -{ - str.replace("&", "&"); - str.replace("<", "<"); - str.replace(">", ">"); +String WiFiManager::htmlEntities(String str) { + str.replace("&","&"); + str.replace("<","<"); + str.replace(">",">"); // str.replace("'","'"); // str.replace("\"","""); // str.replace("/": "/"); // str.replace("`": "`"); // str.replace("=": "="); - return str; +return str; } /** @@ -2820,240 +2423,191 @@ String WiFiManager::htmlEntities(String str) * @param {[type]} uint8_t status [description] * @return {[type]} [description] */ -String WiFiManager::getWLStatusString(uint8_t status) -{ - if (status <= 7) - return WIFI_STA_STATUS[status]; +String WiFiManager::getWLStatusString(uint8_t status){ + if(status <= 7) return WIFI_STA_STATUS[status]; return FPSTR(S_NA); } -String WiFiManager::encryptionTypeStr(uint8_t authmode) -{ +String WiFiManager::encryptionTypeStr(uint8_t authmode) { // DEBUG_WM("enc_tye: ",authmode); return AUTH_MODE_NAMES[authmode]; } -String WiFiManager::getModeString(uint8_t mode) -{ - if (mode <= 3) - return WIFI_MODES[mode]; +String WiFiManager::getModeString(uint8_t mode){ + if(mode <= 3) return WIFI_MODES[mode]; return FPSTR(S_NA); } -bool WiFiManager::WiFiSetCountry() -{ +bool WiFiManager::WiFiSetCountry(){ bool ret = false; -#ifdef ESP32 + #ifdef ESP32 // @todo check if wifi is init, no idea how, doesnt seem to be exposed - if (_wificountry == "") - return ret; // skip not set - else if (WiFi.getMode() == WIFI_MODE_NULL) - ; // exception if wifi not init! - else if (_wificountry == "US") - ret = esp_wifi_set_country(&WM_COUNTRY_US) == ESP_OK; - else if (_wificountry == "JP") - ret = esp_wifi_set_country(&WM_COUNTRY_JP) == ESP_OK; - else if (_wificountry == "CN") - ret = esp_wifi_set_country(&WM_COUNTRY_CN) == ESP_OK; - else - DEBUG_WM(DEBUG_ERROR, "[ERROR] country code not found"); - - if (ret) - DEBUG_WM(DEBUG_VERBOSE, "esp_wifi_set_country: " + _wificountry); - else - DEBUG_WM(DEBUG_ERROR, "[ERROR] esp_wifi_set_country failed"); -#endif + if(_wificountry == "") return ret; // skip not set + else if(WiFi.getMode() == WIFI_MODE_NULL); // exception if wifi not init! + else if(_wificountry == "US") ret = esp_wifi_set_country(&WM_COUNTRY_US) == ESP_OK; + else if(_wificountry == "JP") ret = esp_wifi_set_country(&WM_COUNTRY_JP) == ESP_OK; + else if(_wificountry == "CN") ret = esp_wifi_set_country(&WM_COUNTRY_CN) == ESP_OK; + else DEBUG_WM(DEBUG_ERROR,"[ERROR] country code not found"); + + if(ret) DEBUG_WM(DEBUG_VERBOSE,"esp_wifi_set_country: " + _wificountry); + else DEBUG_WM(DEBUG_ERROR,"[ERROR] esp_wifi_set_country failed"); + #endif return ret; } -// set mode ignores WiFi.persistent -bool WiFiManager::WiFi_Mode(WiFiMode_t m, bool persistent) -{ - bool ret; -#ifdef ESP8266 - if ((wifi_get_opmode() == (uint8)m) && !persistent) - { - return true; - } - ETS_UART_INTR_DISABLE(); - if (persistent) - ret = wifi_set_opmode(m); - else - ret = wifi_set_opmode_current(m); - ETS_UART_INTR_ENABLE(); - return ret; -#elif defined(ESP32) - if (persistent && esp32persistent) - WiFi.persistent(true); - ret = WiFi.mode(m); // @todo persistent check persistant mode , NI - if (persistent && esp32persistent) - WiFi.persistent(false); - return ret; -#endif + +// set mode ignores WiFi.persistent +bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { + bool ret; + #ifdef ESP8266 + if((wifi_get_opmode() == (uint8) m ) && !persistent) { + return true; + } + ETS_UART_INTR_DISABLE(); + if(persistent) ret = wifi_set_opmode(m); + else ret = wifi_set_opmode_current(m); + ETS_UART_INTR_ENABLE(); + return ret; + #elif defined(ESP32) + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.mode(m); // @todo persistent check persistant mode , NI + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif } -bool WiFiManager::WiFi_Mode(WiFiMode_t m) -{ - return WiFi_Mode(m, false); +bool WiFiManager::WiFi_Mode(WiFiMode_t m) { + return WiFi_Mode(m,false); } // sta disconnect without persistent -bool WiFiManager::WiFi_Disconnect() -{ -#ifdef ESP8266 - if ((WiFi.getMode() & WIFI_STA) != 0) - { - bool ret; - DEBUG_WM(DEBUG_DEV, F("WIFI station disconnect")); - ETS_UART_INTR_DISABLE(); // @todo probably not needed - ret = wifi_station_disconnect(); - ETS_UART_INTR_ENABLE(); - return ret; - } -#elif defined(ESP32) - DEBUG_WM(DEBUG_DEV, F("WIFI station disconnect")); - return WiFi.disconnect(); // not persistent atm -#endif - return false; +bool WiFiManager::WiFi_Disconnect() { + #ifdef ESP8266 + if((WiFi.getMode() & WIFI_STA) != 0) { + bool ret; + DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); + ETS_UART_INTR_DISABLE(); // @todo probably not needed + ret = wifi_station_disconnect(); + ETS_UART_INTR_ENABLE(); + return ret; + } + #elif defined(ESP32) + DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); + return WiFi.disconnect(); // not persistent atm + #endif + return false; } // toggle STA without persistent -bool WiFiManager::WiFi_enableSTA(bool enable, bool persistent) -{ - DEBUG_WM(DEBUG_DEV, F("WiFi station enable")); -#ifdef ESP8266 - WiFiMode_t newMode; - WiFiMode_t currentMode = WiFi.getMode(); - bool isEnabled = (currentMode & WIFI_STA) != 0; - if (enable) - newMode = (WiFiMode_t)(currentMode | WIFI_STA); - else - newMode = (WiFiMode_t)(currentMode & (~WIFI_STA)); +bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { + DEBUG_WM(DEBUG_DEV,F("WiFi station enable")); + #ifdef ESP8266 + WiFiMode_t newMode; + WiFiMode_t currentMode = WiFi.getMode(); + bool isEnabled = (currentMode & WIFI_STA) != 0; + if(enable) newMode = (WiFiMode_t)(currentMode | WIFI_STA); + else newMode = (WiFiMode_t)(currentMode & (~WIFI_STA)); - if ((isEnabled != enable) || persistent) - { - if (enable) - { - if (persistent) - DEBUG_WM(DEBUG_DEV, F("enableSTA PERSISTENT ON")); - return WiFi_Mode(newMode, persistent); - } - else - { - return WiFi_Mode(newMode, persistent); - } - } - else - { - return true; - } -#elif defined(ESP32) - bool ret; - if (persistent && esp32persistent) - WiFi.persistent(true); - ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform - if (persistent && esp32persistent) - WiFi.persistent(false); - return ret; -#endif + if((isEnabled != enable) || persistent) { + if(enable) { + if(persistent) DEBUG_WM(DEBUG_DEV,F("enableSTA PERSISTENT ON")); + return WiFi_Mode(newMode,persistent); + } else { + return WiFi_Mode(newMode,persistent); + } + } else { + return true; + } + #elif defined(ESP32) + bool ret; + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif } -bool WiFiManager::WiFi_enableSTA(bool enable) -{ - return WiFi_enableSTA(enable, false); +bool WiFiManager::WiFi_enableSTA(bool enable) { + return WiFi_enableSTA(enable,false); } -bool WiFiManager::WiFi_eraseConfig() -{ -#ifdef ESP8266 -#ifndef WM_FIXERASECONFIG - return ESP.eraseConfig(); -#else - // erase config BUG replacement - // https://github.com/esp8266/Arduino/pull/3635 - const size_t cfgSize = 0x4000; - size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; +bool WiFiManager::WiFi_eraseConfig() { + #ifdef ESP8266 + #ifndef WM_FIXERASECONFIG + return ESP.eraseConfig(); + #else + // erase config BUG replacement + // https://github.com/esp8266/Arduino/pull/3635 + const size_t cfgSize = 0x4000; + size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; - for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) - { - if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) - { - return false; - } - } - return true; -#endif -#elif defined(ESP32) - bool ret; - WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! - WiFi.persistent(true); - ret = WiFi.disconnect(true, true); - WiFi.persistent(false); - return ret; -#endif + for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) { + if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) { + return false; + } + } + return true; + #endif + #elif defined(ESP32) + bool ret; + WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! + WiFi.persistent(true); + ret = WiFi.disconnect(true,true); + WiFi.persistent(false); + return ret; + #endif } -uint8_t WiFiManager::WiFi_softap_num_stations() -{ -#ifdef ESP8266 - return wifi_softap_get_station_num(); -#elif defined(ESP32) - return WiFi.softAPgetStationNum(); -#endif +uint8_t WiFiManager::WiFi_softap_num_stations(){ + #ifdef ESP8266 + return wifi_softap_get_station_num(); + #elif defined(ESP32) + return WiFi.softAPgetStationNum(); + #endif } -bool WiFiManager::WiFi_hasAutoConnect() -{ +bool WiFiManager::WiFi_hasAutoConnect(){ return WiFi_SSID() != ""; } -String WiFiManager::WiFi_SSID() -{ -#ifdef ESP8266 - return WiFi.SSID(); -#elif defined(ESP32) - //@todo , workaround only when not connected - wifi_config_t conf; - esp_wifi_get_config(WIFI_IF_STA, &conf); - return String(reinterpret_cast(conf.sta.ssid)); -#endif +String WiFiManager::WiFi_SSID(){ + #ifdef ESP8266 + return WiFi.SSID(); + #elif defined(ESP32) + //@todo , workaround only when not connected + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.ssid)); + #endif } #ifdef ESP32 -void WiFiManager::WiFiEvent(WiFiEvent_t event, system_event_info_t info) -{ - DEBUG_WM(DEBUG_VERBOSE, "[EVENT]", event); - if (event == SYSTEM_EVENT_STA_DISCONNECTED) - { - DEBUG_WM(DEBUG_VERBOSE, "[EVENT] WIFI_REASON:", info.disconnected.reason); - if (info.disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.disconnected.reason == WIFI_REASON_AUTH_FAIL) - { - _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail - } - else - _lastconxresulttmp = WiFi.status(); - if (info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) - DEBUG_WM(DEBUG_VERBOSE, "[EVENT] WIFI_REASON: NO_AP_FOUND"); -#ifdef esp32autoreconnect - DEBUG_WM(DEBUG_VERBOSE, "[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); - WiFi.reconnect(); -#endif +void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ + DEBUG_WM(DEBUG_VERBOSE,"[EVENT]",event); + if(event == SYSTEM_EVENT_STA_DISCONNECTED){ + DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON:",info.disconnected.reason); + if(info.disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.disconnected.reason == WIFI_REASON_AUTH_FAIL){ + _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail + } else _lastconxresulttmp = WiFi.status(); + if(info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON: NO_AP_FOUND"); + #ifdef esp32autoreconnect + DEBUG_WM(DEBUG_VERBOSE,"[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); + WiFi.reconnect(); + #endif } - else if (event == SYSTEM_EVENT_SCAN_DONE) - { + else if(event == SYSTEM_EVENT_SCAN_DONE){ uint16_t scans = WiFi.scanComplete(); WiFi_scanComplete(scans); } } #endif -void WiFiManager::WiFi_autoReconnect() -{ -#ifdef ESP8266 - WiFi.setAutoReconnect(_wifiAutoReconnect); -#elif defined(ESP32) - // if(_wifiAutoReconnect){ - DEBUG_WM(DEBUG_VERBOSE, "ESP32 event handler enabled"); - using namespace std::placeholders; - WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent, this, _1, _2)); - // } -#endif +void WiFiManager::WiFi_autoReconnect(){ + #ifdef ESP8266 + WiFi.setAutoReconnect(_wifiAutoReconnect); + #elif defined(ESP32) + // if(_wifiAutoReconnect){ + DEBUG_WM(DEBUG_VERBOSE,"ESP32 event handler enabled"); + using namespace std::placeholders; + WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); + // } + #endif } From b4cc27cb56e6908f3a9cc28f4b8f3f04252e56dc Mon Sep 17 00:00:00 2001 From: Fernando Llaca Date: Sun, 2 Sep 2018 21:11:59 +0200 Subject: [PATCH 113/146] Added getParameters and getParametersCount methods. Useful for iterating over WiFiManager parameter list --- WiFiManager.cpp | 16 ++++++++++++++++ WiFiManager.h | 4 ++++ 2 files changed, 20 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 2cb5dd4..4eb540b 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -150,6 +150,22 @@ bool WiFiManager::addParameter(WiFiManagerParameter *p) { return true; } +/** + * [getParameters description] + * @access public + */ +WiFiManagerParameter** WiFiManager::getParameters() { + return _params; +} + +/** + * [getParametersCount description] + * @access public + */ +int WiFiManager::getParametersCount() { + return _paramsCount; +} + /** * -------------------------------------------------------------------------------- * WiFiManager diff --git a/WiFiManager.h b/WiFiManager.h index 262189f..3fe03f3 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -198,6 +198,10 @@ class WiFiManager void setSaveConfigCallback( std::function func ); //adds a custom parameter, returns false on failure bool addParameter(WiFiManagerParameter *p); + //returns the list of Parameters + WiFiManagerParameter** getParameters(); + // returns the Parameters Count + int getParametersCount(); //if this is set, it will exit after config, even if connection is unsuccessful. void setBreakAfterConfig(boolean shouldBreak); // if this is set, portal will be blocking and wait until save or exit, From 448e079bc8584ce735504e1aa3538806f44b258b Mon Sep 17 00:00:00 2001 From: Fernando Llaca Date: Sun, 16 Sep 2018 22:49:40 +0200 Subject: [PATCH 114/146] Use a especific version of ArduinoJson --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ca2ba85..d41a13b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ before_install: install: - ln -s $PWD /usr/local/share/arduino/libraries/WiFiManager - arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json" --save-prefs - - arduino --install-library "ArduinoJson" + - arduino --install-library "ArduinoJson:5.13.2" - arduino --install-boards esp8266:esp8266 - arduino --pref "compiler.warning_level=all" --save-prefs # install esp32 From 12fc6516d2729a3ce1afb5b08d671066d15f3c89 Mon Sep 17 00:00:00 2001 From: Fernando Llaca Date: Sun, 16 Sep 2018 22:57:01 +0200 Subject: [PATCH 115/146] Missing semicolon --- examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino b/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino index 5850e40..d3cbe3f 100644 --- a/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino +++ b/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino @@ -31,7 +31,7 @@ void checkButton(){ // is configuration portal requested? if(digitalRead(TRIGGER_PIN) == LOW) { - delay(50) + delay(50); if(digitalRead(TRIGGER_PIN) == LOW) { if(!portalRunning){ Serial.println("Button Pressed, Starting Portal"); From 1c191c1d14674397bc7f89e8f85303fe459bb89d Mon Sep 17 00:00:00 2001 From: Fernando Llaca Date: Sun, 16 Sep 2018 23:08:23 +0200 Subject: [PATCH 116/146] Rename "Old Examples" folder to "Old_Examples", to avoid errors when iterating examples folder. --- .../AutoConnectWithFeedback/AutoConnectWithFeedback.ino | 0 .../AutoConnectWithReset/AutoConnectWithReset.ino | 0 .../AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino | 0 .../AutoConnectWithTimeout/AutoConnectWithTimeout.ino | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename examples/{Old Examples => Old_examples}/AutoConnectWithFeedback/AutoConnectWithFeedback.ino (100%) rename examples/{Old Examples => Old_examples}/AutoConnectWithReset/AutoConnectWithReset.ino (100%) rename examples/{Old Examples => Old_examples}/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino (100%) rename examples/{Old Examples => Old_examples}/AutoConnectWithTimeout/AutoConnectWithTimeout.ino (100%) diff --git a/examples/Old Examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino b/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino similarity index 100% rename from examples/Old Examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino rename to examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino diff --git a/examples/Old Examples/AutoConnectWithReset/AutoConnectWithReset.ino b/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino similarity index 100% rename from examples/Old Examples/AutoConnectWithReset/AutoConnectWithReset.ino rename to examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino diff --git a/examples/Old Examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino b/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino similarity index 100% rename from examples/Old Examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino rename to examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino diff --git a/examples/Old Examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino b/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino similarity index 100% rename from examples/Old Examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino rename to examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino From c88df8631311beb49abae177205dd566d4706c40 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 17 Sep 2018 13:44:06 -0500 Subject: [PATCH 117/146] syntax error in examples --- examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino b/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino index 5850e40..d3cbe3f 100644 --- a/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino +++ b/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino @@ -31,7 +31,7 @@ void checkButton(){ // is configuration portal requested? if(digitalRead(TRIGGER_PIN) == LOW) { - delay(50) + delay(50); if(digitalRead(TRIGGER_PIN) == LOW) { if(!portalRunning){ Serial.println("Button Pressed, Starting Portal"); From 0cd0b75d9e132f591e0654bdf861768fe2be070e Mon Sep 17 00:00:00 2001 From: Shawn A Date: Tue, 18 Sep 2018 11:35:55 -0500 Subject: [PATCH 118/146] added custom html param example pattern --- examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index 2677711..6f9a474 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -92,6 +92,7 @@ void setup() { WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); WiFiManagerParameter custom_token("api_token", "api token", "", 16); WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); + WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 19,"pattern='\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'"); // callbacks wm.setSaveConfigCallback(saveCallback); @@ -102,6 +103,7 @@ void setup() { wm.addParameter(&custom_mqtt_port); wm.addParameter(&custom_token); wm.addParameter(&custom_tokenb); + wm.addParameter(&custom_ipaddress); custom_html.setValue("test",4); custom_token.setValue("test",4); From 0e4af48d549fa67f191ab886610e9fd2016d9cc9 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Wed, 19 Sep 2018 09:54:17 -0500 Subject: [PATCH 119/146] fix example --- examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index 6f9a474..296f639 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -91,8 +91,8 @@ void setup() { WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); WiFiManagerParameter custom_token("api_token", "api token", "", 16); - WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); - WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 19,"pattern='\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'"); + WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces + WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'"); // callbacks wm.setSaveConfigCallback(saveCallback); From aad1a8d9d2492d1e5e80596b17bc206d66b70a64 Mon Sep 17 00:00:00 2001 From: Dontsov Evgeny Date: Sun, 23 Sep 2018 23:19:17 +0300 Subject: [PATCH 120/146] WiFiManagerParameter init() to protected --- WiFiManager.h | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/WiFiManager.h b/WiFiManager.h index 262189f..2d92247 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -118,6 +118,11 @@ class WiFiManagerParameter { int getLabelPlacement(); const char *getCustomHTML(); void setValue(const char *defaultValue, int length); + + protected: + void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom); + void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement); + private: const char *_id; const char *_placeholder; @@ -126,9 +131,6 @@ class WiFiManagerParameter { int _labelPlacement; const char *_customHTML; - void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom); - void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement); - friend class WiFiManager; }; From dbf91a4e8cbe82b1cc42c94ad85436930cf5b052 Mon Sep 17 00:00:00 2001 From: Dontsov Evgeny Date: Mon, 24 Sep 2018 03:28:03 +0300 Subject: [PATCH 121/146] example: custom paramaters with load/save settings --- .../CustomParamsWithConfig.ino | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 examples/CustomParamsWithConfig/CustomParamsWithConfig.ino diff --git a/examples/CustomParamsWithConfig/CustomParamsWithConfig.ino b/examples/CustomParamsWithConfig/CustomParamsWithConfig.ino new file mode 100644 index 0000000..51e4519 --- /dev/null +++ b/examples/CustomParamsWithConfig/CustomParamsWithConfig.ino @@ -0,0 +1,138 @@ + +#include // https://github.com/tzapu/WiFiManager +#include +#include + +#define SETUP_PIN 0 + +class IPAddressParameter : public WiFiManagerParameter { +public: + IPAddressParameter(const char *id, const char *placeholder, IPAddress address) + : WiFiManagerParameter("") { + init(id, placeholder, address.toString().c_str(), 16, "", WFM_LABEL_BEFORE); + } + + bool getValue(IPAddress &ip) { + return ip.fromString(WiFiManagerParameter::getValue()); + } +}; + +class IntParameter : public WiFiManagerParameter { +public: + IntParameter(const char *id, const char *placeholder, long value, const uint8_t length = 10) + : WiFiManagerParameter("") { + init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); + } + + long getValue() { + return String(WiFiManagerParameter::getValue()).toInt(); + } +}; + +class FloatParameter : public WiFiManagerParameter { +public: + FloatParameter(const char *id, const char *placeholder, float value, const uint8_t length = 10) + : WiFiManagerParameter("") { + init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); + } + + float getValue() { + return String(WiFiManagerParameter::getValue()).toFloat(); + } +}; + +struct Settings { + float f; + int i; + char s[20]; + uint32_t ip; +} sett; + + +void setup() { + pinMode(SETUP_PIN, INPUT_PULLUP); + Serial.begin(9600); + + //Delay to push SETUP button + Serial.println("Press setup button"); + for (int sec = 3; sec > 0; sec--) { + Serial.print(sec); + Serial.print(".."); + delay(1000); + } + + EEPROM.begin( 512 ); + EEPROM.get(0, sett); + Serial.println("Settings loaded"); + + if (digitalRead(SETUP_PIN) == LOW) { + // Button pressed + Serial.println("SETUP"); + + WiFiManager wm; + + sett.s[19] = '\0'; //add null terminator at the end cause overflow + WiFiManagerParameter param_str( "str", "param_string", sett.s, 20); + FloatParameter param_float( "float", "param_float", sett.f); + IntParameter param_int( "int", "param_int", sett.i); + + IPAddress ip(sett.ip); + IPAddressParameter param_ip("ip", "param_ip", ip); + + wm.addParameter( ¶m_str ); + wm.addParameter( ¶m_float ); + wm.addParameter( ¶m_int ); + wm.addParameter( ¶m_ip ); + + //SSID & password parameters already included + wm.startConfigPortal(); + + strncpy(sett.s, param_str.getValue(), 20); + sett.s[19] = '\0'; + sett.f = param_float.getValue(); + sett.i = param_int.getValue(); + + Serial.print("String param: "); + Serial.println(sett.s); + Serial.print("Float param: "); + Serial.println(sett.f); + Serial.print("Int param: "); + Serial.println(sett.i, DEC); + + if (param_ip.getValue(ip)) { + sett.ip = ip; + + Serial.print("IP param: "); + Serial.println(ip); + } else { + Serial.println("Incorrect IP"); + } + + EEPROM.put(0, sett); + if (EEPROM.commit()) { + Serial.println("Settings saved"); + } else { + Serial.println("EEPROM error"); + } + } + else { + Serial.println("WORK"); + + //connect to saved SSID + WiFi.begin(); + + //do smth + Serial.print("String param: "); + Serial.println(sett.s); + Serial.print("Float param: "); + Serial.println(sett.f); + Serial.print("Int param: "); + Serial.println(sett.i, DEC); + Serial.print("IP param: "); + IPAddress ip(sett.ip); + Serial.println(ip); + } +} + +void loop() { +} From 85b2319b593a69eb49a0e4c96aefb9a0cc812f02 Mon Sep 17 00:00:00 2001 From: Dontsov Evgeny Date: Mon, 24 Sep 2018 03:45:49 +0300 Subject: [PATCH 122/146] correct your idea about deflength --- WiFiManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 7eef612..9b083da 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -71,7 +71,7 @@ void WiFiManagerParameter::setValue(const char *defaultValue, int length) { int deflength = strlen(defaultValue); // length actual // use the defult length if it's longer, // @todo consider it might be useful to fail, so user knows they were wrong - if(_length < length){ + if(_length < deflength){ // Serial.println("defaultValue length mismatch"); _length = deflength; } From 7d42423894e3006978d8f7d1ab1b2107a446190b Mon Sep 17 00:00:00 2001 From: Dontsov Evgeny Date: Mon, 24 Sep 2018 04:19:21 +0300 Subject: [PATCH 123/146] value limit is length --- WiFiManager.cpp | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 9b083da..365eb4f 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -68,20 +68,11 @@ void WiFiManagerParameter::setValue(const char *defaultValue, int length) { return; } _length = length; - int deflength = strlen(defaultValue); // length actual - // use the defult length if it's longer, - // @todo consider it might be useful to fail, so user knows they were wrong - if(_length < deflength){ - // Serial.println("defaultValue length mismatch"); - _length = deflength; - } - _value = new char[_length + 1]; - for (int i = 0; i < _length + 1; i++) { - _value[i] = 0; - } + _value = new char[_length + 1]; + memset(_value, 0, _length + 1); // explicit null + if (defaultValue != NULL) { strncpy(_value, defaultValue, _length); - _value[_length] = '\0'; // explicit null } } const char* WiFiManagerParameter::getValue() { From 613ec354bdf5eeeb702e4bcb7bb97d43597a26e2 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Wed, 26 Sep 2018 09:44:59 -0500 Subject: [PATCH 124/146] param defvalue mismatch checking --- WiFiManager.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 365eb4f..f0ad474 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -62,13 +62,20 @@ WiFiManagerParameter::~WiFiManagerParameter() { _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; } - _length = length; - _value = new char[_length + 1]; + + // 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) { From 193fdf177c3c52115b6f40027457d8399967d932 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Wed, 26 Sep 2018 09:45:03 -0500 Subject: [PATCH 125/146] fix example --- examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index 296f639..e8be11b 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -92,7 +92,7 @@ void setup() { WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); WiFiManagerParameter custom_token("api_token", "api token", "", 16); WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces - WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'"); + WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // callbacks wm.setSaveConfigCallback(saveCallback); From fe772f6bf5568e5717e4b4955dcfb2ad4dd996cb Mon Sep 17 00:00:00 2001 From: Shawn A Date: Wed, 26 Sep 2018 09:47:59 -0500 Subject: [PATCH 126/146] fix example --- examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino index 9d283ec..ef8e1eb 100644 --- a/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino +++ b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino @@ -48,6 +48,7 @@ void doWiFiManager(){ if(digitalRead(TRIGGER_PIN) == LOW && (!portalRunning)) { if(startCP){ Serial.println("Button Pressed, Starting Config Portal"); + wm.setConfigPortalBlocking(false); wm.startConfigPortal(); } else{ From 8e7b43a02948febdb5acebb1b224015cfd847687 Mon Sep 17 00:00:00 2001 From: Shawn A Date: Thu, 27 Sep 2018 13:39:12 -0500 Subject: [PATCH 127/146] rename example --- .../ParamsChildClass.ino} | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) rename examples/{CustomParamsWithConfig/CustomParamsWithConfig.ino => ParamsChildClass/ParamsChildClass.ino} (98%) diff --git a/examples/CustomParamsWithConfig/CustomParamsWithConfig.ino b/examples/ParamsChildClass/ParamsChildClass.ino similarity index 98% rename from examples/CustomParamsWithConfig/CustomParamsWithConfig.ino rename to examples/ParamsChildClass/ParamsChildClass.ino index 51e4519..c5d991a 100644 --- a/examples/CustomParamsWithConfig/CustomParamsWithConfig.ino +++ b/examples/ParamsChildClass/ParamsChildClass.ino @@ -1,4 +1,6 @@ - +/** + * WiFiManagerParameter child class example + */ #include // https://github.com/tzapu/WiFiManager #include #include From 669dad42064dd88c506fc8a9394b3b2583953850 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Mon, 1 Oct 2018 12:28:37 -0500 Subject: [PATCH 128/146] starting readme updates --- README.md | 56 ++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 45 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 1f355a2..e4c3857 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,9 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - [Wishlist](#wishlist) - [Quick start](#quick-start) - Installing - - [Through Library Manager](#install-through-library-manager) - - [From Github](#checkout-from-github) + - [Arduino - Through Library Manager](#install-through-library-manager) + - [Arduino - From Github](#checkout-from-github) + - [PlatformIO] - [Using](#using) - [Documentation](#documentation) - [Access Point Password](#password-protect-the-configuration-access-point) @@ -46,12 +47,13 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are ## How It Works -- when your ESP starts up, it sets it up in Station mode and tries to connect to a previously saved Access Point +- When your ESP starts up, it sets it up in Station mode and tries to connect to a previously saved Access Point - if this is unsuccessful (or no previous network saved) it moves the ESP into Access Point mode and spins up a DNS and WebServer (default ip 192.168.4.1) - using any wifi enabled device with a browser (computer, phone, tablet) connect to the newly created Access Point - because of the Captive Portal and the DNS server you will either get a 'Join to network' type of popup or get any domain you try to access redirected to the configuration portal - choose one of the access points scanned, enter password, click save - ESP will try to connect. If successful, it relinquishes control back to your app. If not, reconnect to AP and reconfigure. +- There are options to change this behavior or manually start the configportal and webportal independantly as well as run them in non blocking mode. ## How It Looks ![ESP8266 WiFi Captive Portal Homepage](http://i.imgur.com/YPvW9eql.png) ![ESP8266 WiFi Captive Portal Configuration](http://i.imgur.com/oicWJ4gl.png) @@ -67,9 +69,35 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - [x] add to PlatformIO - [ ] add multiple sets of network credentials - [x] allow users to customize CSS -- [ ] ESP32 support or instructions - [ ] rewrite documentation for simplicity, based on scenarios/goals -- [ ] rely on the SDK's built in auto connect more than forcing a connect + +### Development +- [x] ESP32 support +- [x] rely on the SDK's built in auto connect more than forcing a connect +- [x] add non blocking mode +- [x] easy customization of strings +- [x] hostname support +- [x] fix various bugs and workarounds for esp SDK issues +- [x] additional info page items +- [x] last status display / faiilure reason +- [x] customizeable menu +- [x] seperate custom params page +- [x] ondemand webportal +- [x] complete refactor of code to segment functions +- [x] wiif scan icons or percentage display +- [x] invert class for dark mode +- [x] more template tokens +- [x] progmem for all strings +- [ ] new callbacks +- [ ] new callouts / filters +- [ ] shared web server instance +- [x] latest esp idf/sdk support +- [x] wm is now non persistent, will not erase or change stored esp config on esp8266 +- [x] tons of debugging output / levels +- [ ] disable captiveportal +- [ ] preload wiifscans, faster page loads +- [ ] softap stability fixes when sta is not connected + ## Quick Start @@ -93,14 +121,10 @@ __Github version works with release 2.4.0 or newer of the [ESP8266 core for Ardu ### Using - Include in your sketch ```cpp -#include //ESP8266 Core WiFi Library (you most likely already have this in your sketch) - -#include //Local DNS Server used for redirecting all requests to the configuration portal -#include //Local WebServer used to serve the configuration portal #include //https://github.com/tzapu/WiFiManager WiFi Configuration Magic ``` -- Initialize library, in your setup function add +- Initialize library, in your setup function add, NOTEif you are using non blocking you will make sure you create this in global scope or handle appropriatly , it will not work if in setup and using non blocking mode. ```cpp WiFiManager wifiManager; ``` @@ -284,6 +308,14 @@ Debug is enabled by default on Serial. To disable add before autoConnect wifiManager.setDebugOutput(false); ``` +You can customize the debug level by changing `_debugLevel` in source +options are: +* DEBUG_ERROR +* DEBUG_NOTIFY +* DEBUG_VERBOSE +* DEBUG_DEV +* DEBUG_MAX + ## Troubleshooting If you get compilation errors, more often than not, you may need to install a newer version of the ESP8266 core for Arduino. @@ -296,6 +328,8 @@ If you connect to the created configuration Access Point but the configuration p If trying to connect ends up in an endless loop, try to add `setConnectTimeout(60)` before `autoConnect();`. The parameter is timeout to try connecting in seconds. ## Releases +#### 1.0.1 + #### 0.12 - removed 204 header response - fixed incompatibility with other libs using isnan and other std:: functions without namespace @@ -360,7 +394,7 @@ The support and help I got from the community has been nothing short of phenomen __THANK YOU__ -[Shawn A](https://github.com/tablatronix) +[Shawn A aka tablatronix](https://github.com/tablatronix) [bbx10](https://github.com/bbx10) From ec1d474d7b5ab3e0bdf7ca37c29aa43ae19e4900 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 5 Oct 2018 14:29:11 -0500 Subject: [PATCH 129/146] readme and comments --- README.md | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++ WiFiManager.h | 38 ++++++++++-------- 2 files changed, 130 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index e4c3857..a032860 100644 --- a/README.md +++ b/README.md @@ -431,3 +431,112 @@ And countless others * https://github.com/chriscook8/esp-arduino-apboot * https://github.com/esp8266/Arduino/tree/master/libraries/DNSServer/examples/CaptivePortalAdvanced * Built by AlexT https://github.com/tzapu + +#### THIS BRANCH - Development +## Development Overview + +### Added Public Methods +`setConfigPortalBlocking` + +`setShowStaticFields` + +`setCaptivePortalEnable` + +`setRestorePersistent` + +`setCaptivePortalClientCheck` + +`setWebPortalClientCheck` + +`startWebPortal` + +`stopWebPortal` + +`process` + +`disconnect` + +`erase` + +` debugSoftAPConfig` + +` debugPlatformInfo` + +`setScanDispPerc` + +`setHostname` + +`setMenu(menu_page_t[])` + +`setWiFiAutoReconnect` + +` setSTAStaticIPConfig(..,dns)` + +`setShowDnsFields` + +`getLastConxResult` + +`getWLStatusString` + +`getModeString` + +`getWiFiIsSaved` + +`setShowInfoErase` + +`setEnableConfigPortal` + +`setCountry` + +`setClass` + +`htmleEtities` + + +### WiFiManagerParameter +`WiFiManagerParameter(id,label)` + +`WiFiManagerParameter.setValue(value,length)` + +`getParameters` + +`getParametersCount` + + +### Constructors +`WiFiManager(Stream& consolePort)` + +## define flags +❗️ **Defines cannot be set in user sketches** +`#define WM_MDNS // use MDNS` +`#define WM_FIXERASECONFIG // use erase flash fix, esp8266 2.4.0` +`#define WM_ERASE_NVS // esp32 erase(true) will erase NVS` +`#include // esp32 info page will show last reset reasons if this file is included` + +## Changes +- ESP32 support ( fairly stable ) +- complete refactor of strings `strings_en.h` +- adds new tokens for wifiscan, and some classes (left , invert icons, MSG color) +- adds status callout panel default, primary, special colors +- adds tons of info on info page, and erase capability +- adds signal icons, replaces percentage ( has hover titles ) +- adds labels to all inputs (replaces placeholders) +- all html ( and eventually all strings except debug) moved to `strings_en.h` +- added additional debugging, compressed debug lines, debuglevels +- persistent disabled, and restored via de/con-stuctor (uses `setRestorePersistent`) +- should retain all user modes including AP, should not overwrite or persist user modes or configs,even STA (`storeSTAmode`) (BUGGY) +- ⚠️ return values may have changed depending on portal abort, or timeout ( `portalTimeoutResult`,`portalAbortResult`) +- params memory is auto allocated by increment of `WIFI_MANAGER_MAX_PARAMS(5)` when exceeded, user no longer needs to specify this at all. +- addparameter now returns bool, and it returns false if param ID is not alphanum [0-9,A-Z,a-z,_] +- param field ids allow {I} token to use param_n instead of string in case someones wants to change this due to i18n or character issues +- provides `#DEFINE FIXERASECONFIG` to help deal with https://github.com/esp8266/Arduino/pull/3635 +- failure reason reporting on portal +- set esp8266 sta hostname, esp32 sta+ap hostname ( DHCP client id) +- pass in debug stream in constructor WiFiManager(Stream& consolePort) +- you can force ip fields off with showxfields(false) if you set _disableIpFields=true +- param menu/page (setup) added to separate params from wifi page, handled automatically by setMenu +- set custom root menu +- disable configportal on autoconnect +- wm parameters init is now protected, allowing child classes, example included +- wifiscans are precached and async for faster page loads, refresh forces rescan +- adds esp32 gettemperature ( currently commented out, useful for relative measurement only ) \ No newline at end of file diff --git a/WiFiManager.h b/WiFiManager.h index 97d3103..b591f50 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -31,8 +31,8 @@ // #include "soc/efuse_reg.h" // include to add efuse chip rev to info, getChipRevision() is almost always the same though, so not sure why it matters. -// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge -// autoreconnect status WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 +// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge, deprecated +// autoreconnect is WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 #define WM_WEBSERVERSHIM // use webserver shim lib @@ -174,6 +174,24 @@ class WiFiManager bool erase(); bool erase(bool opt); + //adds a custom parameter, returns false on failure + bool addParameter(WiFiManagerParameter *p); + //returns the list of Parameters + WiFiManagerParameter** getParameters(); + // returns the Parameters Count + int getParametersCount(); + + + //called when AP mode and config portal is started + void setAPCallback( std::function func ); + //called when settings reset have been triggered + void setConfigResetCallback(void(*func)(void)); + //called when settings have been changed and connection was successful + void setSaveConfigCallback( std::function func ); + //called when settings before have been changed and connection was successful + void setPreSaveConfigCallback( std::function func ); + + //sets timeout before AP,webserver loop ends and exits even if there has been no setup. //useful for devices that failed to connect at some point and got stuck in a webserver loop //in seconds setConfigPortalTimeout is a new name for setTimeout, ! not used if setConfigPortalBlocking @@ -194,20 +212,6 @@ class WiFiManager void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); //sets config for a static IP with DNS void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns); - //called when AP mode and config portal is started - void setAPCallback( std::function func ); - //called when settings reset have been triggered - void setConfigResetCallback(void(*func)(void)); - //called when settings have been changed and connection was successful - void setSaveConfigCallback( std::function func ); - //called when settings before have been changed and connection was successful - void setPreSaveConfigCallback( std::function func ); - //adds a custom parameter, returns false on failure - bool addParameter(WiFiManagerParameter *p); - //returns the list of Parameters - WiFiManagerParameter** getParameters(); - // returns the Parameters Count - int getParametersCount(); //if this is set, it will exit after config, even if connection is unsuccessful. void setBreakAfterConfig(boolean shouldBreak); // if this is set, portal will be blocking and wait until save or exit, @@ -465,7 +469,7 @@ class WiFiManager template void DEBUG_WM(Generic text); - template + template void DEBUG_WM(wm_debuglevel_t level,Generic text); template void DEBUG_WM(Generic text,Genericb textb); From b091ee00d8c62f9a062ae5e7c8872f27753e7109 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 5 Oct 2018 15:04:25 -0500 Subject: [PATCH 130/146] working on readme --- README.md | 213 +++++++++++++++++++++++++----------------------------- 1 file changed, 99 insertions(+), 114 deletions(-) diff --git a/README.md b/README.md index a032860..7e53338 100644 --- a/README.md +++ b/README.md @@ -264,7 +264,7 @@ wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddr ##### Custom Station (client) Static IP Configuration This will make use the specified IP configuration instead of using DHCP in station mode. ```cpp -wifiManager.setSTAStaticIPConfig(IPAddress(192,168,0,99), IPAddress(192,168,0,1), IPAddress(255,255,255,0)); +wifiManager.setSTAStaticIPConfig(IPAddress(192,168,0,99), IPAddress(192,168,0,1), IPAddress(255,255,255,0)); // optional DNS 4th argument ``` There are a couple of examples in the examples folder that show you how to set a static IP and even how to configure it through the web configuration portal. @@ -276,7 +276,7 @@ You can use this to any html bit to the head of the configuration portal. If you ```cpp wifiManager.setCustomHeadElement(""); ``` -- inject a custom bit of html in the configuration form +- inject a custom bit of html in the configuration/param form ```cpp WiFiManagerParameter custom_text("

This is just a text paragraph

"); wifiManager.addParameter(&custom_text); @@ -287,6 +287,14 @@ Just add the bit you want added as the last parameter to the custom parameter co WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "iot.eclipse", 40, " readonly"); ``` +#### Theming +You can customize certain elements of the default template with some builtin classes +```CPP +wifiManager.setClass("invert"); // dark theme +wifiManager.setScanDispPerc(true); // display percentages instead of graphs for RSSI +``` +There are additional classes in the css you can use in your custom html , see the example template. + #### Filter Networks You can filter networks based on signal quality and show/hide duplicate networks. @@ -303,11 +311,16 @@ wifiManager.setRemoveDuplicateAPs(false); ``` #### Debug -Debug is enabled by default on Serial. To disable add before autoConnect +Debug is enabled by default on `Serial` in non-stable releases. To disable add before autoConnect/startConfigPortal ```cpp wifiManager.setDebugOutput(false); ``` +You can pass in a custom stream via constructor +```CPP +WiFiManager wifiManager(Serial1); +``` + You can customize the debug level by changing `_debugLevel` in source options are: * DEBUG_ERROR @@ -327,115 +340,14 @@ If you connect to the created configuration Access Point but the configuration p If trying to connect ends up in an endless loop, try to add `setConnectTimeout(60)` before `autoConnect();`. The parameter is timeout to try connecting in seconds. +I get stuck in ap mode when the power goes out or modem resets, try a setConfigPortalTimeout(seconds). This will cause the configportal to close after no activity, and you can reboot or attempt reconnection in your code. + ## Releases -#### 1.0.1 +### 1.0.1 -#### 0.12 -- removed 204 header response -- fixed incompatibility with other libs using isnan and other std:: functions without namespace +### Development Overview -##### 0.11 -- a lot more reliable reconnecting to networks -- custom html in custom parameters (for read only params) -- custom html in custom parameter form (like labels) -- custom head element (like custom css) -- sort networks based on signal quality -- remove duplicate networks - -##### 0.10 -- some css changes -- bug fixes and speed improvements -- added an alternative to waitForConnectResult() for debugging -- changed `setTimeout(seconds)` to `setConfigPortalTimeout(seconds)` - -##### 0.9 - - fixed support for encoded characters in ssid/pass - -##### 0.8 - - made it compile on older versions of ESP8266 core as well, tested down to 2.0.0 - - added simple example for Custom IP - -##### 0.7 - - added static IP in station mode - - added example of persisting custom IP to FS config.json - - more option on portal homepage - - added on PlatformIO - -##### 0.6 - - custom parameters - - prettier - - on demand config portal - - commit #100 :D - -##### 0.5 - - Added to Arduino Boards Manager - Thanks Max - - moved most stuff to PROGMEM - - added signal quality and a nice little padlock to show which networks are encrypted - -##### v0.4 - all of it user contributed changes - Thank you - - added ability to password protect the configuration Access Point - - callback for enter configuration mode - - memory allocation improvements - -##### v0.3 - - removed the need for EEPROM and works with the 2.0.0 and above stable release of the ESP8266 for Arduino IDE package - - removed restart on save of credentials - - updated examples - -##### v0.2 -needs the latest staging version (or at least a recent release of the staging version) to work - -##### v0.1 -works with the staging release ver. 1.6.5-1044-g170995a, built on Aug 10, 2015 of the ESP8266 Arduino library. - - -### Contributions and thanks -The support and help I got from the community has been nothing short of phenomenal. I can't thank you guys enough. This is my first real attept in developing open source stuff and I must say, now I understand why people are so dedicated to it, it is because of all the wonderful people involved. - -__THANK YOU__ - -[Shawn A aka tablatronix](https://github.com/tablatronix) - -[bbx10](https://github.com/bbx10) - -[kentaylor](https://github.com/kentaylor) - -[Maximiliano Duarte](https://github.com/domonetic) - -[alltheblinkythings](https://github.com/alltheblinkythings) - -[Niklas Wall](https://github.com/niklaswall) - -[Jakub Piasecki](https://github.com/zaporylie) - -[Peter Allan](https://github.com/alwynallan) - -[John Little](https://github.com/j0hnlittle) - -[markaswift](https://github.com/markaswift) - -[franklinvv](https://github.com/franklinvv) - -[Alberto Ricci Bitti](https://github.com/riccibitti) - -[SebiPanther](https://github.com/SebiPanther) - -[jonathanendersby](https://github.com/jonathanendersby) - -[walthercarsten](https://github.com/walthercarsten) - -And countless others - -#### Inspiration - * http://www.esp8266.com/viewtopic.php?f=29&t=2520 - * https://github.com/chriscook8/esp-arduino-apboot - * https://github.com/esp8266/Arduino/tree/master/libraries/DNSServer/examples/CaptivePortalAdvanced - * Built by AlexT https://github.com/tzapu - -#### THIS BRANCH - Development -## Development Overview - -### Added Public Methods +#### Added Public Methods `setConfigPortalBlocking` `setShowStaticFields` @@ -493,7 +405,7 @@ And countless others `htmleEtities` -### WiFiManagerParameter +#### WiFiManagerParameter `WiFiManagerParameter(id,label)` `WiFiManagerParameter.setValue(value,length)` @@ -503,17 +415,20 @@ And countless others `getParametersCount` -### Constructors +#### Constructors `WiFiManager(Stream& consolePort)` -## define flags +#### define flags ❗️ **Defines cannot be set in user sketches** `#define WM_MDNS // use MDNS` + `#define WM_FIXERASECONFIG // use erase flash fix, esp8266 2.4.0` + `#define WM_ERASE_NVS // esp32 erase(true) will erase NVS` + `#include // esp32 info page will show last reset reasons if this file is included` -## Changes +#### Changes Overview - ESP32 support ( fairly stable ) - complete refactor of strings `strings_en.h` - adds new tokens for wifiscan, and some classes (left , invert icons, MSG color) @@ -539,4 +454,74 @@ And countless others - disable configportal on autoconnect - wm parameters init is now protected, allowing child classes, example included - wifiscans are precached and async for faster page loads, refresh forces rescan -- adds esp32 gettemperature ( currently commented out, useful for relative measurement only ) \ No newline at end of file +- adds esp32 gettemperature ( currently commented out, useful for relative measurement only ) + +#### 0.12 +- removed 204 header response +- fixed incompatibility with other libs using isnan and other std:: functions without namespace + +##### 0.11 +- a lot more reliable reconnecting to networks +- custom html in custom parameters (for read only params) +- custom html in custom parameter form (like labels) +- custom head element (like custom css) +- sort networks based on signal quality +- remove duplicate networks + +##### 0.10 +- some css changes +- bug fixes and speed improvements +- added an alternative to waitForConnectResult() for debugging +- changed `setTimeout(seconds)` to `setConfigPortalTimeout(seconds)` + +### Contributions and thanks +The support and help I got from the community has been nothing short of phenomenal. I can't thank you guys enough. This is my first real attept in developing open source stuff and I must say, now I understand why people are so dedicated to it, it is because of all the wonderful people involved. + +__THANK YOU__ + +The esp8266 and esp32 arduino and idf maintainers! + +[Shawn A aka tablatronix](https://github.com/tablatronix) + +[liebman](https://github.com/liebman) + +[Evgeny Dontsov](https://github.com/dontsovcmc) + +[Chris Marrin](https://github.com/cmarrin) + +[bbx10](https://github.com/bbx10) + +[kentaylor](https://github.com/kentaylor) + +[Maximiliano Duarte](https://github.com/domonetic) + +[alltheblinkythings](https://github.com/alltheblinkythings) + +[Niklas Wall](https://github.com/niklaswall) + +[Jakub Piasecki](https://github.com/zaporylie) + +[Peter Allan](https://github.com/alwynallan) + +[John Little](https://github.com/j0hnlittle) + +[markaswift](https://github.com/markaswift) + +[franklinvv](https://github.com/franklinvv) + +[Alberto Ricci Bitti](https://github.com/riccibitti) + +[SebiPanther](https://github.com/SebiPanther) + +[jonathanendersby](https://github.com/jonathanendersby) + +[walthercarsten](https://github.com/walthercarsten) + +And countless others + +#### Inspiration + * http://www.esp8266.com/viewtopic.php?f=29&t=2520 + * https://github.com/chriscook8/esp-arduino-apboot + * https://github.com/esp8266/Arduino/tree/master/libraries/DNSServer/examples/CaptivePortalAdvanced + * Built by AlexT https://github.com/tzapu + From ea67dc22c0e58fe8023018b72638e3ec77287507 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sat, 6 Oct 2018 14:11:20 -0500 Subject: [PATCH 131/146] remove resetsettings --- .../AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino b/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino index 4a2c4dd..532ceec 100644 --- a/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino +++ b/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino @@ -36,7 +36,7 @@ void setup() { //Local intialization. Once its business is done, there is no need to keep it around WiFiManager wm; //reset settings - for testing - wm.resetSettings(); + // wm.resetSettings(); //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode wm.setAPCallback(configModeCallback); From bef46b9e72c47d1892ea813c8af4b1540d030ce4 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 11 Oct 2018 15:23:48 -0500 Subject: [PATCH 132/146] adds setSaveParamsCallback clean up examples --- WiFiManager.cpp | 66 +++++++++++-------- WiFiManager.h | 17 +++-- .../OnDemandConfigPortal.ino | 44 +++++-------- 3 files changed, 65 insertions(+), 62 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 03d5050..235b9b9 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -601,8 +601,8 @@ uint8_t WiFiManager::processConfigPortal(){ DEBUG_WM(F("Got IP Address:")); DEBUG_WM(WiFi.localIP()); - if ( _savecallback != NULL) { - _savecallback(); + if ( _savewificallback != NULL) { + _savewificallback(); } stopConfigPortal(); return WL_CONNECTED; // CONNECT SUCCESS @@ -614,8 +614,8 @@ uint8_t WiFiManager::processConfigPortal(){ // 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 ( _savecallback != NULL) { - _savecallback(); + if ( _savewificallback != NULL) { + _savewificallback(); } stopConfigPortal(); return WL_CONNECT_FAILED; // CONNECT FAIL @@ -1330,18 +1330,8 @@ void WiFiManager::handleParamSave() { DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); handleRequest(); - // @todo use new callback for before paramsaves - if ( _presavecallback != NULL) { - _presavecallback(); - } - doParamSave(); - // @todo use new callback for paramsaves - if ( _savecallback != NULL) { - _savecallback(); - } - String page = getHTTPHead(FPSTR(S_titleparamsaved)); // @token titleparamsaved page += FPSTR(HTTP_PARAMSAVED); page += FPSTR(HTTP_END); @@ -1353,13 +1343,18 @@ void WiFiManager::handleParamSave() { } void WiFiManager::doParamSave(){ + // @todo use new callback for before paramsaves, is this really needed? + if ( _presavecallback != NULL) { + _presavecallback(); + } + //parameters if(_paramsCount > 0){ DEBUG_WM(DEBUG_VERBOSE,F("Parameters")); DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); for (int i = 0; i < _paramsCount; i++) { if (_params[i] == NULL) { - break; + break; // @todo might not be needed anymore } //read parameter from server String name = (String)FPSTR(S_parampre)+(String)i; @@ -1376,6 +1371,11 @@ void WiFiManager::doParamSave(){ } DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); } + + if ( _saveparamscallback != NULL) { + _saveparamscallback(); + } + } /** @@ -2007,33 +2007,44 @@ void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { /** * setAPCallback, set a callback when softap is started * @access public - * @param {[type]} void (*func)(WiFiManager* myWiFiManager) [description] + * @param {[type]} void (*func)(WiFiManager* wminstance) */ void WiFiManager::setAPCallback( std::function func ) { _apcallback = func; } - + /** * setSaveConfigCallback, set a save config callback after closing configportal - * @todo only calls if configportal stopped + * @note calls only if wifi is saved or changed, or setBreakAfterConfig(true) * @access public - * @param {[type]} void (*func)(void) [description] + * @param {[type]} void (*func)(void) */ void WiFiManager::setSaveConfigCallback( std::function func ) { - _savecallback = func; + _savewificallback = func; } -//start up reset config callback -void WiFiManager::setConfigResetCallback(void(*func)(void)) { +/** + * setConfigResetCallback, set a callback to occur when a resetSettings() occurs + * @access public + * @param {[type]} void(*func)(void) + */ +void WiFiManager::setConfigResetCallback( std::function func ) { _resetcallback = func; } -//sets a custom element to add to head, like a new style tag /** - * setPreSaveConfigCallback, set a pre save config callback after closing configportal - * @todo only calls if configportal stopped + * setSaveParamsCallback, set a save params callback on params save in wifi or params pages * @access public - * @param {[type]} void (*func)(void) [description] + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setSaveParamsCallback( std::function func ) { + _saveparamscallback = func; +} + +/** + * setPreSaveConfigCallback, set a callback to fire before saving wifi or params + * @access public + * @param {[type]} void (*func)(void) */ void WiFiManager::setPreSaveConfigCallback( std::function func ) { _presavecallback = func; @@ -2049,10 +2060,9 @@ void WiFiManager::setCustomHeadElement(const char* element) { _customHeadElement = element; } -//if this is true, remove duplicated Access Points - defaut true /** * toggle wifiscan hiding of duplicate ssid names - * if enabled, then the webportal wifiscan page will show all aps + * if this is false, wifiscan will remove duplicat Access Points - defaut true * @access public * @param boolean removeDuplicates [true] */ diff --git a/WiFiManager.h b/WiFiManager.h index b591f50..1774d24 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -182,12 +182,16 @@ class WiFiManager int getParametersCount(); + // SET CALLBACKS + //called when AP mode and config portal is started void setAPCallback( std::function func ); //called when settings reset have been triggered - void setConfigResetCallback(void(*func)(void)); - //called when settings have been changed and connection was successful + void setConfigResetCallback( std::function func ); + //called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) void setSaveConfigCallback( std::function func ); + //called when settings have been changed and connection was successful + void setSaveParamsCallback( std::function func ); //called when settings before have been changed and connection was successful void setPreSaveConfigCallback( std::function func ); @@ -277,7 +281,8 @@ class WiFiManager #else using WM_WebServer = ESP8266WebServer; #endif - std::unique_ptr server; + + std::unique_ptr server; std::vector _menuIds; std::vector _menuIdsDefault = {"wifi","info","exit"}; @@ -477,10 +482,12 @@ class WiFiManager void DEBUG_WM(wm_debuglevel_t level, Generic text,Genericb textb); // callbacks + // @todo use cb list (vector) maybe event ids, allow no return value std::function _apcallback; - std::function _savecallback; + std::function _savewificallback; std::function _presavecallback; - void (*_resetcallback)(void) = NULL; // @todo change to std func + std::function _saveparamscallback; + std::function _resetcallback; template auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index e8be11b..3ded79b 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -7,6 +7,7 @@ const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; WiFiManager wm; +bool TEST_CP = true; // always start the configportal char ssid[] = "*************"; // your network SSID (name) char pass[] = "********"; // your network password @@ -34,20 +35,24 @@ void debugchipid(){ // ESP32 Chip ID = 507726A4AE30 } -void saveCallback(){ - Serial.println("saveCallback fired"); +void saveWifiCallback(){ + Serial.println("[CALLBACK] saveCallback fired"); } //gets called when WiFiManager enters configuration mode void configModeCallback (WiFiManager *myWiFiManager) { - Serial.println("configModeCallback fired"); + Serial.println("[CALLBACK] configModeCallback fired"); // myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // Serial.println(WiFi.softAPIP()); //if you used auto generated SSID, print it // Serial.println(myWiFiManager->getConfigPortalSSID()); } +void saveParamCallback(){ + Serial.println("[CALLBACK] saveParamCallback fired"); +} + void setup() { // put your setup code here, to run once: Serial.begin(115200); @@ -68,7 +73,6 @@ void setup() { // wm.erase(); wm.setClass("invert"); - wm.setAPCallback(configModeCallback); //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep @@ -77,16 +81,6 @@ void setup() { // wm.setConnectTimeout(5); // wm.setShowStaticFields(true); - // uint8_t menu[] = {wm.MENU_WIFI,wm.MENU_INFO,wm.MENU_PARAM,wm.MENU_CLOSE}; - // wm.setMenu(menu); - - // std::vector menu = {wm.MENU_WIFI,wm.MENU_INFO,wm.MENU_PARAM,wm.MENU_CLOSE,wm.MENU_SEP,wm.MENU_ERASE,wm.MENU_EXIT}; - // wm.setMenu(menu); - -// std::vector menu = {wm.MENU_WIFI,wm.MENU_INFO,wm.MENU_PARAM,wm.MENU_CLOSE,wm.MENU_SEP,wm.MENU_ERASE,wm.MENU_EXIT}; - // wm.setMenu(menu); - - WiFiManagerParameter custom_html("

This Is Custom HTML

"); WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); @@ -95,7 +89,9 @@ void setup() { WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // callbacks - wm.setSaveConfigCallback(saveCallback); + wm.setAPCallback(configModeCallback); + wm.setSaveConfigCallback(saveWifiCallback); + wm.setSaveParamsCallback(saveParamCallback); //add all your parameters here wm.addParameter(&custom_html); @@ -108,21 +104,11 @@ void setup() { custom_html.setValue("test",4); custom_token.setValue("test",4); - // MENU_WIFI = 0, - // MENU_WIFINOSCAN = 1, - // MENU_INFO = 2, - // MENU_PARAM = 3, - // MENU_CLOSE = 4, - // MENU_RESTART = 5, - // MENU_EXIT = 6, - // MENU_ERASE = 7, - // MENU_SEP = 8 - // const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; // wm.setMenu(menu,9); std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - wm.setMenu(menu); + // wm.setMenu(menu); // set static sta ip // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); @@ -152,10 +138,10 @@ void setup() { if(!wm.autoConnect("AutoConnectAP")) { Serial.println("failed to connect and hit timeout"); } - else { + else if(TEST_CP) { // start configportal always - // wm.setConfigPortalTimeout(60); - // wm.startConfigPortal(); + wm.setConfigPortalTimeout(60); + wm.startConfigPortal(); } pinMode(TRIGGER_PIN, INPUT); From 1d0970a882b84d8840eb597785aae52e5c688605 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 12 Oct 2018 14:10:16 -0500 Subject: [PATCH 133/146] moving apcallback after sosftap() apcallback used to only indicate that mode was softap, moved untikl after actually starting the ap, so it can be used to check status and get ip etc. --- WiFiManager.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 235b9b9..818e20e 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -326,11 +326,6 @@ bool WiFiManager::startAP(){ bool ret = true; DEBUG_WM(F("StartAP with SSID: "),_apName); - // do AP callback if set - if ( _apcallback != NULL) { - _apcallback(this); - } - #ifdef ESP8266 // @bug workaround for bug #4372 https://github.com/esp8266/Arduino/issues/4372 if(!WiFi.enableAP(true)) { @@ -375,6 +370,11 @@ bool WiFiManager::startAP(){ if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] There was a problem starting the AP"); // @todo add softAP retry here + + // do AP callback if set + if ( _apcallback != NULL) { + _apcallback(this); + } delay(500); // slight delay to make sure we get an AP IP DEBUG_WM(F("AP IP address:"),WiFi.softAPIP()); From 080f7751e021d2828b401ef59a06c2c6330207dd Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 12 Oct 2018 14:52:10 -0500 Subject: [PATCH 134/146] moving apcallback after everything --- WiFiManager.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 818e20e..e9f71bd 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -370,11 +370,6 @@ bool WiFiManager::startAP(){ if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] There was a problem starting the AP"); // @todo add softAP retry here - - // do AP callback if set - if ( _apcallback != NULL) { - _apcallback(this); - } delay(500); // slight delay to make sure we get an AP IP DEBUG_WM(F("AP IP address:"),WiFi.softAPIP()); @@ -389,6 +384,10 @@ bool WiFiManager::startAP(){ } #endif + // do AP callback if set + if ( _apcallback != NULL) { + _apcallback(this); + } return ret; } From 3c280b12a84bd5eb68de1f39133512170c2dda3a Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 12 Oct 2018 15:16:59 -0500 Subject: [PATCH 135/146] moved apcallback after webserver is available --- WiFiManager.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index e9f71bd..5a79cbe 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -343,10 +343,9 @@ bool WiFiManager::startAP(){ } } - if(_channelSync){ DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",WiFi.channel()); - } + } // start soft AP with password or anonymous if (_apPassword != "") { @@ -384,10 +383,6 @@ bool WiFiManager::startAP(){ } #endif - // do AP callback if set - if ( _apcallback != NULL) { - _apcallback(this); - } return ret; } @@ -530,6 +525,11 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo DEBUG_WM(DEBUG_DEV,F("setupConfigPortal")); setupConfigPortal(); + // do AP callback if set + if ( _apcallback != NULL) { + _apcallback(this); + } + if(!_configPortalIsBlocking){ DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, non blocking/processing")); return result; From c3fd7d962236e664b2e4e9fe852d492378d2eaa6 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 12 Oct 2018 15:57:35 -0500 Subject: [PATCH 136/146] #461 testing adds new callback and moved webserver to public --- WiFiManager.cpp | 27 +++++++++++++++---- WiFiManager.h | 7 +++-- .../OnDemandConfigPortal.ino | 12 ++++++++- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 5a79cbe..2299fa2 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -453,6 +453,12 @@ void WiFiManager::setupConfigPortal() { 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)); @@ -521,15 +527,15 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo startAP(); WiFiSetCountry(); - // init configportal - DEBUG_WM(DEBUG_DEV,F("setupConfigPortal")); - setupConfigPortal(); - // 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; @@ -2012,6 +2018,17 @@ void WiFiManager::setAPCallback( std::function func ) { _apcallback = func; } +/** + * setWebServerCallback, set a callback after webserver is reset, and before routes are setup + * if we set webserver handlers before wm, they are used and wm is not by esp webserver + * on events cannot be overrided once set, and are not mutiples + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setWebServerCallback( std::function func ) { + _webservercallback = func; +} + /** * setSaveConfigCallback, set a save config callback after closing configportal * @note calls only if wifi is saved or changed, or setBreakAfterConfig(true) diff --git a/WiFiManager.h b/WiFiManager.h index 1774d24..c44057d 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -184,8 +184,10 @@ class WiFiManager // SET CALLBACKS - //called when AP mode and config portal is started + //called after AP mode and config portal has started void setAPCallback( std::function func ); + //called after webserver has started + void setWebServerCallback( std::function func ); //called when settings reset have been triggered void setConfigResetCallback( std::function func ); //called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) @@ -273,7 +275,6 @@ class WiFiManager // set body class (invert) void setClass(String str); - private: std::unique_ptr dnsServer; #if defined(ESP32) && defined(WM_WEBSERVERSHIM) @@ -284,6 +285,7 @@ class WiFiManager std::unique_ptr server; + private: std::vector _menuIds; std::vector _menuIdsDefault = {"wifi","info","exit"}; @@ -484,6 +486,7 @@ class WiFiManager // callbacks // @todo use cb list (vector) maybe event ids, allow no return value std::function _apcallback; + std::function _webservercallback; std::function _savewificallback; std::function _presavecallback; std::function _saveparamscallback; diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index 3ded79b..8ceebd8 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -39,7 +39,6 @@ void saveWifiCallback(){ Serial.println("[CALLBACK] saveCallback fired"); } - //gets called when WiFiManager enters configuration mode void configModeCallback (WiFiManager *myWiFiManager) { Serial.println("[CALLBACK] configModeCallback fired"); @@ -53,6 +52,16 @@ void saveParamCallback(){ Serial.println("[CALLBACK] saveParamCallback fired"); } +void bindServerCallback(){ + wm.server->on("/custom",handleRoute); + // wm.server->on("/info",handleRoute); // can override wm! +} + +void handleRoute(){ + Serial.println("[HTTP] handle route"); + wm.server->send(200, "text/plain", "hello from user code"); +} + void setup() { // put your setup code here, to run once: Serial.begin(115200); @@ -90,6 +99,7 @@ void setup() { // callbacks wm.setAPCallback(configModeCallback); + wm.setWebServerCallback(bindServerCallback); wm.setSaveConfigCallback(saveWifiCallback); wm.setSaveParamsCallback(saveParamCallback); From 256c889715614f44050568f8546764e3d7e4ece4 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 12 Oct 2018 16:08:31 -0500 Subject: [PATCH 137/146] comments --- WiFiManager.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 2299fa2..caa430e 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -343,6 +343,8 @@ bool WiFiManager::startAP(){ } } + //@todo add callback here if needed to modify ap but cannot use setAPStaticIPConfig + if(_channelSync){ DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",WiFi.channel()); } From 2d021bbab82308ab7dd1e776e4a533578daf7956 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Sat, 13 Oct 2018 15:57:00 -0500 Subject: [PATCH 138/146] adds nonblocking params example --- .../AutoConnectNonBlockingwParams.ino | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino diff --git a/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino b/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino new file mode 100644 index 0000000..f5d4881 --- /dev/null +++ b/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino @@ -0,0 +1,35 @@ +#include // https://github.com/tzapu/WiFiManager +WiFiManager wm; +WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + wm.addParameter(&custom_mqtt_server); + wm.setConfigPortalBlocking(false); + wm.setSaveParamsCallback(saveParamsCallback); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + if(wm.autoConnect("AutoConnectAP")){ + Serial.println("connected...yeey :)"); + } + else { + Serial.println("Configportal running"); + } +} + +void loop() { + wm.process(); + // put your main code here, to run repeatedly: +} + +void saveParamsCallback () { + Serial.println("Get Params:"); + Serial.print(custom_mqtt_server.getID()); + Serial.print(" : "); + Serial.println(custom_mqtt_server.getValue()); +} From 55577692fee14312c318d105cd15be4e84d86f58 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Thu, 18 Oct 2018 16:47:52 -0500 Subject: [PATCH 139/146] add ntp time to dev example --- WiFiManager.h | 2 +- examples/Advanced/Advanced.ino | 4 +- .../OnDemandConfigPortal.ino | 113 ++++++++++-------- 3 files changed, 66 insertions(+), 53 deletions(-) diff --git a/WiFiManager.h b/WiFiManager.h index c44057d..7f77483 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -31,7 +31,7 @@ // #include "soc/efuse_reg.h" // include to add efuse chip rev to info, getChipRevision() is almost always the same though, so not sure why it matters. -// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge, deprecated +// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge, @DEPRECATED // autoreconnect is WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 #define WM_WEBSERVERSHIM // use webserver shim lib diff --git a/examples/Advanced/Advanced.ino b/examples/Advanced/Advanced.ino index 700ab6c..21a4bd9 100644 --- a/examples/Advanced/Advanced.ino +++ b/examples/Advanced/Advanced.ino @@ -69,11 +69,11 @@ void setup() { void checkButton(){ // check for button press if ( digitalRead(TRIGGER_PIN) == LOW ) { - // poor mans debounce/press-hold, not recommended for production code + // poor mans debounce/press-hold, code not ideal for production delay(50); if( digitalRead(TRIGGER_PIN) == LOW ){ - // holding button 3000 ms, reset settings + // still holding button for 3000 ms, reset settings, code not ideaa for production delay(3000); // reset delay hold if( digitalRead(TRIGGER_PIN) == LOW ){ Serial.println("Erasing Config"); diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index 8ceebd8..308eb1a 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -2,39 +2,17 @@ * This is a kind of unit test for DEV for now */ #include // https://github.com/tzapu/WiFiManager +#include #define TRIGGER_PIN 0 const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; WiFiManager wm; -bool TEST_CP = true; // always start the configportal - +bool TEST_CP = false; // always start the configportal +bool TEST_NET = true; // do a network test, get ntp time char ssid[] = "*************"; // your network SSID (name) char pass[] = "********"; // your network password -void debugchipid(){ - // WiFi.mode(WIFI_STA); - // WiFi.printDiag(Serial); - // Serial.println(modes[WiFi.getMode()]); - - // ESP.eraseConfig(); - // wm.resetSettings(); - // wm.erase(true); - WiFi.mode(WIFI_AP); - // WiFi.softAP(); - WiFi.enableAP(true); - delay(500); - // esp_wifi_start(); - delay(1000); - WiFi.printDiag(Serial); - delay(60000); - ESP.restart(); - - // AP esp_267751 - // 507726A4AE30 - // ESP32 Chip ID = 507726A4AE30 -} - void saveWifiCallback(){ Serial.println("[CALLBACK] saveCallback fired"); } @@ -68,12 +46,8 @@ void setup() { Serial.setDebugOutput(true); // delay(3000); Serial.println("\n Starting"); - // WiFi.setSleepMode(WIFI_NONE_SLEEP); + // WiFi.setSleepMode(WIFI_NONE_SLEEP); // disable sleep, can improve ap stability - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - // WiFiManager wm; - wm.debugPlatformInfo(); //Local intialization. Once its business is done, there is no need to keep it around @@ -90,12 +64,12 @@ void setup() { // wm.setConnectTimeout(5); // wm.setShowStaticFields(true); - WiFiManagerParameter custom_html("

This Is Custom HTML

"); + WiFiManagerParameter custom_html("

This Is Custom HTML

"); // only custom html WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); WiFiManagerParameter custom_token("api_token", "api token", "", 16); WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces - WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); + WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // custom input attrs (ip mask) // callbacks wm.setAPCallback(configModeCallback); @@ -114,11 +88,12 @@ void setup() { custom_html.setValue("test",4); custom_token.setValue("test",4); + // Set cutom menu via menu[] or vector // const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - // wm.setMenu(menu,9); + // wm.setMenu(menu,9); // custom menu array must provide length std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - // wm.setMenu(menu); + // wm.setMenu(menu); // custom menu, pass vector // set static sta ip // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); @@ -153,7 +128,10 @@ void setup() { wm.setConfigPortalTimeout(60); wm.startConfigPortal(); } - + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } pinMode(TRIGGER_PIN, INPUT); } @@ -161,22 +139,8 @@ void loop() { // is configuration portal requested? if ( digitalRead(TRIGGER_PIN) == LOW ) { Serial.println("BUTTON PRESSED"); - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - //reset settings - for testing - //wm.resetSettings(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep, in seconds wm.setConfigPortalTimeout(120); - //it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - - //WITHOUT THIS THE AP DOES NOT SEEM TO WORK PROPERLY WITH SDK 1.5 , update to at least 1.5.1 - //WiFi.mode(WIFI_STA); - // disable captive portal redirection // wm.setCaptivePortalEnable(false); @@ -186,9 +150,58 @@ void loop() { } else { //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); - } + getTime(); + } } + if(WiFi.status() == WL_CONNECTED) getTime(); // put your main code here, to run repeatedly: delay(5000); } + +void getTime() { + int tz = -5; + int dst = 0; + time_t now = time(nullptr); + unsigned timeout = 5000; + unsigned start = millis(); + configTime(tz * 3600, dst * 3600, "pool.ntp.org", "time.nist.gov"); + Serial.print("Waiting for NTP time sync: "); + while (now < 8 * 3600 * 2 ) { + delay(100); + Serial.print("."); + now = time(nullptr); + if((millis() - start) > timeout){ + Serial.println("[ERROR] Failed to get NTP time."); + return; + } + } + Serial.println(""); + struct tm timeinfo; + gmtime_r(&now, &timeinfo); + Serial.print("Current time: "); + Serial.print(asctime(&timeinfo)); +} + +void debugchipid(){ + // WiFi.mode(WIFI_STA); + // WiFi.printDiag(Serial); + // Serial.println(modes[WiFi.getMode()]); + + // ESP.eraseConfig(); + // wm.resetSettings(); + // wm.erase(true); + WiFi.mode(WIFI_AP); + // WiFi.softAP(); + WiFi.enableAP(true); + delay(500); + // esp_wifi_start(); + delay(1000); + WiFi.printDiag(Serial); + delay(60000); + ESP.restart(); + + // AP esp_267751 + // 507726A4AE30 + // ESP32 Chip ID = 507726A4AE30 +} \ No newline at end of file From 7f0bd1e41f7478bfb8830551a22f3ac2690925e7 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 31 Oct 2018 13:47:05 -0500 Subject: [PATCH 140/146] changed placeholder to label deprecated getPlaceholder with getLabel --- WiFiManager.cpp | 27 +++++++++++++++------------ WiFiManager.h | 17 +++++++++-------- 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index caa430e..ae8829d 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -24,32 +24,32 @@ uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS; WiFiManagerParameter::WiFiManagerParameter(const char *custom) { _id = NULL; - _placeholder = NULL; + _label = NULL; _length = 1; _value = NULL; _labelPlacement = WFM_LABEL_BEFORE; _customHTML = custom; } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder) { - init(id, placeholder, "", 0, "", WFM_LABEL_BEFORE); +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label) { + init(id, label, "", 0, "", WFM_LABEL_BEFORE); } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length) { - init(id, placeholder, defaultValue, length, "", 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 *placeholder, const char *defaultValue, int length, const char *custom) { - init(id, placeholder, defaultValue, length, custom, 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 *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) { - init(id, placeholder, defaultValue, length, custom, labelPlacement); +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 *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) { +void WiFiManagerParameter::init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { _id = id; - _placeholder = placeholder; + _label = label; _labelPlacement = labelPlacement; _customHTML = custom; setValue(defaultValue,length); @@ -89,7 +89,10 @@ const char* WiFiManagerParameter::getID() { return _id; } const char* WiFiManagerParameter::getPlaceholder() { - return _placeholder; + return _label; +} +const char* WiFiManagerParameter::getLabel() { + return _label; } int WiFiManagerParameter::getValueLength() { return _length; diff --git a/WiFiManager.h b/WiFiManager.h index 7f77483..44ad3bb 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -105,27 +105,28 @@ class WiFiManagerParameter { @id is used for HTTP queries and must not contain spaces nor other special characters */ WiFiManagerParameter(const char *custom); - WiFiManagerParameter(const char *id, const char *placeholder); - WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length); - WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom); - WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement); + WiFiManagerParameter(const char *id, const char *label); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); ~WiFiManagerParameter(); const char *getID(); const char *getValue(); - const char *getPlaceholder(); + const char *getLabel(); + const char *getPlaceholder(); // @deprecated, use getLabel int getValueLength(); int getLabelPlacement(); const char *getCustomHTML(); void setValue(const char *defaultValue, int length); protected: - void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom); - void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement); + void init(const char *id, const char *label, const char *defaultValue, int length, const char *custom); + void init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); private: const char *_id; - const char *_placeholder; + const char *_label; char *_value; int _length; int _labelPlacement; From 2209f987b7429b58e32bd8717b94c5d44ebc7bfb Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 31 Oct 2018 14:02:16 -0500 Subject: [PATCH 141/146] removed placeholder and added temlplace comments --- WiFiManager.cpp | 24 +++++++++++++----------- strings_en.h | 2 +- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index ae8829d..2505edd 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1221,7 +1221,7 @@ String WiFiManager::getParamOut(){ bool tok_v = HTTP_PARAM_temp.indexOf(FPSTR(T_v)) > 0; bool tok_c = HTTP_PARAM_temp.indexOf(FPSTR(T_c)) > 0; - char parLength[5]; + char valLength[5]; // add the extra parameters to the form for (int i = 0; i < _paramsCount; i++) { if (_params[i] == NULL || _params[i]->_length == 0) { @@ -1229,7 +1229,7 @@ String WiFiManager::getParamOut(){ break; } - // label before or after, this could probably be done via floats however + // label before or after, @todo this could be done via floats or CSS and eliminated String pitem; switch (_params[i]->getLabelPlacement()) { case WFM_LABEL_BEFORE: @@ -1246,17 +1246,19 @@ String WiFiManager::getParamOut(){ break; } + // Input templating + // "
"; // if no ID use customhtml for item, else generate from param string if (_params[i]->getID() != NULL) { - if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); - if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); - if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); - if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); - if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getPlaceholder()); - snprintf(parLength, 5, "%d", _params[i]->getValueLength()); - if(tok_l)pitem.replace(FPSTR(T_l), parLength); - if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); - if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // meant for additional attributes, not html + if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); // T_I id number + if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); // T_i id name + if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); // T_n id name alias + if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); // T_p replace legacy placeholder token + if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getLabel()); // T_t title/label + snprintf(valLength, 5, "%d", _params[i]->getValueLength()); + if(tok_l)pitem.replace(FPSTR(T_l), valLength); // T_l value length + if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); // T_v value + if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // T_c meant for additional attributes, not html, but can stuff } else { pitem = _params[i]->getCustomHTML(); } diff --git a/strings_en.h b/strings_en.h index db8e6bc..265ec5d 100644 --- a/strings_en.h +++ b/strings_en.h @@ -44,7 +44,7 @@ const char HTTP_FORM_STATIC_HEAD[] PROGMEM = "

"; const char HTTP_FORM_END[] PROGMEM = "

"; const char HTTP_FORM_LABEL[] PROGMEM = ""; const char HTTP_FORM_PARAM_HEAD[] PROGMEM = "

"; -const char HTTP_FORM_PARAM[] PROGMEM = "
"; +const char HTTP_FORM_PARAM[] PROGMEM = "
"; const char HTTP_SCAN_LINK[] PROGMEM = "
"; const char HTTP_SAVED[] PROGMEM = "
Saving Credentials
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; From 370be061e4d22226e3d2c183c0fc689ea6a594f7 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 31 Oct 2018 14:03:26 -0500 Subject: [PATCH 142/146] adds custom param examples to advanced --- examples/Advanced/Advanced.ino | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/examples/Advanced/Advanced.ino b/examples/Advanced/Advanced.ino index 21a4bd9..6878172 100644 --- a/examples/Advanced/Advanced.ino +++ b/examples/Advanced/Advanced.ino @@ -6,7 +6,8 @@ #define TRIGGER_PIN 0 -WiFiManager wm; +WiFiManager wm; // global wm instance +WiFiManagerParameter custom_field(""); // global param ( for non blocking w params ) void setup() { Serial.begin(115200); @@ -15,13 +16,14 @@ void setup() { Serial.println("\n Starting"); pinMode(TRIGGER_PIN, INPUT); - + // wm.resetSettings(); // wipe settings // add a custom input field int customFieldLength = 40; - WiFiManagerParameter custom_field("customfield", "Custom Field", "Default Value", customFieldLength); + new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\""); // reconstruct (hmm) wm.addParameter(&custom_field); + wm.setSaveParamsCallback(saveParamCallback); // custom menu via array or vector // @@ -33,15 +35,16 @@ void setup() { // set dark theme // wm.setClass("invert"); - + + //set static ip // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn // wm.setShowStaticFields(true); // force show static ip fields // wm.setShowDnsFields(true); // force show dns field always // wm.setConnectTimeout(20); // how long to try to connect for before continuing - // wm.setConfigPortalTimeout(60); // auto close configportal after n seconds - // wifiManager.setCaptivePortalEnable(false); // disable captive portal redirection + wm.setConfigPortalTimeout(30); // auto close configportal after n seconds + // wm.setCaptivePortalEnable(false); // disable captive portal redirection // wifi scan settings // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) @@ -72,11 +75,12 @@ void checkButton(){ // poor mans debounce/press-hold, code not ideal for production delay(50); if( digitalRead(TRIGGER_PIN) == LOW ){ - + Serial.println("Button Pressed"); // still holding button for 3000 ms, reset settings, code not ideaa for production delay(3000); // reset delay hold if( digitalRead(TRIGGER_PIN) == LOW ){ - Serial.println("Erasing Config"); + Serial.println("Button Held"); + Serial.println("Erasing Config, restarting"); wm.resetSettings(); ESP.restart(); } @@ -85,7 +89,7 @@ void checkButton(){ Serial.println("Starting config portal"); wm.setConfigPortalTimeout(120); - if (!wm.startConfigPortal("OnDemandAP")) { + if (!wm.startConfigPortal("OnDemandAP","password")) { Serial.println("failed to connect or hit timeout"); delay(3000); // ESP.restart(); @@ -97,6 +101,10 @@ void checkButton(){ } } +void saveParamCallback(){ + Serial.println("[CALLBACK] saveParamCallback fired"); +} + void loop() { checkButton(); // put your main code here, to run repeatedly: From 38b6c878a209f4f83d32da6f112d0e70efe10dc5 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 31 Oct 2018 14:15:02 -0500 Subject: [PATCH 143/146] chaange setCaptivePortalClientCheck to setAPClientCheck --- WiFiManager.cpp | 6 +++--- WiFiManager.h | 6 +++--- examples/Advanced/Advanced.ino | 1 + 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 2505edd..e91719b 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -416,7 +416,7 @@ void WiFiManager::stopWebPortal() { boolean WiFiManager::configPortalHasTimeout(){ - if(_configPortalTimeout == 0 || (_cpClientCheck && (WiFi_softap_num_stations() > 0))){ + 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()); @@ -2175,8 +2175,8 @@ void WiFiManager::setWiFiAutoReconnect(boolean enabled){ * @access public * @param boolean enabled [false] */ -void WiFiManager::setCaptivePortalClientCheck(boolean enabled){ - _cpClientCheck = enabled; +void WiFiManager::setAPClientCheck(boolean enabled){ + _apClientCheck = enabled; } /** diff --git a/WiFiManager.h b/WiFiManager.h index 44ad3bb..a8c7d1f 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -237,8 +237,8 @@ class WiFiManager void setShowDnsFields(boolean alwaysShow); //if false, disable captive portal redirection void setCaptivePortalEnable(boolean enabled); - //if false, timeout captive portal even if a STA client connected (false), suggest disabling if captiveportal is open - void setCaptivePortalClientCheck(boolean enabled); + //if false, timeout captive portal even if a STA client connected to softAP (false), suggest disabling if captiveportal is open + void setAPClientCheck(boolean enabled); //if true, reset timeout when webclient connects (true), suggest disabling if captiveportal is open void setWebPortalClientCheck(boolean enabled); // if true, enable autoreconnecting @@ -344,7 +344,7 @@ class WiFiManager boolean _enableCaptivePortal = true; // enable captive portal redirection boolean _userpersistent = true; // users preffered persistence to restore boolean _wifiAutoReconnect = true; // there is no platform getter for this, we must assume its true and make it so - boolean _cpClientCheck = false; // keep cp alive if cp have station + boolean _apClientCheck = false; // keep cp alive if ap have station boolean _webClientCheck = true; // keep cp alive if web have client boolean _scanDispOptions = false; // show percentage in scans not icons boolean _paramsInWifi = true; // show custom parameters on wifi page diff --git a/examples/Advanced/Advanced.ino b/examples/Advanced/Advanced.ino index 6878172..9cd1211 100644 --- a/examples/Advanced/Advanced.ino +++ b/examples/Advanced/Advanced.ino @@ -45,6 +45,7 @@ void setup() { // wm.setConnectTimeout(20); // how long to try to connect for before continuing wm.setConfigPortalTimeout(30); // auto close configportal after n seconds // wm.setCaptivePortalEnable(false); // disable captive portal redirection + // wm.setAPClientCheck(true); // avoid timeout if client connected to softap // wifi scan settings // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) From 73f2a8c366092fff2851017f27089e7ea9a2a2b1 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Wed, 31 Oct 2018 14:23:39 -0500 Subject: [PATCH 144/146] adds empty param constructor --- WiFiManager.cpp | 4 ++++ WiFiManager.h | 1 + examples/Advanced/Advanced.ino | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index e91719b..2d54415 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -22,6 +22,10 @@ uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS; * -------------------------------------------------------------------------------- **/ +WiFiManagerParameter::WiFiManagerParameter() { + WiFiManagerParameter(""); +} + WiFiManagerParameter::WiFiManagerParameter(const char *custom) { _id = NULL; _label = NULL; diff --git a/WiFiManager.h b/WiFiManager.h index a8c7d1f..6e03ffe 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -104,6 +104,7 @@ class WiFiManagerParameter { Create custom parameters that can be added to the WiFiManager setup web page @id is used for HTTP queries and must not contain spaces nor other special characters */ + WiFiManagerParameter(); WiFiManagerParameter(const char *custom); WiFiManagerParameter(const char *id, const char *label); WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length); diff --git a/examples/Advanced/Advanced.ino b/examples/Advanced/Advanced.ino index 9cd1211..4ec9d60 100644 --- a/examples/Advanced/Advanced.ino +++ b/examples/Advanced/Advanced.ino @@ -7,7 +7,7 @@ #define TRIGGER_PIN 0 WiFiManager wm; // global wm instance -WiFiManagerParameter custom_field(""); // global param ( for non blocking w params ) +WiFiManagerParameter custom_field; // global param ( for non blocking w params ) void setup() { Serial.begin(115200); From 501c824993f136d0a63ed3a4ed00e2c81abf5a95 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Fri, 2 Nov 2018 10:13:07 -0500 Subject: [PATCH 145/146] supports stopConfigPortal if blocking , flag abort --- WiFiManager.cpp | 26 ++++++++++++++----- WiFiManager.h | 5 ++-- .../OnDemandConfigPortal.ino | 3 ++- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index caa430e..25e3dc6 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -408,7 +408,7 @@ void WiFiManager::stopWebPortal() { if(!configPortalActive && !webPortalActive) return; DEBUG_WM(DEBUG_VERBOSE,F("Stopping Web Portal")); webPortalActive = false; - stopConfigPortal(); + shutdownConfigPortal(); } boolean WiFiManager::configPortalHasTimeout(){ @@ -550,7 +550,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo // if timed out or abort, break if(configPortalHasTimeout() || abort){ DEBUG_WM(DEBUG_DEV,F("configportal abort")); - stopConfigPortal(); + shutdownConfigPortal(); result = abort ? portalAbortResult : portalTimeoutResult; // false, false break; } @@ -611,7 +611,7 @@ uint8_t WiFiManager::processConfigPortal(){ if ( _savewificallback != NULL) { _savewificallback(); } - stopConfigPortal(); + shutdownConfigPortal(); return WL_CONNECTED; // CONNECT SUCCESS } DEBUG_WM(DEBUG_ERROR,F("[ERROR] Connect to new AP Failed")); @@ -624,7 +624,7 @@ uint8_t WiFiManager::processConfigPortal(){ if ( _savewificallback != NULL) { _savewificallback(); } - stopConfigPortal(); + shutdownConfigPortal(); return WL_CONNECT_FAILED; // CONNECT FAIL } else{ @@ -642,11 +642,11 @@ uint8_t WiFiManager::processConfigPortal(){ } /** - * [stopConfigPortal description] + * [shutdownConfigPortal description] * @access public - * @return {[type]} [description] + * @return bool success (softapdisconnect) */ -boolean WiFiManager::stopConfigPortal(){ +bool WiFiManager::shutdownConfigPortal(){ if(webPortalActive) return false; //DNS handler @@ -1831,6 +1831,18 @@ void WiFiManager::reportStatus(String &page){ * reset wifi settings, clean stored ap password */ +/** + * [stopConfigPortal description] + * @return {[type]} [description] + */ +bool WiFiManager::stopConfigPortal(){ + if(_configPortalIsBlocking){ + abort = true; + return true; + } + return shutdownConfigPortal(); +} + /** * disconnect * @access public diff --git a/WiFiManager.h b/WiFiManager.h index 7f77483..f7a7b48 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -151,8 +151,8 @@ class WiFiManager boolean startConfigPortal(); // auto generates apname boolean startConfigPortal(char const *apName, char const *apPassword = NULL); - //manually stop the config portal if started manually - boolean stopConfigPortal(); + //manually stop the config portal if started manually, stop immediatly if non blocking, flag abort if blocking + bool stopConfigPortal(); //manually start the web portal, autoconnect does this automatically on connect failure void startWebPortal(); @@ -367,6 +367,7 @@ class WiFiManager void _end(); void setupConfigPortal(); + bool shutdownConfigPortal(); #ifdef NO_EXTRA_4K_HEAP boolean _tryWPS = false; // try WPS on save failure, unsupported diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index 308eb1a..4e14584 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -28,6 +28,7 @@ void configModeCallback (WiFiManager *myWiFiManager) { void saveParamCallback(){ Serial.println("[CALLBACK] saveParamCallback fired"); + // wm.stopConfigPortal(); } void bindServerCallback(){ @@ -93,7 +94,7 @@ void setup() { // wm.setMenu(menu,9); // custom menu array must provide length std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - // wm.setMenu(menu); // custom menu, pass vector + wm.setMenu(menu); // custom menu, pass vector // set static sta ip // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); From ccfca4b663696baddc708e515571f8d1030df561 Mon Sep 17 00:00:00 2001 From: tablatronix Date: Tue, 6 Nov 2018 12:04:18 -0600 Subject: [PATCH 146/146] adds customhtml input example --- examples/Advanced/Advanced.ino | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/examples/Advanced/Advanced.ino b/examples/Advanced/Advanced.ino index 4ec9d60..267bcbb 100644 --- a/examples/Advanced/Advanced.ino +++ b/examples/Advanced/Advanced.ino @@ -21,7 +21,17 @@ void setup() { // add a custom input field int customFieldLength = 40; - new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\""); // reconstruct (hmm) + + + // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\""); + + // test custom html input type(checkbox) + // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\" type=\"checkbox\""); // custom html type + + // test custom html(radio) + const char* custom_radio_str = "
One
Two
Three"; + new (&custom_field) WiFiManagerParameter(custom_radio_str); // custom html input + wm.addParameter(&custom_field); wm.setSaveParamsCallback(saveParamCallback); @@ -34,7 +44,7 @@ void setup() { wm.setMenu(menu); // set dark theme - // wm.setClass("invert"); + wm.setClass("invert"); //set static ip @@ -102,8 +112,19 @@ void checkButton(){ } } + +String getParam(String name){ + //read parameter from server, for customhmtl input + String value; + if(wm.server->hasArg(name)) { + value = wm.server->arg(name); + } + return value; +} + void saveParamCallback(){ Serial.println("[CALLBACK] saveParamCallback fired"); + Serial.println("PARAM customfieldid = " + getParam("customfieldid")); } void loop() {