diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 7e89b55..bb5af87 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -216,7 +216,7 @@ WiFiManager::~WiFiManager() { void WiFiManager::_begin(){ if(_hasBegun) return; _hasBegun = true; - _usermode = WiFi.getMode(); + // _usermode = WiFi.getMode(); #ifndef ESP32 WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites @@ -245,97 +245,113 @@ boolean WiFiManager::autoConnect() { */ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { DEBUG_WM(F("AutoConnect")); - _begin(); + if(getWiFiIsSaved()){ - // attempt to connect using saved settings, on fail fallback to AP config portal - if(!WiFi.enableSTA(true)){ - // handle failure mode Brownout detector etc. - DEBUG_WM(DEBUG_ERROR,"[FATAL] Unable to enable wifi!"); - return false; - } - - WiFiSetCountry(); + _begin(); - #ifdef ESP32 - if(esp32persistent) WiFi.persistent(false); // disable persistent for esp32 after esp_wifi_start or else saves wont work - #endif + // attempt to connect using saved settings, on fail fallback to AP config portal + if(!WiFi.enableSTA(true)){ + // handle failure mode Brownout detector etc. + DEBUG_WM(DEBUG_ERROR,"[FATAL] Unable to enable wifi!"); + return false; + } + + WiFiSetCountry(); - _usermode = WIFI_STA; - - // no getter for autoreconnectpolicy before this - // https://github.com/esp8266/Arduino/pull/4359 - // so we must force it on else, if not connectimeout then waitforconnectionresult gets stuck endless loop - WiFi_autoReconnect(); - - // set hostname before stating - if((String)_hostname != ""){ - DEBUG_WM(DEBUG_VERBOSE,"Setting hostname:",_hostname); - bool res = true; - #ifdef ESP8266 - res = WiFi.hostname(_hostname); - #ifdef ESP8266MDNS_H - DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname"); - if(MDNS.begin(_hostname)){ - MDNS.addService("http", "tcp", 80); - } - #endif - #elif defined(ESP32) - // @note hostname must be set after STA_START - delay(200); // do not remove, give time for STA_START - res = WiFi.setHostname(_hostname); - #ifdef ESP32MDNS_H - DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname"); - if(MDNS.begin(_hostname)){ - MDNS.addService("http", "tcp", 80); - } - #endif + #ifdef ESP32 + if(esp32persistent) WiFi.persistent(false); // disable persistent for esp32 after esp_wifi_start or else saves wont work #endif - - if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: set failed!")); - - if(WiFi.status() == WL_CONNECTED){ - DEBUG_WM(DEBUG_VERBOSE,F("reconnecting to set new hostname")); - // WiFi.reconnect(); // This does not reset dhcp - WiFi_Disconnect(); - delay(200); // do not remove, need a delay for disconnect to change status() - } - } - // if already connected, or try stored connect - // @note @todo ESP32 has no autoconnect, so connectwifi will always be called unless user called begin etc before - // @todo check if correct ssid == saved ssid when already connected - bool connected = false; - if (WiFi.status() == WL_CONNECTED){ - connected = true; - DEBUG_WM(F("AutoConnect: ESP Already Connected")); - setSTAConfig(); - } + _usermode = WIFI_STA; // When using autoconnect , assume the user wants sta mode on permanently. - if(connected || connectWifi("", "") == WL_CONNECTED){ - //connected - DEBUG_WM(F("AutoConnect: SUCCESS")); - DEBUG_WM(F("STA IP Address:"),WiFi.localIP()); - _lastconxresult = WL_CONNECTED; + // no getter for autoreconnectpolicy before this + // https://github.com/esp8266/Arduino/pull/4359 + // so we must force it on else, if not connectimeout then waitforconnectionresult gets stuck endless loop + WiFi_autoReconnect(); + // set hostname before stating if((String)_hostname != ""){ - #ifdef ESP8266 - DEBUG_WM(DEBUG_DEV,"hostname: STA",WiFi.hostname()); - #elif defined(ESP32) - DEBUG_WM(DEBUG_DEV,"hostname: STA",WiFi.getHostname()); - #endif + setupHostname(true); } - return true; - } - // possibly skip the config portal - if (!_enableConfigPortal) { - return false; - } + // if already connected, or try stored connect + // @note @todo ESP32 has no autoconnect, so connectwifi will always be called unless user called begin etc before + // @todo check if correct ssid == saved ssid when already connected + bool connected = false; + if (WiFi.status() == WL_CONNECTED){ + connected = true; + DEBUG_WM(F("AutoConnect: ESP Already Connected")); + setSTAConfig(); + } - DEBUG_WM(F("AutoConnect: FAILED")); + if(connected || connectWifi("", "") == WL_CONNECTED){ + //connected + DEBUG_WM(F("AutoConnect: SUCCESS")); + DEBUG_WM(F("STA IP Address:"),WiFi.localIP()); + _lastconxresult = WL_CONNECTED; + + if((String)_hostname != ""){ + #ifdef ESP8266 + DEBUG_WM(DEBUG_DEV,"hostname: STA",WiFi.hostname()); + #elif defined(ESP32) + DEBUG_WM(DEBUG_DEV,"hostname: STA",WiFi.getHostname()); + #endif + } + return true; + } + + // possibly skip the config portal + if (!_enableConfigPortal) { + return false; + } + + DEBUG_WM(F("AutoConnect: FAILED")); + } + else DEBUG_WM(F("No Credentials are Saved, skipping connect")); // not connected start configportal - return startConfigPortal(apName, apPassword); + bool res = startConfigPortal(apName, apPassword); + return res; +} + +bool WiFiManager::setupHostname(bool restart){ + DEBUG_WM(DEBUG_VERBOSE,"Setting hostname:",_hostname); + if((String)_hostname == "") { + DEBUG_WM(DEBUG_VERBOSE,"No Hostname to set"); + return false; + } + 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!")); + + // in sta mode restart , not sure about softap + if(restart && (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() + } + + return res; } // CONFIG PORTAL @@ -475,7 +491,7 @@ 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()); // @todo not showing ip dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); // @todo new callback, webserver started, callback cannot override handlers, but can grab them first @@ -623,7 +639,7 @@ uint8_t WiFiManager::processConfigPortal(){ // Waiting for save... if(connect) { connect = false; - DEBUG_WM(DEBUG_VERBOSE,F("process connect")); + DEBUG_WM(DEBUG_VERBOSE,F("processing save")); if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast. // skip wifi if no ssid @@ -648,10 +664,12 @@ uint8_t WiFiManager::processConfigPortal(){ } if (_shouldBreakAfterConfig) { + // do save callback // @todo this is more of an exiting callback than a save, clarify when this should actually occur // confirm or verify data was saved to make this more accurate callback if ( _savewificallback != NULL) { + DEBUG_WM(DEBUG_VERBOSE,F("WiFi/Param save callback")); _savewificallback(); } shutdownConfigPortal(); @@ -750,7 +768,7 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { connRes = waitForConnectResult(); } else { - DEBUG_WM(F("No saved credentials, skipping wifi")); + DEBUG_WM(F("No wifi save required, skipping")); } } @@ -941,7 +959,7 @@ 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 page = getHTTPHead(FPSTR(S_options)); // @token options @todo replace options with title 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; @@ -1939,7 +1957,6 @@ bool WiFiManager::erase(bool opt){ // 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"); @@ -1971,7 +1988,7 @@ bool WiFiManager::erase(bool opt){ * @access public */ void WiFiManager::resetSettings() { - DEBUG_WM(F("SETTINGS ERASED")); + DEBUG_WM(F("resetSettings")); WiFi_enableSTA(true,true); // must be sta to disconnect erase if (_resetcallback != NULL) @@ -1983,7 +2000,8 @@ void WiFiManager::resetSettings() { WiFi.persistent(true); WiFi.disconnect(true); WiFi.persistent(false); - #endif + #endif + DEBUG_WM(F("SETTINGS ERASED")); } // SETTERS diff --git a/WiFiManager.h b/WiFiManager.h index d8f6757..02032f2 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -336,7 +336,7 @@ class WiFiManager unsigned long _saveTimeout = 0; // ms stop trying to connect to ap on saves, in case bugs in esp waitforconnectresult unsigned long _configPortalStart = 0; // ms config portal start time (updated for timeouts) unsigned long _webPortalAccessed = 0; // ms last web access time - WiFiMode_t _usermode = WIFI_OFF; + WiFiMode_t _usermode = WIFI_STA; // Default user mode String _wifissidprefix = FPSTR(S_ssidpre); // auto apname prefix prefix+chipid uint8_t _lastconxresult = WL_IDLE_STATUS; int _numNetworks = 0; @@ -397,7 +397,8 @@ class WiFiManager void setupConfigPortal(); bool shutdownConfigPortal(); - + bool setupHostname(bool restart); + #ifdef NO_EXTRA_4K_HEAP boolean _tryWPS = false; // try WPS on save failure, unsupported void startWPS(); diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index 597636f..f78546e 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -170,7 +170,7 @@ void setup() { std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; // wm.setMenu(menu); // custom menu, pass vector - wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu! + // wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu! // set static sta ip // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); @@ -204,7 +204,7 @@ void setup() { // wm.setCleanConnect(true); // disconenct before connect, clean connect - // wm.setBreakAfterConfig(true); + wm.setBreakAfterConfig(true); //fetches ssid and pass and tries to connect //if it does not connect it starts an access point with the specified name @@ -212,7 +212,7 @@ void setup() { //and goes into a blocking loop awaiting configuration wifiInfo(); print_oled(F("Connecting..."),2); - if(!AUTOSTARTCP || !wm.autoConnect("WM_AutoConnectAP")) { + if(!wm.autoConnect("WM_AutoConnectAP","12345678")) { Serial.println("failed to connect and hit timeout"); print_oled("Not Connected",2); } diff --git a/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino index 7ebd8d5..b231cc3 100644 --- a/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino +++ b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino @@ -6,6 +6,13 @@ */ #include // https://github.com/tzapu/WiFiManager +// include MDNS +#ifdef ESP8266 +#include +#elif defined(ESP32) +#include +#endif + // select which pin will trigger the configuration portal when set to LOW #define TRIGGER_PIN 0 @@ -20,11 +27,21 @@ void setup() { WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP // put your setup code here, to run once Serial.begin(115200); + Serial.setDebugOutput(true); + delay(1000); Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); + + // wm.resetSettings(); + wm.setHostname("MDNSEXAMPLE"); + // wm.setEnableConfigPortal(false); + // wm.setConfigPortalBlocking(false); + wm.autoConnect(); } void loop() { + MDNS.update(); doWiFiManager(); // put your main code here, to run repeatedly: } diff --git a/examples/Tests/AnonymousCB.ino b/examples/Tests/AnonymousCB.ino new file mode 100644 index 0000000..ff44976 --- /dev/null +++ b/examples/Tests/AnonymousCB.ino @@ -0,0 +1,24 @@ +#include // https://github.com/tzapu/WiFiManager + +bool _enteredConfigMode = false; + +void setup(){ + Serial.begin(115200); +WiFiManager wifiManager; + + // wifiManager.setAPCallback([this](WiFiManager* wifiManager) { + wifiManager.setAPCallback([&](WiFiManager* wifiManager) { + Serial.printf("Entered config mode:ip=%s, ssid='%s'\n", + WiFi.softAPIP().toString().c_str(), + wifiManager->getConfigPortalSSID().c_str()); + _enteredConfigMode = true; + }); + wifiManager.resetSettings(); + if (!wifiManager.autoConnect()) { + Serial.printf("*** Failed to connect and hit timeout\n"); + ESP.reset(); + delay(1000); + } +} + +void loop(){} diff --git a/strings_en.h b/strings_en.h index 85cf298..75c5fc9 100644 --- a/strings_en.h +++ b/strings_en.h @@ -25,7 +25,8 @@ const char HTTP_SCRIPT[] PROGMEM = ""; const char HTTP_HEAD_END[] PROGMEM = "
"; - +// example of embedded logo, base64 encoded inline, No styling here +// const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

"; const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

"; const char * const HTTP_PORTAL_MENU[] PROGMEM = { "

\n", // MENU_WIFI