diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 0f0d740..080e70d 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,7 +1,10 @@ -{ - // See http://go.microsoft.com/fwlink/?LinkId=827846 - // for the documentation about the extensions.json format - "recommendations": [ - "platformio.platformio-ide" - ] -} +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ], + "unwantedRecommendations": [ + "ms-vscode.cpptools-extension-pack" + ] +} diff --git a/include/Config.h b/include/Config.h index e23918b..9497477 100755 --- a/include/Config.h +++ b/include/Config.h @@ -108,7 +108,7 @@ */ #define I2C_SDA_PIN (15) #define I2C_SCL_PIN (13) -#define I2C_CLOCK_SPEED (100000) +#define I2C_CLOCK_SPEED (100000ul) /** * @brief LED pin configuration diff --git a/lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp b/lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp index 6a8ac3c..6f699fa 100644 --- a/lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp +++ b/lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp @@ -33,20 +33,20 @@ WiFiManagerParameter::WiFiManagerParameter(const char *custom) { _label = NULL; _length = 1; _value = NULL; - _labelPlacement = WFM_LABEL_BEFORE; + _labelPlacement = WFM_LABEL_DEFAULT; _customHTML = custom; } WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label) { - init(id, label, "", 0, "", WFM_LABEL_BEFORE); + init(id, label, "", 0, "", WFM_LABEL_DEFAULT); } WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length) { - init(id, label, defaultValue, length, "", WFM_LABEL_BEFORE); + init(id, label, defaultValue, length, "", WFM_LABEL_DEFAULT); } WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom) { - init(id, label, defaultValue, length, custom, WFM_LABEL_BEFORE); + init(id, label, defaultValue, length, custom, WFM_LABEL_DEFAULT); } WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { @@ -94,26 +94,26 @@ void WiFiManagerParameter::setValue(const char *defaultValue, int length) { strncpy(_value, defaultValue, _length); } } -const char* WiFiManagerParameter::getValue() { +const char* WiFiManagerParameter::getValue() const { // Serial.println(printf("Address of _value is %p\n", (void *)_value)); return _value; } -const char* WiFiManagerParameter::getID() { +const char* WiFiManagerParameter::getID() const { return _id; } -const char* WiFiManagerParameter::getPlaceholder() { +const char* WiFiManagerParameter::getPlaceholder() const { return _label; } -const char* WiFiManagerParameter::getLabel() { +const char* WiFiManagerParameter::getLabel() const { return _label; } -int WiFiManagerParameter::getValueLength() { +int WiFiManagerParameter::getValueLength() const { return _length; } -int WiFiManagerParameter::getLabelPlacement() { +int WiFiManagerParameter::getLabelPlacement() const { return _labelPlacement; } -const char* WiFiManagerParameter::getCustomHTML() { +const char* WiFiManagerParameter::getCustomHTML() const { return _customHTML; } @@ -128,7 +128,9 @@ bool WiFiManager::addParameter(WiFiManagerParameter *p) { 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"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] parameter IDs can only contain alpha numeric chars")); + #endif return false; } } @@ -136,23 +138,31 @@ bool WiFiManager::addParameter(WiFiManagerParameter *p) { // init params if never malloc if(_params == NULL){ - DEBUG_WM(DEBUG_DEV,"allocating params bytes:",_max_params * sizeof(WiFiManagerParameter*)); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("allocating params bytes:"),_max_params * sizeof(WiFiManagerParameter*)); + #endif _params = (WiFiManagerParameter**)malloc(_max_params * sizeof(WiFiManagerParameter*)); } // resize the params array by increment of WIFI_MANAGER_MAX_PARAMS if(_paramsCount == _max_params){ _max_params += WIFI_MANAGER_MAX_PARAMS; + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("Updated _max_params:"),_max_params); - DEBUG_WM(DEBUG_DEV,"re-allocating params bytes:",_max_params * sizeof(WiFiManagerParameter*)); + DEBUG_WM(DEBUG_DEV,F("re-allocating params bytes:"),_max_params * sizeof(WiFiManagerParameter*)); + #endif WiFiManagerParameter** new_params = (WiFiManagerParameter**)realloc(_params, _max_params * sizeof(WiFiManagerParameter*)); + #ifdef WM_DEBUG_LEVEL // DEBUG_WM(WIFI_MANAGER_MAX_PARAMS); // DEBUG_WM(_paramsCount); // DEBUG_WM(_max_params); + #endif if (new_params != NULL) { _params = new_params; } else { - DEBUG_WM(DEBUG_ERROR,"[ERROR] failed to realloc params, size not increased!"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] failed to realloc params, size not increased!")); + #endif return false; } } @@ -160,7 +170,9 @@ bool WiFiManager::addParameter(WiFiManagerParameter *p) { _params[_paramsCount] = p; _paramsCount++; - DEBUG_WM(DEBUG_VERBOSE,"Added Parameter:",p->getID()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Added Parameter:"),p->getID()); + #endif return true; } @@ -187,7 +199,7 @@ int WiFiManager::getParametersCount() { **/ // constructors -WiFiManager::WiFiManager(Stream& consolePort):_debugPort(consolePort){ +WiFiManager::WiFiManager(Print& consolePort):_debugPort(consolePort){ WiFiManagerInit(); } @@ -197,7 +209,7 @@ WiFiManager::WiFiManager() { void WiFiManager::WiFiManagerInit(){ setMenu(_menuIdsDefault); - if(_debug && _debugLevel > DEBUG_DEV) debugPlatformInfo(); + if(_debug && _debugLevel >= DEBUG_DEV) debugPlatformInfo(); _max_params = WIFI_MANAGER_MAX_PARAMS; } @@ -207,18 +219,22 @@ WiFiManager::~WiFiManager() { // parameters // @todo below belongs to wifimanagerparameter if (_params != NULL){ + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("freeing allocated params!")); + #endif free(_params); _params = NULL; } - // @todo remove event + // remove event // WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); #ifdef ESP32 WiFi.removeEvent(wm_event_id); #endif + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("unloading")); + #endif } void WiFiManager::_begin(){ @@ -252,15 +268,36 @@ boolean WiFiManager::autoConnect() { * @return {[type]} [description] */ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("AutoConnect")); - if(getWiFiIsSaved()){ + #endif + + #ifdef ESP32 + setupHostname(true); + + if(_hostname){ + // disable wifi if already on + if(WiFi.getMode() & WIFI_STA){ + WiFi.mode(WIFI_OFF); + int timeout = millis()+1200; + // async loop for mode change + while(WiFi.getMode()!= WIFI_OFF && millis()0){ - DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",channel); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Starting AP on channel:"),channel); + #endif } // start soft AP with password or anonymous @@ -410,7 +500,9 @@ bool WiFiManager::startAP(){ ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),1,_apHidden);//password option } } else { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!")); + #endif if(channel>0){ ret = WiFi.softAP(_apName.c_str(),"",channel,_apHidden); } @@ -421,19 +513,23 @@ bool WiFiManager::startAP(){ if(_debugLevel >= DEBUG_DEV) debugSoftAPConfig(); - if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] There was a problem starting the AP"); - // @todo add softAP retry here + // @todo add softAP retry here to dela with unknown failures delay(500); // slight delay to make sure we get an AP IP + #ifdef WM_DEBUG_LEVEL + if(!ret) DEBUG_WM(DEBUG_ERROR,F("[ERROR] There was a problem starting the AP")); DEBUG_WM(F("AP IP address:"),WiFi.softAPIP()); + #endif // set ap hostname #ifdef ESP32 - if(ret && (String)_hostname != ""){ - DEBUG_WM(DEBUG_VERBOSE,"setting softAP Hostname:",_hostname); - bool res = WiFi.softAPsetHostname(_hostname); + if(ret && _hostname != ""){ + bool res = WiFi.softAPsetHostname(_hostname.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("setting softAP Hostname:"),_hostname); if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: AP set failed!")); DEBUG_WM(DEBUG_DEV,F("hostname: AP: "),WiFi.softAPgetHostname()); + #endif } #endif @@ -447,6 +543,7 @@ bool WiFiManager::startAP(){ */ void WiFiManager::startWebPortal() { if(configPortalActive || webPortalActive) return; + connect = abort = false; setupConfigPortal(); webPortalActive = true; } @@ -458,81 +555,117 @@ void WiFiManager::startWebPortal() { */ void WiFiManager::stopWebPortal() { if(!configPortalActive && !webPortalActive) return; + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("Stopping Web Portal")); + #endif webPortalActive = false; shutdownConfigPortal(); } boolean WiFiManager::configPortalHasTimeout(){ + if(!configPortalActive) return false; + uint16_t logintvl = 30000; // how often to emit timeing out counter logging + // handle timeout portal client check if(_configPortalTimeout == 0 || (_apClientCheck && (WiFi_softap_num_stations() > 0))){ - if(millis() - timer > 30000){ + // debug num clients every 30s + if(millis() - timer > logintvl){ timer = millis(); - DEBUG_WM(DEBUG_VERBOSE,"NUM CLIENTS: " + (String)WiFi_softap_num_stations()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("NUM CLIENTS: "),(String)WiFi_softap_num_stations()); + #endif } _configPortalStart = millis(); // kludge, bump configportal start time to skew timeouts return false; } - // handle timeout + + // handle timeout webclient check if(_webClientCheck && (_webPortalAccessed>_configPortalStart)>0) _configPortalStart = _webPortalAccessed; + // handle timed out if(millis() > _configPortalStart + _configPortalTimeout){ + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("config portal has timed out")); - 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")); - } + #endif + return true; // timeout bail, else do debug logging + } + else if(_debug && _debugLevel > 0) { + // log timeout time remaining every 30s + if((millis() - timer) > logintvl){ + timer = millis(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Portal Timeout In"),(String)((_configPortalStart + _configPortalTimeout-millis())/1000) + (String)F(" seconds")); + #endif } } return false; } -void WiFiManager::setupConfigPortal() { +void WiFiManager::setupHTTPServer(){ + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("Starting Web Portal")); + #endif - // setup dns and web servers - dnsServer.reset(new DNSServer()); - server.reset(new WM_WebServer(_httpPort)); - - if(_httpPort != 80) DEBUG_WM(DEBUG_VERBOSE,"http server started with custom port: ",_httpPort); // @todo not showing ip - - /* 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()); // @todo not showing ip - dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); + if(_httpPort != 80) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("http server started with custom port: "),_httpPort); // @todo not showing ip + #endif + } - // @todo new callback, webserver started, callback cannot override handlers, but can grab them first + server.reset(new WM_WebServer(_httpPort)); + // This is not the safest way to reset the webserver, it can cause crashes on callbacks initilized before this and since its a shared pointer... if ( _webservercallback != NULL) { - _webservercallback(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("[CB] _webservercallback calling")); + #endif + _webservercallback(); // @CALLBACK } - + // @todo add a new callback maybe, after webserver started, callback cannot override handlers, but can grab them first + /* Setup httpd callbacks, web pages: root, wifi config pages, SO captive portal detectors and not found. */ - 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)); + + // G macro workaround for Uri() bug https://github.com/esp8266/Arduino/issues/7102 + server->on(WM_G(R_root), std::bind(&WiFiManager::handleRoot, this)); + server->on(WM_G(R_wifi), std::bind(&WiFiManager::handleWifi, this, true)); + server->on(WM_G(R_wifinoscan), std::bind(&WiFiManager::handleWifi, this, false)); + server->on(WM_G(R_wifisave), std::bind(&WiFiManager::handleWifiSave, this)); + server->on(WM_G(R_info), std::bind(&WiFiManager::handleInfo, this)); + server->on(WM_G(R_param), std::bind(&WiFiManager::handleParam, this)); + server->on(WM_G(R_paramsave), std::bind(&WiFiManager::handleParamSave, this)); + server->on(WM_G(R_restart), std::bind(&WiFiManager::handleReset, this)); + server->on(WM_G(R_exit), std::bind(&WiFiManager::handleExit, this)); + server->on(WM_G(R_close), std::bind(&WiFiManager::handleClose, this)); + server->on(WM_G(R_erase), std::bind(&WiFiManager::handleErase, this, false)); + server->on(WM_G(R_status), std::bind(&WiFiManager::handleWiFiStatus, this)); server->onNotFound (std::bind(&WiFiManager::handleNotFound, this)); + server->on(WM_G(R_update), std::bind(&WiFiManager::handleUpdate, this)); + server->on(WM_G(R_updatedone), HTTP_POST, std::bind(&WiFiManager::handleUpdateDone, this), std::bind(&WiFiManager::handleUpdating, this)); + server->begin(); // Web server start + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("HTTP server started")); + #endif +} + +void WiFiManager::setupDNSD(){ + dnsServer.reset(new DNSServer()); + + /* Setup the DNS server redirecting all the domains to the apIP */ + dnsServer->setErrorReplyCode(DNSReplyCode::NoError); + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM("dns server started port: ",DNS_PORT); + DEBUG_WM(DEBUG_DEV,F("dns server started with ip: "),WiFi.softAPIP()); // @todo not showing ip + #endif + dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); +} +void WiFiManager::setupConfigPortal() { + setupHTTPServer(); + _lastscan = 0; // reset network scan cache if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan , async } @@ -551,26 +684,35 @@ boolean WiFiManager::startConfigPortal() { boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { _begin(); + if(configPortalActive){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Starting Config Portal FAILED, is already running")); + #endif + return false; + } + //setup AP _apName = apName; // @todo check valid apname ? _apPassword = apPassword; + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("Starting Config Portal")); + #endif if(_apName == "") _apName = getDefaultAPName(); if(!validApPassword()) return false; // HANDLE issues with STA connections, shutdown sta if not connected, or else this will hang channel scanning and softap will not respond - // @todo sometimes still cannot connect to AP for no known reason, no events in log either if(_disableSTA || (!WiFi.isConnected() && _disableSTAConn)){ // this fixes most ap problems, however, simply doing mode(WIFI_AP) does not work if sta connection is hanging, must `wifi_station_disconnect` WiFi_Disconnect(); WiFi_enableSTA(false); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("Disabling STA")); + #endif } 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); } @@ -582,102 +724,160 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo _configPortalStart = millis(); // start access point + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("Enabling AP")); + #endif startAP(); WiFiSetCountry(); // do AP callback if set if ( _apcallback != NULL) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("[CB] _apcallback calling")); + #endif _apcallback(this); } // init configportal + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("setupConfigPortal")); + #endif setupConfigPortal(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("setupDNSD")); + #endif + setupDNSD(); + + if(!_configPortalIsBlocking){ - DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, non blocking/processing")); - return result; + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, non blocking (processing)")); + if(_configPortalTimeout > 0) DEBUG_WM(DEBUG_VERBOSE,F("Portal Timeout In"),(String)(_configPortalTimeout/1000) + (String)F(" seconds")); + #endif + return result; // skip blocking loop } - DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, blocking, waiting for clients...")); - // blocking loop waiting for config + // enter blocking loop, waiting for config + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, blocking, waiting for clients...")); + if(_configPortalTimeout > 0) DEBUG_WM(DEBUG_VERBOSE,F("Portal Timeout In"),(String)(_configPortalTimeout/1000) + (String)F(" seconds")); + #endif + while(1){ // if timed out or abort, break if(configPortalHasTimeout() || abort){ - DEBUG_WM(DEBUG_DEV,F("configportal abort")); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("configportal loop abort")); + #endif shutdownConfigPortal(); result = abort ? portalAbortResult : portalTimeoutResult; // false, false break; } state = processConfigPortal(); - + // status change, break + // @todo what is this for, should be moved inside the processor + // I think.. this is to detect autoconnect by esp in background, there are also many open issues about autoreconnect not working if(state != WL_IDLE_STATUS){ result = (state == WL_CONNECTED); // true if connected + DEBUG_WM(DEBUG_DEV,F("configportal loop break")); break; } + if(!configPortalActive) break; + yield(); // watchdog - // esp_task_wdt_reset();/ } + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_NOTIFY,F("config portal exiting")); + #endif return result; } /** * [process description] * @access public - * @return {[type]} [description] + * @return bool connected */ boolean WiFiManager::process(){ // process mdns, esp32 not required #if defined(WM_MDNS) && defined(ESP8266) MDNS.update(); #endif - + if(webPortalActive || (configPortalActive && !_configPortalIsBlocking)){ - uint8_t state = processConfigPortal(); - return state == WL_CONNECTED; + // if timed out or abort, break + if(_allowExit && (configPortalHasTimeout() || abort)){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("process loop abort")); + #endif + webPortalActive = false; + shutdownConfigPortal(); + return false; + } + + uint8_t state = processConfigPortal(); + return state == WL_CONNECTED; } return false; } -//using esp enums returns for now, should be fine +//using esp wl_status enums as returns for now, should be fine uint8_t WiFiManager::processConfigPortal(){ - //DNS handler - dnsServer->processNextRequest(); + if(configPortalActive){ + //DNS handler + dnsServer->processNextRequest(); + } + //HTTP handler server->handleClient(); // Waiting for save... if(connect) { connect = false; + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("processing save")); + #endif if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast. // skip wifi if no ssid if(_ssid == ""){ + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("No ssid, skipping wifi save")); + #endif } 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()); + uint8_t res = connectWifi(_ssid, _pass, _connectonsave) == WL_CONNECTED; + if (res || (!_connectonsave)) { + #ifdef WM_DEBUG_LEVEL + if(!_connectonsave){ + DEBUG_WM(F("SAVED with no connect to new AP")); + } else { + DEBUG_WM(F("Connect to new AP [SUCCESS]")); + DEBUG_WM(F("Got IP Address:")); + DEBUG_WM(WiFi.localIP()); + } + #endif if ( _savewificallback != NULL) { - _savewificallback(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("[CB] _savewificallback calling")); + #endif + _savewificallback(); // @CALLBACK } - shutdownConfigPortal(); + if(!_connectonsave) return WL_IDLE_STATUS; + if(_disableConfigPortal) shutdownConfigPortal(); return WL_CONNECTED; // CONNECT SUCCESS } + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_ERROR,F("[ERROR] Connect to new AP Failed")); + #endif } if (_shouldBreakAfterConfig) { @@ -686,20 +886,29 @@ uint8_t WiFiManager::processConfigPortal(){ // @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(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("[CB] WiFi/Param save callback")); + #endif + _savewificallback(); // @CALLBACK } - shutdownConfigPortal(); + if(_disableConfigPortal) shutdownConfigPortal(); return WL_CONNECT_FAILED; // CONNECT FAIL } - else{ + else if(_configPortalIsBlocking){ // 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")); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Processing - Disabling STA")); + #endif + } + else{ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Portal is non blocking - remaining open")); + #endif } } @@ -712,42 +921,59 @@ uint8_t WiFiManager::processConfigPortal(){ * @return bool success (softapdisconnect) */ bool WiFiManager::shutdownConfigPortal(){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("shutdownConfigPortal")); + #endif + if(webPortalActive) return false; - //DNS handler - dnsServer->processNextRequest(); + if(configPortalActive){ + //DNS handler + dnsServer->processNextRequest(); + } + //HTTP handler server->handleClient(); // @todo what is the proper way to shutdown and free the server up + // debug - many open issues aobut port not clearing for use with other servers server->stop(); server.reset(); - dnsServer->stop(); // free heap ? - dnsServer.reset(); WiFi.scanDelete(); // free wifi scan results if(!configPortalActive) return false; + dnsServer->stop(); // free heap ? + dnsServer.reset(); + // turn off AP // @todo bug workaround // https://github.com/esp8266/Arduino/issues/3793 // [APdisconnect] set_config failed! *WM: disconnect configportal - softAPdisconnect failed // still no way to reproduce reliably - DEBUG_WM(DEBUG_VERBOSE,F("disconnect configportal")); + bool ret = false; ret = WiFi.softAPdisconnect(false); + + #ifdef WM_DEBUG_LEVEL if(!ret)DEBUG_WM(DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); + DEBUG_WM(DEBUG_VERBOSE,F("restoring usermode"),getModeString(_usermode)); + #endif delay(1000); - DEBUG_WM(DEBUG_VERBOSE,"restoring usermode",getModeString(_usermode)); WiFi_Mode(_usermode); // restore users wifi mode, BUG https://github.com/esp8266/Arduino/issues/4372 if(WiFi.status()==WL_IDLE_STATUS){ WiFi.reconnect(); // restart wifi since we disconnected it in startconfigportal - DEBUG_WM(DEBUG_VERBOSE,"WiFi Reconnect, was idle"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Reconnect, was idle")); + #endif } - DEBUG_WM(DEBUG_VERBOSE,"wifi status:",getWLStatusString(WiFi.status())); - DEBUG_WM(DEBUG_VERBOSE,"wifi mode:",getModeString(WiFi.getMode())); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("wifi status:"),getWLStatusString(WiFi.status())); + DEBUG_WM(DEBUG_VERBOSE,F("wifi mode:"),getModeString(WiFi.getMode())); + #endif configPortalActive = false; + DEBUG_WM(DEBUG_VERBOSE,F("configportal closed")); _end(); return ret; } @@ -755,28 +981,45 @@ bool WiFiManager::shutdownConfigPortal(){ // @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) { +uint8_t WiFiManager::connectWifi(String ssid, String pass, bool connect) { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("Connecting as wifi client...")); - + #endif + uint8_t retry = 1; 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 !) - + // WiFi.setAutoReconnect(false); 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 + // @todo find out what status is when this is needed, can we detect it and handle it, say in between states or idle_status to avoid these + + // if retry without delay (via begin()), the IDF is still busy even after returning status + // E (5130) wifi:sta is connecting, return error + // [E][WiFiSTA.cpp:221] begin(): connect failed! + while(retry <= _connectRetries && (connRes!=WL_CONNECTED)){ + if(_connectRetries > 1){ + if(_aggresiveReconn) delay(1000); // add idle time before recon + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Connect Wifi, ATTEMPT #"),(String)retry+" of "+(String)_connectRetries); + #endif + } // if ssid argument provided connect to that if (ssid != "") { - wifiConnectNew(ssid,pass); - if(_saveTimeout > 0){ - connRes = waitForConnectResult(_saveTimeout); // use default save timeout for saves to prevent bugs in esp->waitforconnectresult loop - } - else { - connRes = waitForConnectResult(0); - } + wifiConnectNew(ssid,pass,connect); + // @todo connect=false seems to disconnect sta in begin() so not sure if _connectonsave is useful at all + // skip wait if not connecting + // if(connect){ + if(_saveTimeout > 0){ + connRes = waitForConnectResult(_saveTimeout); // use default save timeout for saves to prevent bugs in esp->waitforconnectresult loop + } + else { + connRes = waitForConnectResult(0); + } + // } } else { // connect using saved ssid if there is one @@ -785,11 +1028,17 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { connRes = waitForConnectResult(); } else { - DEBUG_WM(F("No wifi save required, skipping")); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("No wifi saved, skipping")); + #endif } } + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("Connection result:"),getWLStatusString(connRes)); + #endif + retry++; +} // WPS enabled? https://github.com/esp8266/Arduino/pull/4889 #ifdef NO_EXTRA_4K_HEAP @@ -815,17 +1064,22 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { * @param String ssid * @param String pass * @return bool success + * @return connect only save if false */ -bool WiFiManager::wifiConnectNew(String ssid, String pass){ +bool WiFiManager::wifiConnectNew(String ssid, String pass,bool connect){ bool ret = false; - DEBUG_WM(F("CONNECTED:"),WiFi.status() == WL_CONNECTED); + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_DEV,F("CONNECTED: "),WiFi.status() == WL_CONNECTED ? "Y" : "NO"); DEBUG_WM(F("Connecting to NEW AP:"),ssid); DEBUG_WM(DEBUG_DEV,F("Using Password:"),pass); + #endif 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()); + ret = WiFi.begin(ssid.c_str(), pass.c_str(), 0, NULL, connect); WiFi.persistent(false); - if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed"); + #ifdef WM_DEBUG_LEVEL + if(!ret) DEBUG_WM(DEBUG_ERROR,F("[ERROR] wifi begin failed")); + #endif return ret; } @@ -836,12 +1090,26 @@ bool WiFiManager::wifiConnectNew(String ssid, String pass){ */ bool WiFiManager::wifiConnectDefault(){ bool ret = false; + + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("Connecting to SAVED AP:"),WiFi_SSID(true)); DEBUG_WM(DEBUG_DEV,F("Using Password:"),WiFi_psk(true)); + #endif + ret = WiFi_enableSTA(true,storeSTAmode); - if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi enableSta failed"); + delay(500); // THIS DELAY ? + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("Mode after delay: "),getModeString(WiFi.getMode())); + if(!ret) DEBUG_WM(DEBUG_ERROR,F("[ERROR] wifi enableSta failed")); + #endif + ret = WiFi.begin(); - if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed"); + + #ifdef WM_DEBUG_LEVEL + if(!ret) DEBUG_WM(DEBUG_ERROR,F("[ERROR] wifi begin failed")); + #endif + return ret; } @@ -852,23 +1120,36 @@ bool WiFiManager::wifiConnectDefault(){ * @return bool success */ bool WiFiManager::setSTAConfig(){ + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("STA static IP:"),_sta_static_ip); + #endif bool ret = true; if (_sta_static_ip) { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("Custom static IP/GW/Subnet/DNS")); + #endif if(_sta_static_dns) { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("Custom static DNS")); + #endif ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn, _sta_static_dns); } else { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("Custom STA IP/GW/Subnet")); + #endif 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 { + #ifdef WM_DEBUG_LEVEL + if(!ret) DEBUG_WM(DEBUG_ERROR,F("[ERROR] wifi config failed")); + else DEBUG_WM(F("STA IP set:"),WiFi.localIP()); + #endif + } + else { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("setSTAConfig static ip not set, skipping")); + #endif } return ret; } @@ -886,19 +1167,23 @@ void WiFiManager::updateConxResult(uint8_t status){ #elif defined(ESP32) // if(_lastconxresult == WL_CONNECT_FAILED){ if(_lastconxresult == WL_CONNECT_FAILED || _lastconxresult == WL_DISCONNECTED){ - DEBUG_WM(DEBUG_DEV,"lastconxresulttmp:",getWLStatusString(_lastconxresulttmp)); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("lastconxresulttmp:"),getWLStatusString(_lastconxresulttmp)); + #endif if(_lastconxresulttmp != WL_IDLE_STATUS){ _lastconxresult = _lastconxresulttmp; // _lastconxresulttmp = WL_IDLE_STATUS; } } + DEBUG_WM(DEBUG_DEV,F("lastconxresult:"),getWLStatusString(_lastconxresult)); #endif - DEBUG_WM(DEBUG_DEV,"lastconxresult:",getWLStatusString(_lastconxresult)); } uint8_t WiFiManager::waitForConnectResult() { - if(_connectTimeout > 0) DEBUG_WM(DEBUG_VERBOSE,_connectTimeout,F("ms connectTimeout set")); + #ifdef WM_DEBUG_LEVEL + if(_connectTimeout > 0) DEBUG_WM(DEBUG_DEV,_connectTimeout,F("ms connectTimeout set")); + #endif return waitForConnectResult(_connectTimeout); } @@ -907,14 +1192,18 @@ uint8_t WiFiManager::waitForConnectResult() { * @param uint16_t timeout in seconds * @return uint8_t WL Status */ -uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) { +uint8_t WiFiManager::waitForConnectResult(uint32_t timeout) { if (timeout == 0){ + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("connectTimeout not set, ESP waitForConnectResult...")); + #endif return WiFi.waitForConnectResult(); } unsigned long timeoutmillis = millis() + timeout; + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,timeout,F("ms timeout, waiting for connect...")); + #endif uint8_t status = WiFi.status(); while(millis() < timeoutmillis) { @@ -923,7 +1212,9 @@ uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) { if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) { return status; } + #ifdef WM_DEBUG_LEVEL DEBUG_WM (DEBUG_VERBOSE,F(".")); + #endif delay(100); } return status; @@ -932,13 +1223,17 @@ uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) { // WPS enabled? https://github.com/esp8266/Arduino/pull/4889 #ifdef NO_EXTRA_4K_HEAP void WiFiManager::startWPS() { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("START WPS")); + #endif #ifdef ESP8266 WiFi.beginWPSConfig(); #else // @todo #endif + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("END WPS")); + #endif } #endif @@ -962,32 +1257,57 @@ String WiFiManager::getHTTPHead(String title){ return page; } +void WiFiManager::HTTPSend(String content){ + server->send(200, FPSTR(HTTP_HEAD_CT), content); +} + /** * HTTPD handler for page requests */ void WiFiManager::handleRequest() { _webPortalAccessed = millis(); + + // TESTING HTTPD AUTH RFC 2617 + // BASIC_AUTH will hold onto creds, hard to "logout", but convienent + // DIGEST_AUTH will require new auth often, and nonce is random + // bool authenticate(const char * username, const char * password); + // bool authenticateDigest(const String& username, const String& H1); + // void requestAuthentication(HTTPAuthMethod mode = BASIC_AUTH, const char* realm = NULL, const String& authFailMsg = String("") ); + + // 2.3 NO AUTH available + bool testauth = false; + if(!testauth) return; + + DEBUG_WM(DEBUG_DEV,F("DOING AUTH")); + bool res = server->authenticate("admin","12345"); + if(!res){ + #ifndef WM_NOAUTH + server->requestAuthentication(HTTPAuthMethod::BASIC_AUTH); // DIGEST_AUTH + #endif + DEBUG_WM(DEBUG_DEV,F("AUTH FAIL")); + } } /** * HTTPD CALLBACK root or redirect to captive portal */ void WiFiManager::handleRoot() { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Root")); + #endif if (captivePortal()) return; // If captive portal redirect instead of displaying the page handleRequest(); - 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 + String page = getHTTPHead(_title); // @token options @todo replace options with title + String str = FPSTR(HTTP_ROOT_MAIN); // @todo custom title + str.replace(FPSTR(T_t),_title); + str.replace(FPSTR(T_v),configPortalActive ? _apName : (getWiFiHostname() + " - " + WiFi.localIP().toString())); // use ip if ap is not active for heading @todo use hostname? page += str; page += FPSTR(HTTP_PORTAL_OPTIONS); page += getMenuOut(); reportStatus(page); page += FPSTR(HTTP_END); - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); - // server->close(); // testing reliability fix for content length mismatches during mutiple flood hits WiFi_scanNetworks(); // preload wifiscan + HTTPSend(page); if(_preloadwifiscan) WiFi_scanNetworks(_scancachetime,true); // preload wifiscan throttled, async // @todo buggy, captive portals make a query on every page load, causing this to run every time in addition to the real page load // I dont understand why, when you are already in the captive portal, I guess they want to know that its still up and not done or gone @@ -998,11 +1318,15 @@ void WiFiManager::handleRoot() { * HTTPD CALLBACK Wifi config page handler */ void WiFiManager::handleWifi(boolean scan) { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Wifi")); + #endif handleRequest(); String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi if (scan) { + #ifdef WM_DEBUG_LEVEL // DEBUG_WM(DEBUG_DEV,"refresh flag:",server->hasArg(F("refresh"))); + #endif WiFi_scanNetworks(server->hasArg(F("refresh")),false); //wifiscan, force if arg refresh page += getScanItemOut(); } @@ -1018,9 +1342,13 @@ void WiFiManager::handleWifi(boolean scan) { if(_showPassword){ pitem.replace(FPSTR(T_p), WiFi_psk()); } - else { + else if(WiFi_psk() != ""){ pitem.replace(FPSTR(T_p),FPSTR(S_passph)); } + else { + pitem.replace(FPSTR(T_p),""); + } + page += pitem; page += getStaticOut(); @@ -1035,18 +1363,20 @@ void WiFiManager::handleWifi(boolean scan) { reportStatus(page); page += FPSTR(HTTP_END); - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); - // server->close(); // testing reliability fix for content length mismatches during mutiple flood hits + HTTPSend(page); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("Sent config page")); + #endif } /** * HTTPD CALLBACK Wifi param page handler */ void WiFiManager::handleParam(){ + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Param")); + #endif handleRequest(); String page = getHTTPHead(FPSTR(S_titleparam)); // @token titlewifi @@ -1062,10 +1392,11 @@ void WiFiManager::handleParam(){ reportStatus(page); page += FPSTR(HTTP_END); - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); + HTTPSend(page); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("Sent param page")); + #endif } @@ -1073,7 +1404,11 @@ String WiFiManager::getMenuOut(){ String page; for(auto menuId :_menuIds ){ - if(((String)menuId == "param") && (_paramsCount == 0)) continue; // no params set, omit params from menu, @todo this may be undesired by someone + if((String)_menutokens[menuId] == "param" && _paramsCount == 0) continue; // no params set, omit params from menu, @todo this may be undesired by someone, use only menu to force? + if((String)_menutokens[menuId] == "custom" && _customMenuHTML!=NULL){ + page += _customMenuHTML; + continue; + } page += HTTP_PORTAL_MENU[menuId]; } @@ -1088,14 +1423,16 @@ String WiFiManager::getMenuOut(){ void WiFiManager::WiFi_scanComplete(int networksFound){ _lastscan = millis(); _numNetworks = networksFound; + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC completed"), "in "+(String)(_lastscan - _startscan)+" ms"); DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC found:"),_numNetworks); + #endif } 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); } @@ -1103,44 +1440,71 @@ bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime){ return WiFi_scanNetworks(millis()-_lastscan > cachetime,false); } bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ + #ifdef WM_DEBUG_LEVEL // 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)){ + #endif + if(_numNetworks == 0){ + DEBUG_WM(DEBUG_DEV,"NO APs found forcing new scan"); + force = true; + } + if(force || (_lastscan>0 && (millis()-_lastscan > 60000))){ int8_t res; _startscan = millis(); if(async && _asyncScan){ #ifdef ESP8266 #ifndef WM_NOASYNC // no async available < 2.4.0 + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); + #endif using namespace std::placeholders; // for `_1` WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); #else + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan SYNC started")); res = WiFi.scanNetworks(); #endif #else + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); + #endif res = WiFi.scanNetworks(true); #endif return false; } else{ + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan SYNC started")); res = WiFi.scanNetworks(); } - if(res == WIFI_SCAN_FAILED) DEBUG_WM(DEBUG_ERROR,"[ERROR] scan failed"); + if(res == WIFI_SCAN_FAILED){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] scan failed")); + #endif + } else if(res == WIFI_SCAN_RUNNING){ - DEBUG_WM(DEBUG_ERROR,"[ERROR] scan waiting"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] scan waiting")); + #endif while(WiFi.scanComplete() == WIFI_SCAN_RUNNING){ + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_ERROR,"."); + #endif delay(100); } _numNetworks = WiFi.scanComplete(); } else if(res >=0 ) _numNetworks = res; _lastscan = millis(); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); + #endif return true; - } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+" ms ago"); + } + else { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Scan is cached"),(String)(millis()-_lastscan )+" ms ago"); + #endif + } return false; } @@ -1151,11 +1515,16 @@ String WiFiManager::WiFiManager::getScanItemOut(){ int n = _numNetworks; if (n == 0) { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("No networks found")); + #endif page += FPSTR(S_nonetworks); // @token nonetworks - } + page += F("

"); + } else { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(n,F("networks found")); + #endif //sort networks int indices[n]; for (int i = 0; i < n; i++) { @@ -1186,7 +1555,9 @@ String WiFiManager::WiFiManager::getScanItemOut(){ cssid = WiFi.SSID(indices[i]); for (int j = i + 1; j < n; j++) { if (cssid == WiFi.SSID(indices[j])) { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("DUP AP:"),WiFi.SSID(indices[j])); + #endif indices[j] = -1; // set dup aps to index -1 } } @@ -1213,14 +1584,21 @@ String WiFiManager::WiFiManager::getScanItemOut(){ for (int i = 0; i < n; i++) { if (indices[i] == -1) continue; // skip dups + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("AP: "),(String)WiFi.RSSI(indices[i]) + " " + (String)WiFi.SSID(indices[i])); + #endif 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(WiFi.SSID(indices[i]) == ""){ + // Serial.println(WiFi.BSSIDstr(indices[i])); + continue; // No idea why I am seeing these, lets just skip them for now + } + item.replace(FPSTR(T_V), htmlEntities(WiFi.SSID(indices[i]))); // ssid no encoding + item.replace(FPSTR(T_v), htmlEntities(WiFi.SSID(indices[i]),true)); // 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 @@ -1232,11 +1610,15 @@ String WiFiManager::WiFiManager::getScanItemOut(){ item.replace(FPSTR(T_i), ""); } } - //DEBUG_WM(item); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,item); + #endif page += item; delay(0); } else { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("Skipping , does not meet _minimumQuality")); + #endif } } @@ -1263,7 +1645,9 @@ 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"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("_staShowStaticFields")); + #endif 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 @@ -1286,6 +1670,10 @@ String WiFiManager::getStaticOut(){ String WiFiManager::getParamOut(){ String page; + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("getParamOut"),_paramsCount); + #endif + if(_paramsCount > 0){ String HTTP_PARAM_temp = FPSTR(HTTP_FORM_LABEL); @@ -1300,13 +1688,20 @@ String WiFiManager::getParamOut(){ bool tok_c = HTTP_PARAM_temp.indexOf(FPSTR(T_c)) > 0; 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) { - DEBUG_WM(DEBUG_ERROR,"[ERROR] WiFiManagerParameter is out of scope"); - break; + //Serial.println((String)_params[i]->_length); + if (_params[i] == NULL || _params[i]->_length == 0 || _params[i]->_length > 99999) { + // try to detect param scope issues, doesnt always catch but works ok + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFiManagerParameter is out of scope")); + #endif + return ""; } + } + // add the extra parameters to the form + for (int i = 0; i < _paramsCount; i++) { // label before or after, @todo this could be done via floats or CSS and eliminated String pitem; switch (_params[i]->getLabelPlacement()) { @@ -1349,58 +1744,69 @@ String WiFiManager::getParamOut(){ } void WiFiManager::handleWiFiStatus(){ + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi status ")); + #endif handleRequest(); String page; // String page = "{\"result\":true,\"count\":1}"; #ifdef WM_JSTEST page = FPSTR(HTTP_JS); #endif - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); + HTTPSend(page); } /** * HTTPD CALLBACK save form and redirect to WLAN config page again */ void WiFiManager::handleWifiSave() { + #ifdef WM_DEBUG_LEVEL 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)); + #endif handleRequest(); - // @todo use new callback for before paramsaves - if ( _presavecallback != NULL) { - _presavecallback(); - } - //SAVE/connect here _ssid = server->arg(F("s")).c_str(); _pass = server->arg(F("p")).c_str(); - if(_paramsInWifi) doParamSave(); - + // set static ips from server args 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()); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("static ip:"),ip); + #endif } if (server->arg(FPSTR(S_gw)) != "") { String gw = server->arg(FPSTR(S_gw)); optionalIPFromString(&_sta_static_gw, gw.c_str()); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("static gateway:"),gw); + #endif } if (server->arg(FPSTR(S_sn)) != "") { String sn = server->arg(FPSTR(S_sn)); optionalIPFromString(&_sta_static_sn, sn.c_str()); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("static netmask:"),sn); + #endif } if (server->arg(FPSTR(S_dns)) != "") { String dns = server->arg(FPSTR(S_dns)); optionalIPFromString(&_sta_static_dns, dns.c_str()); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("static DNS:"),dns); + #endif } + if (_presavewificallback != NULL) { + _presavewificallback(); // @CALLBACK + } + + if(_paramsInWifi) doParamSave(); + String page; if(_ssid == ""){ @@ -1413,19 +1819,24 @@ void WiFiManager::handleWifiSave() { } page += FPSTR(HTTP_END); - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->sendHeader(FPSTR(HTTP_HEAD_CORS), FPSTR(HTTP_HEAD_CORS_ALLOW_ALL)); - server->send(200, FPSTR(HTTP_HEAD_CT), page); + server->sendHeader(FPSTR(HTTP_HEAD_CORS), FPSTR(HTTP_HEAD_CORS_ALLOW_ALL)); // @HTTPHEAD send cors + HTTPSend(page); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); + #endif connect = true; //signal ready to connect/reset process in processConfigPortal } void WiFiManager::handleParamSave() { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Param save ")); + #endif + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); + #endif handleRequest(); doParamSave(); @@ -1434,26 +1845,31 @@ void WiFiManager::handleParamSave() { page += FPSTR(HTTP_PARAMSAVED); page += FPSTR(HTTP_END); - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); + HTTPSend(page); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("Sent param save page")); + #endif } void WiFiManager::doParamSave(){ // @todo use new callback for before paramsaves, is this really needed? - if ( _presavecallback != NULL) { - _presavecallback(); + if ( _presaveparamscallback != NULL) { + _presaveparamscallback(); // @CALLBACK } //parameters if(_paramsCount > 0){ + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("Parameters")); DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + #endif 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"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFiManagerParameter is out of scope")); + #endif break; // @todo might not be needed anymore } //read parameter from server @@ -1467,13 +1883,17 @@ void WiFiManager::doParamSave(){ //store it in params array value.toCharArray(_params[i]->_value, _params[i]->_length+1); // length+1 null terminated + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,(String)_params[i]->getID() + ":",value); + #endif } + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + #endif } if ( _saveparamscallback != NULL) { - _saveparamscallback(); + _saveparamscallback(); // @CALLBACK } } @@ -1482,7 +1902,9 @@ void WiFiManager::doParamSave(){ * HTTPD CALLBACK info page */ void WiFiManager::handleInfo() { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Info")); + #endif handleRequest(); String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo reportStatus(page); @@ -1492,7 +1914,7 @@ void WiFiManager::handleInfo() { //@todo convert to enum or refactor to strings //@todo wrap in build flag to remove all info code for memory saving #ifdef ESP8266 - infos = 27; + infos = 28; String infoids[] = { F("esphead"), F("uptime"), @@ -1500,7 +1922,6 @@ void WiFiManager::handleInfo() { F("fchipid"), F("idesize"), F("flashsize"), - F("sdkver"), F("corever"), F("bootver"), F("cpufreq"), @@ -1509,46 +1930,53 @@ void WiFiManager::handleInfo() { F("memsmeter"), F("lastreset"), F("wifihead"), - F("apip"), - F("apmac"), - F("apssid"), - F("apbssid"), + F("conx"), + F("stassid"), F("staip"), F("stagw"), F("stasub"), F("dnss"), F("host"), F("stamac"), - F("conx"), - F("autoconx") + F("autoconx"), + F("wifiaphead"), + F("apssid"), + F("apip"), + F("apbssid"), + F("apmac") }; #elif defined(ESP32) - infos = 22; + // add esp_chip_info ? + infos = 26; String infoids[] = { F("esphead"), F("uptime"), F("chipid"), F("chiprev"), F("idesize"), - F("sdkver"), + F("flashsize"), F("cpufreq"), F("freeheap"), + F("memsketch"), + F("memsmeter"), F("lastreset"), - // F("temp"), F("wifihead"), - F("apip"), - F("apmac"), - F("aphost"), - F("apssid"), - F("apbssid"), + F("conx"), + F("stassid"), F("staip"), F("stagw"), F("stasub"), F("dnss"), F("host"), F("stamac"), - F("conx") + F("apssid"), + F("wifiaphead"), + F("apip"), + F("apmac"), + F("aphost"), + F("apbssid") + // F("temp") }; #endif @@ -1556,15 +1984,28 @@ void WiFiManager::handleInfo() { if(infoids[i] != NULL) page += getInfoData(infoids[i]); } page += F(""); + + page += F("

About


"); + page += getInfoData("aboutver"); + page += getInfoData("aboutarduinover"); + page += getInfoData("aboutidfver"); + page += getInfoData("aboutdate"); + page += F("
"); + + if(_showInfoUpdate){ + page += HTTP_PORTAL_MENU[8]; + page += HTTP_PORTAL_MENU[9]; + } if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); if(_showBack) page += FPSTR(HTTP_BACKBTN); 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); + HTTPSend(page); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,F("Sent info page")); + #endif } String WiFiManager::getInfoData(String id){ @@ -1609,14 +2050,9 @@ String WiFiManager::getInfoData(String id){ #ifdef ESP8266 p = FPSTR(HTTP_INFO_flashsize); p.replace(FPSTR(T_1),(String)ESP.getFlashChipRealSize()); - #endif - } - 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()); + #elif defined ESP32 + p = FPSTR(HTTP_INFO_psrsize); + p.replace(FPSTR(T_1),(String)ESP.getPsramSize()); #endif } else if(id==F("corever")){ @@ -1639,20 +2075,16 @@ String WiFiManager::getInfoData(String id){ p = FPSTR(HTTP_INFO_freeheap); p.replace(FPSTR(T_1),(String)ESP.getFreeHeap()); } - #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())); } - #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())); } - #endif else if(id==F("lastreset")){ #ifdef ESP8266 p = FPSTR(HTTP_INFO_lastreset); @@ -1700,14 +2132,27 @@ String WiFiManager::getInfoData(String id){ p.replace(FPSTR(T_1),WiFi.softAPgetHostname()); } #endif + #ifndef WM_NOSOFTAPSSID + #ifdef ESP8266 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(WiFi.softAPSSID())); } + #endif + #endif else if(id==F("apbssid")){ p = FPSTR(HTTP_INFO_apbssid); p.replace(FPSTR(T_1),(String)WiFi.BSSIDstr()); } + // softAPgetHostname // esp32 + // softAPSubnetCIDR + // softAPNetworkID + // softAPBroadcastIP + + else if(id==F("stassid")){ + p = FPSTR(HTTP_INFO_stassid); + p.replace(FPSTR(T_1),htmlEntities((String)WiFi_SSID())); + } else if(id==F("staip")){ p = FPSTR(HTTP_INFO_staip); p.replace(FPSTR(T_1),WiFi.localIP().toString()); @@ -1746,27 +2191,62 @@ String WiFiManager::getInfoData(String id){ p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); } #endif - #ifdef ESP32 + #if defined(ESP32) && !defined(WM_NOTEMP) 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)); + // p.replace(FPSTR(T_3),(String)hallRead()); + p.replace(FPSTR(T_3),"NA"); } #endif + else if(id==F("aboutver")){ + p = FPSTR(HTTP_INFO_aboutver); + p.replace(FPSTR(T_1),FPSTR(WM_VERSION_STR)); + } + else if(id==F("aboutarduinover")){ + #ifdef VER_ARDUINO_STR + p = FPSTR(HTTP_INFO_aboutarduino); + p.replace(FPSTR(T_1),String(VER_ARDUINO_STR)); + #endif + } + // else if(id==F("aboutidfver")){ + // #ifdef VER_IDF_STR + // p = FPSTR(HTTP_INFO_aboutidf); + // p.replace(FPSTR(T_1),String(VER_IDF_STR)); + // #endif + // } + else if(id==F("aboutsdkver")){ + p = FPSTR(HTTP_INFO_sdkver); + #ifdef ESP32 + p.replace(FPSTR(T_1),(String)esp_get_idf_version()); + // p.replace(FPSTR(T_1),(String)system_get_sdk_version()); // deprecated + #else + p.replace(FPSTR(T_1),(String)system_get_sdk_version()); + #endif + } + else if(id==F("aboutdate")){ + p = FPSTR(HTTP_INFO_aboutdate); + p.replace(FPSTR(T_1),String(__DATE__ " " __TIME__)); + } return p; } /** - * HTTPD CALLBACK root or redirect to captive portal + * HTTPD CALLBACK exit, closes configportal if blocking, if non blocking undefined */ void WiFiManager::handleExit() { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Exit")); + #endif handleRequest(); String page = getHTTPHead(FPSTR(S_titleexit)); // @token titleexit page += FPSTR(S_exiting); // @token exiting - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); + // ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'}) + server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); // @HTTPHEAD send cache + HTTPSend(page); + delay(2000); abort = true; } @@ -1774,16 +2254,19 @@ void WiFiManager::handleExit() { * HTTPD CALLBACK reset page */ void WiFiManager::handleReset() { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Reset")); + #endif handleRequest(); String page = getHTTPHead(FPSTR(S_titlereset)); //@token titlereset page += FPSTR(S_resetting); //@token resetting page += FPSTR(HTTP_END); - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); + HTTPSend(page); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("RESETTING ESP")); + #endif delay(1000); reboot(); } @@ -1796,7 +2279,9 @@ void WiFiManager::handleReset() { // handleErase(false); // } void WiFiManager::handleErase(boolean opt) { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Erase")); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_NOTIFY,F("<- HTTP Erase")); + #endif handleRequest(); String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase @@ -1805,16 +2290,19 @@ void WiFiManager::handleErase(boolean opt) { if(ret) page += FPSTR(S_resetting); // @token resetting else { page += FPSTR(S_error); // @token erroroccur + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFi EraseConfig failed")); + #endif } page += FPSTR(HTTP_END); - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); + HTTPSend(page); if(ret){ delay(2000); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("RESETTING ESP")); + #endif reboot(); } } @@ -1837,10 +2325,9 @@ void WiFiManager::handleNotFound() { 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("Cache-Control"), F("no-cache, no-store, must-revalidate")); // @HTTPHEAD send cache 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 ); } @@ -1850,7 +2337,9 @@ void WiFiManager::handleNotFound() { * Return true in that case so the page handler do not try to handle the request again. */ boolean WiFiManager::captivePortal() { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_DEV,"-> " + server->hostHeader()); + #endif if(!_enableCaptivePortal) return false; // skip redirections, @todo maybe allow redirection even when no cp ? might be useful @@ -1860,8 +2349,10 @@ boolean WiFiManager::captivePortal() { // doredirect = !isIp(server->hostHeader()) // old check if (doredirect) { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("<- Request redirected to captive portal")); - server->sendHeader(F("Location"), (String)F("http://") + serverLoc, true); + #endif + server->sendHeader(F("Location"), (String)F("http://") + serverLoc, true); // @HTTPHEAD send redirect 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; @@ -1874,18 +2365,23 @@ void WiFiManager::stopCaptivePortal(){ // @todo maybe disable configportaltimeout(optional), or just provide callback for user } +// HTTPD CALLBACK, handle close, stop captive portal, if not enabled undefined void WiFiManager::handleClose(){ + DEBUG_WM(DEBUG_VERBOSE,F("Disabling Captive Portal")); stopCaptivePortal(); + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP close")); + #endif handleRequest(); String page = getHTTPHead(FPSTR(S_titleclose)); // @token titleclose page += FPSTR(S_closing); // @token closing - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); + HTTPSend(page); } void WiFiManager::reportStatus(String &page){ - updateConxResult(WiFi.status()); + // updateConxResult(WiFi.status()); // @todo: this defeats the purpose of last result, update elsewhere or add logic here + DEBUG_WM(DEBUG_DEV,F("[WIFI] reportStatus prev:"),getWLStatusString(_lastconxresult)); + DEBUG_WM(DEBUG_DEV,F("[WIFI] reportStatus current:"),getWLStatusString(WiFi.status())); String str; if (WiFi_SSID() != ""){ if (WiFi.status()==WL_CONNECTED){ @@ -1951,10 +2447,14 @@ bool WiFiManager::stopConfigPortal(){ */ bool WiFiManager::disconnect(){ if(WiFi.status() != WL_CONNECTED){ - DEBUG_WM(DEBUG_VERBOSE,"Disconnecting: Not connected"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Disconnecting: Not connected")); + #endif return false; } - DEBUG_WM("Disconnecting"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Disconnecting")); + #endif return WiFi_Disconnect(); } @@ -1963,7 +2463,9 @@ bool WiFiManager::disconnect(){ * @access public */ void WiFiManager::reboot(){ - DEBUG_WM("Restarting"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Restarting")); + #endif ESP.restart(); } @@ -1976,34 +2478,52 @@ bool WiFiManager::erase(){ } bool WiFiManager::erase(bool opt){ + #ifdef WM_DEBUG_LEVEL DEBUG_WM("Erasing"); + #endif #if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) // if opt true, do nvs erase if(opt){ - DEBUG_WM("Erasing NVS"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing NVS")); + #endif esp_err_t err; err = nvs_flash_init(); - DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_init: ",err!=ESP_OK ? (String)err : "Success"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("nvs_flash_init: "),err!=ESP_OK ? (String)err : "Success"); + #endif err = nvs_flash_erase(); - DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_erase: ", err!=ESP_OK ? (String)err : "Success"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("nvs_flash_erase: "), err!=ESP_OK ? (String)err : "Success"); + #endif return err == ESP_OK; } #elif defined(ESP8266) && defined(spiffs_api_h) if(opt){ bool ret = false; if(SPIFFS.begin()){ - DEBUG_WM("Erasing SPIFFS"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing SPIFFS")); + #endif bool ret = SPIFFS.format(); - DEBUG_WM(DEBUG_VERBOSE,"spiffs erase: ",ret ? "Success" : "ERROR"); - } else DEBUG_WM("[ERROR] Could not start SPIFFS"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("spiffs erase: "),ret ? "Success" : "ERROR"); + #endif + } else{ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("[ERROR] Could not start SPIFFS")); + #endif + } return ret; } #else (void)opt; #endif - DEBUG_WM("Erasing WiFi Config"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing WiFi Config")); + #endif return WiFi_eraseConfig(); } @@ -2013,11 +2533,14 @@ bool WiFiManager::erase(bool opt){ * @access public */ void WiFiManager::resetSettings() { +#ifdef WM_DEBUG_LEVEL DEBUG_WM(F("resetSettings")); + #endif WiFi_enableSTA(true,true); // must be sta to disconnect erase - - if (_resetcallback != NULL) - _resetcallback(); + delay(500); // ensure sta is enabled + if (_resetcallback != NULL){ + _resetcallback(); // @CALLBACK + } #ifdef ESP32 WiFi.disconnect(true,true); @@ -2026,7 +2549,9 @@ void WiFiManager::resetSettings() { WiFi.disconnect(true); WiFi.persistent(false); #endif + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("SETTINGS ERASED")); + #endif } // SETTERS @@ -2057,6 +2582,16 @@ void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { void WiFiManager::setConnectTimeout(unsigned long seconds) { _connectTimeout = seconds * 1000; } + +/** + * [setConnectRetries description] + * @access public + * @param {[type]} uint8_t numRetries [description] + */ +void WiFiManager::setConnectRetries(uint8_t numRetries){ + _connectRetries = constrain(numRetries,1,10); +} + /** * toggle _cleanconnect, always disconnect before connecting * @param {[type]} bool enable [description] @@ -2074,6 +2609,16 @@ void WiFiManager::setSaveConnectTimeout(unsigned long seconds) { _saveTimeout = seconds * 1000; } +/** + * Set save portal connect on save option, + * if false, will only save credentials not connect + * @access public + * @param {[type]} bool connect [description] + */ +void WiFiManager::setSaveConnect(bool connect) { + _connectonsave = connect; +} + /** * [setDebugOutput description] * @access public @@ -2084,6 +2629,11 @@ void WiFiManager::setDebugOutput(boolean debug) { if(_debug && _debugLevel == DEBUG_DEV) debugPlatformInfo(); } +void WiFiManager::setDebugOutput(boolean debug, String prefix) { + _debugPrefix = prefix; + setDebugOutput(debug); +} + /** * [setAPStaticIPConfig description] * @access public @@ -2172,6 +2722,15 @@ void WiFiManager::setSaveConfigCallback( std::function func ) { _savewificallback = 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 ) { + _presavewificallback = func; +} + /** * setConfigResetCallback, set a callback to occur when a resetSettings() occurs * @access public @@ -2191,22 +2750,41 @@ void WiFiManager::setSaveParamsCallback( std::function func ) { } /** - * setPreSaveConfigCallback, set a callback to fire before saving wifi or params + * setPreSaveParamsCallback, set a pre save params callback on params save prior to anything else * @access public * @param {[type]} void (*func)(void) */ -void WiFiManager::setPreSaveConfigCallback( std::function func ) { - _presavecallback = func; +void WiFiManager::setPreSaveParamsCallback( std::function func ) { + _presaveparamscallback = func; +} + +/** + * setPreOtaUpdateCallback, set a callback to fire before OTA update + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreOtaUpdateCallback( std::function func ) { + _preotaupdatecallback = func; } /** * set custom head html - * custom element will be added to head, eg. new style tag etc. + * custom element will be added to head, eg. new meta,style,script tag etc. + * @access public + * @param char element + */ +void WiFiManager::setCustomHeadElement(const char* html) { + _customHeadElement = html; +} + +/** + * set custom menu html + * custom element will be added to menu under custom menu item. * @access public * @param char element */ -void WiFiManager::setCustomHeadElement(const char* element) { - _customHeadElement = element; +void WiFiManager::setCustomMenuHTML(const char* html) { + _customMenuHTML = html; } /** @@ -2227,8 +2805,8 @@ void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) { * @access public * @param boolean shoudlBlock [false] */ -void WiFiManager::setConfigPortalBlocking(boolean shoudlBlock) { - _configPortalIsBlocking = shoudlBlock; +void WiFiManager::setConfigPortalBlocking(boolean shouldBlock) { + _configPortalIsBlocking = shouldBlock; } /** @@ -2241,7 +2819,11 @@ void WiFiManager::setConfigPortalBlocking(boolean shoudlBlock) { */ void WiFiManager::setRestorePersistent(boolean persistent) { _userpersistent = persistent; - if(!persistent) DEBUG_WM(F("persistent is off")); + if(!persistent){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("persistent is off")); + #endif + } } /** @@ -2349,6 +2931,17 @@ void WiFiManager::setEnableConfigPortal(boolean enable) _enableConfigPortal = enable; } +/** + * toggle configportal if autoconnect failed + * if enabled, then the configportal will be de-activated on wifi save + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setDisableConfigPortal(boolean enable) +{ + _disableConfigPortal = enable; +} /** * set the hostname (dhcp client id) @@ -2358,6 +2951,12 @@ void WiFiManager::setEnableConfigPortal(boolean enable) * @return bool false if hostname is not valid */ bool WiFiManager::setHostname(const char * hostname){ + //@todo max length 32 + _hostname = String(hostname); + return true; +} + +bool WiFiManager::setHostname(String hostname){ //@todo max length 32 _hostname = hostname; return true; @@ -2388,6 +2987,47 @@ void WiFiManager::setShowInfoErase(boolean enabled){ _showInfoErase = enabled; } +/** + * toggle showing update upload web ota button on info page + * @param boolean enabled + */ +void WiFiManager::setShowInfoUpdate(boolean enabled){ + _showInfoUpdate = enabled; +} + +/** + * check if the config portal is running + * @return bool true if active + */ +bool WiFiManager::getConfigPortalActive(){ + return configPortalActive; +} + +/** + * [getConfigPortalActive description] + * @return bool true if active + */ +bool WiFiManager::getWebPortalActive(){ + return webPortalActive; +} + + +String WiFiManager::getWiFiHostname(){ + #ifdef ESP32 + return (String)WiFi.getHostname(); + #else + return (String)WiFi.hostname(); + #endif +} + +/** + * [setTitle description] + * @param String title, set app title + */ +void WiFiManager::setTitle(String title){ + _title = title; +} + /** * set menu items and order * if param is present in menu , params will be removed from wifi page automatically @@ -2398,7 +3038,9 @@ 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"); +#ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_DEV,"setmenu array"); + #endif _menuIds.clear(); for(size_t i = 0; i < size; i++){ for(size_t j = 0; j < _nummenutokens; j++){ @@ -2408,7 +3050,9 @@ void WiFiManager::setMenu(const char * menu[], uint8_t size){ } } } + #ifdef WM_DEBUG_LEVEL // DEBUG_WM(getMenuOut()); + #endif } /** @@ -2421,7 +3065,9 @@ void WiFiManager::setMenu(const char * menu[], uint8_t size){ * @param {[type]} std::vector& menu [description] */ void WiFiManager::setMenu(std::vector& menu){ - // DEBUG_WM(DEBUG_VERBOSE,"setmenu vector"); +#ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_DEV,"setmenu vector"); + #endif _menuIds.clear(); for(auto menuitem : menu ){ for(size_t j = 0; j < _nummenutokens; j++){ @@ -2431,7 +3077,9 @@ void WiFiManager::setMenu(std::vector& menu){ } } } - // DEBUG_WM(getMenuOut()); + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_DEV,getMenuOut()); + #endif } @@ -2481,6 +3129,11 @@ bool WiFiManager::getWiFiIsSaved(){ return WiFi_hasAutoConnect(); } +/** + * getDefaultAPName + * @since $dev + * @return string + */ String WiFiManager::getDefaultAPName(){ String hostString = String(WIFI_getChipId(),HEX); hostString.toUpperCase(); @@ -2506,10 +3159,29 @@ void WiFiManager::setClass(String str){ _bodyClass = str; } +/** + * setDarkMode + * @param bool enable, enable dark mode via invert class + */ +void WiFiManager::setDarkMode(bool enable){ + _bodyClass = enable ? "invert" : ""; +} + +/** + * setHttpPort + * @param uint16_t port webserver port number default 80 + */ void WiFiManager::setHttpPort(uint16_t port){ _httpPort = port; } + +bool WiFiManager::preloadWiFi(String ssid, String pass){ + _defaultssid = ssid; + _defaultpass = pass; + return true; +} + // HELPERS /** @@ -2554,12 +3226,12 @@ void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { if(!_debug || _debugLevel < level) return; if(_debugLevel >= DEBUG_MAX){ - uint32_t free; - uint16_t max; - uint8_t frag; #ifdef ESP8266 - ESP.getHeapStats(&free, &max, &frag); - _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); + // uint32_t free; + // uint16_t max; + // uint8_t frag; + // ESP.getHeapStats(&free, &max, &frag);// @todo Does not exist in 2.3.0 + // _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); #elif defined ESP32 // total_free_bytes; ///< Total free bytes in the heap. Equivalent to multi_free_heap_size(). // total_allocated_bytes; ///< Total bytes allocated to data in the heap. @@ -2570,14 +3242,14 @@ void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { // total_blocks; ///< Total number of (variable size) blocks in the heap. multi_heap_info_t info; heap_caps_get_info(&info, MALLOC_CAP_INTERNAL); - free = info.total_free_bytes; - max = info.largest_free_block; - frag = 100 - (max * 100) / free; + uint32_t free = info.total_free_bytes; + uint16_t max = info.largest_free_block; + uint8_t frag = 100 - (max * 100) / free; _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); #endif } - _debugPort.print("*WM: "); - if(_debugLevel == DEBUG_DEV) _debugPort.print("["+(String)level+"] "); + _debugPort.print(_debugPrefix); + if(_debugLevel >= debugLvlShow) _debugPort.print("["+(String)level+"] "); _debugPort.print(text); if(textb){ _debugPort.print(" "); @@ -2592,19 +3264,23 @@ void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { * @return {[type]} [description] */ void WiFiManager::debugSoftAPConfig(){ - wifi_country_t country; #ifdef ESP8266 softap_config config; wifi_softap_get_config(&config); - wifi_get_country(&country); + #if !defined(WM_NOCOUNTRY) + wifi_country_t country; + wifi_get_country(&country); + #endif #elif defined(ESP32) + wifi_country_t country; wifi_config_t conf_config; esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK wifi_ap_config_t config = conf_config.ap; esp_wifi_get_country(&country); #endif + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("SoftAP Configuration")); DEBUG_WM(FPSTR(D_HR)); DEBUG_WM(F("ssid: "),(char *) config.ssid); @@ -2614,9 +3290,14 @@ void WiFiManager::debugSoftAPConfig(){ 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("country: "),(String)country.cc); + #endif + #if !defined(WM_NOCOUNTRY) + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("country: "),(String)country.cc); + #endif DEBUG_WM(F("beacon_interval: "),(String)config.beacon_interval + "(ms)"); DEBUG_WM(FPSTR(D_HR)); + #endif } /** @@ -2627,21 +3308,26 @@ void WiFiManager::debugSoftAPConfig(){ void WiFiManager::debugPlatformInfo(){ #ifdef ESP8266 system_print_meminfo(); + #ifdef WM_DEBUG_LEVEL 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()); + #endif #elif defined(ESP32) - size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); - DEBUG_WM("Free heap: ", ESP.getFreeHeap()); - DEBUG_WM("ESP SDK version: ", ESP.getSdkVersion()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Free heap: "), ESP.getFreeHeap()); + DEBUG_WM(F("ESP SDK version: "), ESP.getSdkVersion()); + #endif // esp_chip_info_t chipInfo; // esp_chip_info(&chipInfo); + #ifdef WM_DEBUG_LEVEL // DEBUG_WM("Chip Info: Model: ",chipInfo.model); // DEBUG_WM("Chip Info: Cores: ",chipInfo.cores); // DEBUG_WM("Chip Info: Rev: ",chipInfo.revision); // DEBUG_WM(printf("Chip Info: Model: %d, cores: %d, revision: %d", chipInfo.model.c_str(), chipInfo.cores, chipInfo.revision)); // DEBUG_WM("Chip Rev: ",(String)ESP.getChipRevision()); + #endif // core version is not avail #endif } @@ -2685,12 +3371,16 @@ boolean WiFiManager::validApPassword(){ if (_apPassword == NULL) _apPassword = ""; if (_apPassword != "") { if (_apPassword.length() < 8 || _apPassword.length() > 63) { + #ifdef WM_DEBUG_LEVEL DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); + #endif _apPassword = ""; - return false; // @todo FATAL or fallback to empty ? + return false; // @todo FATAL or fallback to empty , currently fatal, fail secure. } + #ifdef WM_DEBUG_LEVEL DEBUG_WM(DEBUG_VERBOSE,F("AccessPoint set password is VALID")); - DEBUG_WM(_apPassword); + DEBUG_WM(DEBUG_DEV,"ap pass",_apPassword); + #endif } return true; } @@ -2701,11 +3391,13 @@ boolean WiFiManager::validApPassword(){ * @param string str string to replace entities * @return string encoded string */ -String WiFiManager::htmlEntities(String str) { +String WiFiManager::htmlEntities(String str, bool whitespace) { str.replace("&","&"); str.replace("<","<"); str.replace(">",">"); - // str.replace("'","'"); + str.replace("'","'"); + if(whitespace) str.replace(" "," "); + // str.replace("-","–"); // str.replace("\"","""); // str.replace("/": "/"); // str.replace("`": "`"); @@ -2724,8 +3416,16 @@ String WiFiManager::getWLStatusString(uint8_t status){ return FPSTR(S_NA); } +String WiFiManager::getWLStatusString(){ + uint8_t status = WiFi.status(); + if(status <= 7) return WIFI_STA_STATUS[status]; + return FPSTR(S_NA); +} + String WiFiManager::encryptionTypeStr(uint8_t authmode) { +#ifdef WM_DEBUG_LEVEL // DEBUG_WM("enc_tye: ",authmode); + #endif return AUTH_MODE_NAMES[authmode]; } @@ -2736,25 +3436,67 @@ String WiFiManager::getModeString(uint8_t mode){ bool WiFiManager::WiFiSetCountry(){ if(_wificountry == "") return false; // skip not set - bool ret = false; + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("WiFiSetCountry to"),_wificountry); + #endif + +/* + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by eps_wifi_init + * - ESP_ERR_WIFI_IF: invalid interface + * - ESP_ERR_WIFI_ARG: invalid argument + * - others: refer to error codes in esp_err.h + */ + + // @todo move these definitions, and out of cpp `esp_wifi_set_country(&WM_COUNTRY_US)` + bool ret = true; + // ret = esp_wifi_set_bandwidth(WIFI_IF_AP,WIFI_BW_HT20); // WIFI_BW_HT40 #ifdef ESP32 - // @todo check if wifi is init, no idea how, doesnt seem to be exposed atm ( might be now! ) - 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"); + esp_err_t err = ESP_OK; + // @todo check if wifi is init, no idea how, doesnt seem to be exposed atm ( check again it might be now! ) + if(WiFi.getMode() == WIFI_MODE_NULL){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] cannot set country, wifi not init"); + } // exception if wifi not init! + // Assumes that _wificountry is set to one of the supported country codes : "01"(world safe mode) "AT","AU","BE","BG","BR", + // "CA","CH","CN","CY","CZ","DE","DK","EE","ES","FI","FR","GB","GR","HK","HR","HU", + // "IE","IN","IS","IT","JP","KR","LI","LT","LU","LV","MT","MX","NL","NO","NZ","PL","PT", + // "RO","SE","SI","SK","TW","US" + // If an invalid country code is passed, ESP_ERR_WIFI_ARG will be returned + // This also uses 802.11d mode, which matches the STA to the country code of the AP it connects to (meaning + // that the country code will be overridden if connecting to a "foreign" AP) + else { + #ifndef WM_NOCOUNTRY + err = esp_wifi_set_country_code(_wificountry.c_str(), true); + #else + DEBUG_WM(DEBUG_ERROR,"[ERROR] esp wifi set country is not available"); + err = true; + #endif + } + #ifdef WM_DEBUG_LEVEL + if(err){ + if(err == ESP_ERR_WIFI_NOT_INIT) DEBUG_WM(DEBUG_ERROR,"[ERROR] ESP_ERR_WIFI_NOT_INIT"); + else if(err == ESP_ERR_INVALID_ARG) DEBUG_WM(DEBUG_ERROR,"[ERROR] ESP_ERR_WIFI_ARG (invalid country code)"); + else if(err != ESP_OK)DEBUG_WM(DEBUG_ERROR,"[ERROR] unknown error",(String)err); + } + #endif + ret = err == ESP_OK; - #elif defined(ESP8266) + #elif defined(ESP8266) && !defined(WM_NOCOUNTRY) // if(WiFi.getMode() == WIFI_OFF); // exception if wifi not init! if(_wificountry == "US") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_US); else if(_wificountry == "JP") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_JP); else if(_wificountry == "CN") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_CN); - else DEBUG_WM(DEBUG_ERROR,"[ERROR] country code not found"); + #ifdef WM_DEBUG_LEVEL + else DEBUG_WM(DEBUG_ERROR,F("[ERROR] country code not found")); + #endif #endif - if(ret) DEBUG_WM(DEBUG_VERBOSE,"esp_wifi_set_country: " + _wificountry); - else DEBUG_WM(DEBUG_ERROR,"[ERROR] esp_wifi_set_country failed"); + #ifdef WM_DEBUG_LEVEL + if(ret) DEBUG_WM(DEBUG_VERBOSE,F("[OK] esp_wifi_set_country: "),_wificountry); + else DEBUG_WM(DEBUG_ERROR,F("[ERROR] esp_wifi_set_country failed")); + #endif return ret; } @@ -2772,7 +3514,7 @@ bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { return ret; #elif defined(ESP32) if(persistent && esp32persistent) WiFi.persistent(true); - ret = WiFi.mode(m); // @todo persistent check persistant mode , NI + ret = WiFi.mode(m); // @todo persistent check persistant mode, was eventually added to esp lib, but have to add version checking probably if(persistent && esp32persistent) WiFi.persistent(false); return ret; #endif @@ -2786,14 +3528,18 @@ 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 + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi station disconnect")); + #endif + ETS_UART_INTR_DISABLE(); // @todo possibly not needed ret = wifi_station_disconnect(); ETS_UART_INTR_ENABLE(); return ret; } #elif defined(ESP32) - DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi station disconnect")); + #endif return WiFi.disconnect(); // not persistent atm #endif return false; @@ -2801,7 +3547,9 @@ 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 WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi_enableSTA"),(String) enable? "enable" : "disable"); + #endif #ifdef ESP8266 WiFiMode_t newMode; WiFiMode_t currentMode = WiFi.getMode(); @@ -2811,7 +3559,9 @@ bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { if((isEnabled != enable) || persistent) { if(enable) { + #ifdef WM_DEBUG_LEVEL if(persistent) DEBUG_WM(DEBUG_DEV,F("enableSTA PERSISTENT ON")); + #endif return WiFi_Mode(newMode,persistent); } else { @@ -2828,11 +3578,16 @@ bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { return ret; #endif } + bool WiFiManager::WiFi_enableSTA(bool enable) { return WiFi_enableSTA(enable,false); } bool WiFiManager::WiFi_eraseConfig() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi_eraseConfig")); + #endif + #ifdef ESP8266 #ifndef WM_FIXERASECONFIG return ESP.eraseConfig(); @@ -2850,10 +3605,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 ! WiFi.persistent(true); - ret = WiFi.disconnect(true,true); + ret = WiFi.disconnect(true,true); // disconnect(bool wifioff, bool eraseap) + delay(500); WiFi.persistent(false); return ret; #endif @@ -2926,25 +3683,48 @@ String WiFiManager::WiFi_psk(bool persistent) const { } #ifdef ESP32 -void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ + #ifdef WM_ARDUINOEVENTS + void WiFiManager::WiFiEvent(WiFiEvent_t event,arduino_event_info_t info){ + #else + void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ + #define wifi_sta_disconnected disconnected + #define ARDUINO_EVENT_WIFI_STA_DISCONNECTED SYSTEM_EVENT_STA_DISCONNECTED + #define ARDUINO_EVENT_WIFI_SCAN_DONE SYSTEM_EVENT_SCAN_DONE + #endif if(!_hasBegun){ - // DEBUG_WM(DEBUG_VERBOSE,"[ERROR] WiFiEvent, not ready"); - Serial.println("[ERROR] wm not ready"); + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_VERBOSE,"[ERROR] WiFiEvent, not ready"); + #endif + // Serial.println(F("\n[EVENT] WiFiEvent logging (wm debug not available)")); + // Serial.print(F("[EVENT] ID: ")); + // Serial.println(event); return; } + #ifdef WM_DEBUG_LEVEL // 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){ + #endif + if(event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: "),info.wifi_sta_disconnected.reason); + #endif + if(info.wifi_sta_disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.wifi_sta_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 WM_DEBUG_LEVEL + if(info.wifi_sta_disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: NO_AP_FOUND")); + if(info.wifi_sta_disconnected.reason == WIFI_REASON_ASSOC_FAIL){ + if(_aggresiveReconn) _connectRetries+=4; + DEBUG_WM(DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: AUTH FAIL")); + } + #endif #ifdef esp32autoreconnect - DEBUG_WM(DEBUG_VERBOSE,"[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting")); + #endif WiFi.reconnect(); #endif } - else if(event == SYSTEM_EVENT_SCAN_DONE){ + else if(event == ARDUINO_EVENT_WIFI_SCAN_DONE){ uint16_t scans = WiFi.scanComplete(); WiFi_scanComplete(scans); } @@ -2957,11 +3737,157 @@ void WiFiManager::WiFi_autoReconnect(){ #elif defined(ESP32) // if(_wifiAutoReconnect){ // @todo move to seperate method, used for event listener now - DEBUG_WM(DEBUG_VERBOSE,"ESP32 event handler enabled"); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("ESP32 event handler enabled")); + #endif using namespace std::placeholders; - wm_event_id = WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); + if(wm_event_id == 0) wm_event_id = WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); // } #endif } +// Called when /update is requested +void WiFiManager::handleUpdate() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- Handle update")); + #endif + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + String page = getHTTPHead(_title); // @token options + String str = FPSTR(HTTP_ROOT_MAIN); + str.replace(FPSTR(T_t), _title); + str.replace(FPSTR(T_v), configPortalActive ? _apName : (getWiFiHostname() + " - " + WiFi.localIP().toString())); // use ip if ap is not active for heading + page += str; + + page += FPSTR(HTTP_UPDATE); + page += FPSTR(HTTP_END); + + HTTPSend(page); + +} + +// upload via /u POST +void WiFiManager::handleUpdating(){ + // @todo + // cannot upload files in captive portal, file select is not allowed, show message with link or hide + // cannot upload if softreset after upload, maybe check for hard reset at least for dev, ERROR[11]: Invalid bootstrapping state, reset ESP8266 before updating + // add upload status to webpage somehow + // abort upload if error detected ? + // [x] supress cp timeout on upload, so it doesnt keep uploading? + // add progress handler for debugging + // combine route handlers into one callback and use argument or post checking instead of mutiple functions maybe, if POST process else server upload page? + // [x] add upload checking, do we need too check file? + // convert output to debugger if not moving to example + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + bool error = false; + unsigned long _configPortalTimeoutSAV = _configPortalTimeout; // store cp timeout + _configPortalTimeout = 0; // disable timeout + + // handler for the file upload, get's the sketch bytes, and writes + // them through the Update object + HTTPUpload& upload = server->upload(); + + // UPLOAD START + if (upload.status == UPLOAD_FILE_START) { + if(_debug) Serial.setDebugOutput(true); + uint32_t maxSketchSpace; + + // Use new callback for before OTA update + if (_preotaupdatecallback != NULL) { + _preotaupdatecallback(); // @CALLBACK + } + #ifdef ESP8266 + WiFiUDP::stopAll(); + maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; + #elif defined(ESP32) + // Think we do not need to stop WiFIUDP because we haven't started a listener + // maxSketchSpace = (ESP.getFlashChipSize() - 0x1000) & 0xFFFFF000; + // #define UPDATE_SIZE_UNKNOWN 0xFFFFFFFF // include update.h + maxSketchSpace = UPDATE_SIZE_UNKNOWN; + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,"Update file: ", upload.filename.c_str()); + #endif + + // Update.onProgress(THandlerFunction_Progress fn); + // Update.onProgress([](unsigned int progress, unsigned int total) { + // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + // }); + + if (!Update.begin(maxSketchSpace)) { // start with max available size + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] OTA Update ERROR"), Update.getError()); + #endif + error = true; + Update.end(); // Not sure the best way to abort, I think client will keep sending.. + } + } + // UPLOAD WRITE + else if (upload.status == UPLOAD_FILE_WRITE) { + // Serial.print("."); + if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] OTA Update WRITE ERROR"), Update.getError()); + //Update.printError(Serial); // write failure + #endif + error = true; + } + } + // UPLOAD FILE END + else if (upload.status == UPLOAD_FILE_END) { + if (Update.end(true)) { // true to set the size to the current progress + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("\n\n[OTA] OTA FILE END bytes: "), upload.totalSize); + // Serial.printf("Updated: %u bytes\r\nRebooting...\r\n", upload.totalSize); + #endif + } + else { + Update.printError(Serial); + error = true; + } + } + // UPLOAD ABORT + else if (upload.status == UPLOAD_FILE_ABORTED) { + Update.end(); + DEBUG_WM(F("[OTA] Update was aborted")); + error = true; + } + if(error) _configPortalTimeout = _configPortalTimeoutSAV; + delay(0); +} + +// upload and ota done, show status +void WiFiManager::handleUpdateDone() { + DEBUG_WM(DEBUG_VERBOSE, F("<- Handle update done")); + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + + String page = getHTTPHead(FPSTR(S_options)); // @token options + String str = FPSTR(HTTP_ROOT_MAIN); + str.replace(FPSTR(T_t),_title); + str.replace(FPSTR(T_v), configPortalActive ? _apName : WiFi.localIP().toString()); // use ip if ap is not active for heading + page += str; + + if (Update.hasError()) { + page += FPSTR(HTTP_UPDATE_FAIL); + #ifdef ESP32 + page += "OTA Error: " + (String)Update.errorString(); + #else + page += "OTA Error: " + (String)Update.getError(); + #endif + DEBUG_WM(F("[OTA] update failed")); + } + else { + page += FPSTR(HTTP_UPDATE_SUCCESS); + DEBUG_WM(F("[OTA] update ok")); + } + page += FPSTR(HTTP_END); + + HTTPSend(page); + + delay(1000); // send page + if (!Update.hasError()) { + ESP.restart(); + } +} + #endif diff --git a/lib/WiFiManager-2.0.3-alpha/WiFiManager.h b/lib/WiFiManager-2.0.3-alpha/WiFiManager.h index 0834390..4c057ee 100644 --- a/lib/WiFiManager-2.0.3-alpha/WiFiManager.h +++ b/lib/WiFiManager-2.0.3-alpha/WiFiManager.h @@ -32,7 +32,15 @@ #ifdef ARDUINO_ESP8266_RELEASE_2_3_0 #warning "ARDUINO_ESP8266_RELEASE_2_3_0, some WM features disabled" +// @todo check failing on platform = espressif8266@1.7.3 #define WM_NOASYNC // esp8266 no async scan wifi +#define WM_NOCOUNTRY // esp8266 no country +#define WM_NOAUTH // no httpauth +#define WM_NOSOFTAPSSID // no softapssid() @todo shim +#endif + +#ifdef ARDUINO_ESP32S3_DEV +#define WM_NOTEMP #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. @@ -42,6 +50,33 @@ #define WM_WEBSERVERSHIM // use webserver shim lib +#define WM_G(string_literal) (String(FPSTR(string_literal)).c_str()) + +#define WM_STRING2(x) #x +#define WM_STRING(x) STRING2(x) + +// #include +#ifdef ESP_IDF_VERSION + // #pragma message "ESP_IDF_VERSION_MAJOR = " WM_STRING(ESP_IDF_VERSION_MAJOR) + // #pragma message "ESP_IDF_VERSION_MINOR = " WM_STRING(ESP_IDF_VERSION_MINOR) + // #pragma message "ESP_IDF_VERSION_PATCH = " WM_STRING(ESP_IDF_VERSION_PATCH) + #define VER_IDF_STR WM_STRING(ESP_IDF_VERSION_MAJOR) "." WM_STRING(ESP_IDF_VERSION_MINOR) "." WM_STRING(ESP_IDF_VERSION_PATCH) +#endif + +// #include "esp_arduino_version.h" +#ifdef ESP_ARDUINO_VERSION + // #pragma message "ESP_ARDUINO_VERSION_MAJOR = " WM_STRING(ESP_ARDUINO_VERSION_MAJOR) + // #pragma message "ESP_ARDUINO_VERSION_MINOR = " WM_STRING(ESP_ARDUINO_VERSION_MINOR) + // #pragma message "ESP_ARDUINO_VERSION_PATCH = " WM_STRING(ESP_ARDUINO_VERSION_PATCH) + #define VER_ARDUINO_STR WM_STRING(ESP_ARDUINO_VERSION_MAJOR) "." WM_STRING(ESP_ARDUINO_VERSION_MINOR) "." WM_STRING(ESP_ARDUINO_VERSION_PATCH) +#else + // #include + // #pragma message "ESP_ARDUINO_VERSION_GIT = " WM_STRING(ARDUINO_ESP32_GIT_VER)// 0x46d5afb1 + // #pragma message "ESP_ARDUINO_VERSION_DESC = " WM_STRING(ARDUINO_ESP32_GIT_DESC) // 1.0.6 + #define VER_ARDUINO_STR "Unknown" + // #pragma message "ESP_ARDUINO_VERSION_REL = " WM_STRING(ARDUINO_ESP32_RELEASE) //"1_0_6" +#endif + #ifdef ESP8266 extern "C" { @@ -54,13 +89,14 @@ #include #endif - #define WIFI_getChipId() ESP.getChipId() + #define WIFI_getChipId() ESP.getChipId() #define WM_WIFIOPEN ENC_TYPE_NONE #elif defined(ESP32) #include #include + #include #define WIFI_getChipId() (uint32_t)ESP.getEfuseMac() #define WM_WIFIOPEN WIFI_AUTH_OPEN @@ -102,6 +138,7 @@ #define WFM_LABEL_BEFORE 1 #define WFM_LABEL_AFTER 2 #define WFM_NO_LABEL 0 +#define WFM_LABEL_DEFAULT 1 class WiFiManagerParameter { public: @@ -118,13 +155,13 @@ class WiFiManagerParameter { ~WiFiManagerParameter(); // WiFiManagerParameter& operator=(const WiFiManagerParameter& rhs); - const char *getID(); - const char *getValue(); - const char *getLabel(); - const char *getPlaceholder(); // @deprecated, use getLabel - int getValueLength(); - int getLabelPlacement(); - const char *getCustomHTML(); + const char *getID() const; + const char *getValue() const; + const char *getLabel() const; + const char *getPlaceholder() const; // @deprecated, use getLabel + int getValueLength() const; + int getLabelPlacement() const; + virtual const char *getCustomHTML() const; void setValue(const char *defaultValue, int length); protected: @@ -137,6 +174,7 @@ class WiFiManagerParameter { char *_value; int _length; int _labelPlacement; + protected: const char *_customHTML; friend class WiFiManager; }; @@ -145,7 +183,7 @@ class WiFiManagerParameter { class WiFiManager { public: - WiFiManager(Stream& consolePort); + WiFiManager(Print& consolePort); WiFiManager(); ~WiFiManager(); void WiFiManagerInit(); @@ -210,12 +248,17 @@ class WiFiManager //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 + //called when saving params-in-wifi or params before anything else happens (eg wifi) void setPreSaveConfigCallback( std::function func ); + //called when saving params before anything else happens + void setPreSaveParamsCallback( std::function func ); + + //called when saving either params-in-wifi or params page + void setSaveParamsCallback( std::function func ); + + //called just before doing OTA update + void setPreOtaUpdateCallback( 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 @@ -225,13 +268,20 @@ class WiFiManager //sets timeout for which to attempt connecting, useful if you get a lot of failed connects void setConnectTimeout(unsigned long seconds); + + // sets number of retries for autoconnect, force retry after wait failure exit + void setConnectRetries(uint8_t numRetries); // default 1 //sets timeout for which to attempt connecting on saves, useful if there are bugs in esp waitforconnectloop void setSaveConnectTimeout(unsigned long seconds); + // lets you disable automatically connecting after save from webportal + void setSaveConnect(bool connect = true); + // toggle debug output void setDebugOutput(boolean debug); - + void setDebugOutput(boolean debug, String prefix); // log line prefix, default "*wm:" + //set min quality percentage to include in scan, defaults to 8% if not specified void setMinimumSignalQuality(int quality = 8); @@ -252,9 +302,12 @@ class WiFiManager // setConfigPortalTimeout is ignored in this mode, user is responsible for closing configportal void setConfigPortalBlocking(boolean shouldBlock); + //add custom html at inside for all pages + void setCustomHeadElement(const char* html); + //if this is set, customise style - void setCustomHeadElement(const char* element); - + void setCustomMenuHTML(const char* html); + //if this is true, remove duplicated Access Points - defaut true void setRemoveDuplicateAPs(boolean removeDuplicates); @@ -287,13 +340,20 @@ class WiFiManager // if true (default) then start the config portal from autoConnect if connection failed void setEnableConfigPortal(boolean enable); - + + // if true (default) then stop the config portal from autoConnect when wifi is saved + void setDisableConfigPortal(boolean enable); + // set a custom hostname, sets sta and ap dhcp client id for esp32, and sta for esp8266 bool setHostname(const char * hostname); + bool setHostname(String hostname); // show erase wifi onfig button on info page, true void setShowInfoErase(boolean enabled); - + + // show OTA upload button on info page + void setShowInfoUpdate(boolean enabled); + // set ap channel void setWiFiAPChannel(int32_t channel); @@ -308,6 +368,9 @@ class WiFiManager void setMenu(std::vector& menu); void setMenu(const char* menu[], uint8_t size); + // set the webapp title, default WiFiManager + void setTitle(String title); + // add params to its own menu page and remove from wifi, NOT TO BE COMBINED WITH setMenu! void setParamsPage(bool enable); @@ -316,6 +379,7 @@ class WiFiManager // get a status as string String getWLStatusString(uint8_t status); + String getWLStatusString(); // get wifi mode as string String getModeString(uint8_t mode); @@ -323,11 +387,11 @@ class WiFiManager // check if the module has a saved ap to connect to bool getWiFiIsSaved(); - // helper to get saved ssid, if persistent get stored, else get current if connected - String getWiFiPass(bool persistent = false); + // helper to get saved password, if persistent get stored, else get current if connected + String getWiFiPass(bool persistent = true); - // helper to get saved password, if persistent get stored, else get current if connected - String getWiFiSSID(bool persistent = false); + // helper to get saved ssid, if persistent get stored, else get current if connected + String getWiFiSSID(bool persistent = true); // debug output the softap config void debugSoftAPConfig(); @@ -336,20 +400,36 @@ class WiFiManager void debugPlatformInfo(); // helper for html - String htmlEntities(String str); + String htmlEntities(String str, bool whitespace = false); // set the country code for wifi settings, CN void setCountry(String cc); - // set body class (invert), may be used for hacking in alt classes in the future + // set body class (invert), may be used for hacking in alt classes void setClass(String str); + // set dark mode via invert class + void setDarkMode(bool enable); + // get default ap esp uses , esp_chipid etc String getDefaultAPName(); // set port of webserver, 80 void setHttpPort(uint16_t port); + // check if config portal is active (true) + bool getConfigPortalActive(); + + // check if web portal is active (true) + bool getWebPortalActive(); + + // to preload autoconnect for test fixtures or other uses that skip esp sta config + bool preloadWiFi(String ssid, String pass); + + // get hostname helper + String getWiFiHostname(); + + std::unique_ptr dnsServer; #if defined(ESP32) && defined(WM_WEBSERVERSHIM) @@ -361,9 +441,11 @@ class WiFiManager std::unique_ptr server; private: + // vars std::vector _menuIds; std::vector _menuIdsParams = {"wifi","param","info","exit"}; - std::vector _menuIdsDefault = {"wifi","info","exit"}; + std::vector _menuIdsUpdate = {"wifi","param","info","update","exit"}; + std::vector _menuIdsDefault = {"wifi","info","exit","sep","update"}; // ip configs @todo struct ? IPAddress _ap_static_ip; @@ -374,38 +456,48 @@ class WiFiManager IPAddress _sta_static_sn; IPAddress _sta_static_dns; + unsigned long _configPortalStart = 0; // ms config portal start time (updated for timeouts) + unsigned long _webPortalAccessed = 0; // ms last web access time + uint8_t _lastconxresult = WL_IDLE_STATUS; // store last result when doing connect operations + int _numNetworks = 0; // init index for numnetworks wifiscans + unsigned long _lastscan = 0; // ms for timing wifi scans + unsigned long _startscan = 0; // ms for timing wifi scans + unsigned long _startconn = 0; // ms for timing wifi connects + // defaults const byte DNS_PORT = 53; - const byte HTTP_PORT = 80; String _apName = "no-net"; String _apPassword = ""; - String _ssid = ""; - String _pass = ""; - + String _ssid = ""; // var temp ssid + String _pass = ""; // var temp psk + String _defaultssid = ""; // preload ssid + String _defaultpass = ""; // preload pass + // options flags unsigned long _configPortalTimeout = 0; // ms close config portal loop if set (depending on _cp/webClientCheck options) unsigned long _connectTimeout = 0; // ms stop trying to connect to ap if set 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_STA; // Default user mode String _wifissidprefix = FPSTR(S_ssidpre); // auto apname prefix prefix+chipid - uint8_t _lastconxresult = WL_IDLE_STATUS; // store last result when doing connect operations - int _numNetworks = 0; // init index for numnetworks wifiscans - 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 = false; // disconnect before connect in connectwifi, increases stability on connects - + bool _connectonsave = true; // connect to wifi when saving creds 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 same wifi sta channel when starting ap - int32_t _apChannel = 0; // channel to use for ap + int32_t _apChannel = 0; // default channel to use for ap, 0 for auto bool _apHidden = false; // store softap hidden value - uint16_t _httpPort = 80; // port for webserver + uint16_t _httpPort = 80; // port for webserver + // uint8_t _retryCount = 0; // counter for retries, probably not needed if synchronous + uint8_t _connectRetries = 1; // number of sta connect retries, force reconnect, wait loop (connectimeout) does not always work and first disconnect bails + bool _aggresiveReconn = true; // use an agrressive reconnect strategy, WILL delay conxs + // on some conn failure modes will add delays and many retries to work around esp and ap bugs, ie, anti de-auth protections + // https://github.com/tzapu/WiFiManager/issues/1067 + bool _allowExit = true; // allow exit in nonblocking, else user exit/abort calls will be ignored including cptimeout #ifdef ESP32 - wifi_event_id_t wm_event_id; + wifi_event_id_t wm_event_id = 0; static uint8_t _lastconxresulttmp; // tmp var for esp32 callback #endif @@ -415,8 +507,8 @@ class WiFiManager // parameter options int _minimumQuality = -1; // filter wifiscan ap by this rssi - int _staShowStaticFields = 0; // ternary 1=always show static ip fields, 0=only if set, -1=never(cannot change ips via web!) - int _staShowDns = 0; // ternary 1=always show dns, 0=only if set, -1=never(cannot change dns via web!) + int _staShowStaticFields = 0; // ternary 1=always show static ip fields, 0=only if set, -1=never(cannot change ips via web!) + int _staShowDns = 0; // ternary 1=always show dns, 0=only if set, -1=never(cannot change dns via web!) boolean _removeDuplicateAPs = true; // remove dup aps from wifiscan boolean _showPassword = false; // show or hide saved password on wifi form, might be a security issue! boolean _shouldBreakAfterConfig = false; // stop configportal on save failure @@ -429,16 +521,21 @@ class WiFiManager boolean _scanDispOptions = false; // show percentage in scans not icons boolean _paramsInWifi = true; // show custom parameters on wifi page boolean _showInfoErase = true; // info page erase button + boolean _showInfoUpdate = true; // info page update button boolean _showBack = false; // show back button - boolean _enableConfigPortal = true; // use config portal if autoconnect failed - const char * _hostname = ""; // hostname for esp8266 for dhcp, and or MDNS + boolean _enableConfigPortal = true; // FOR autoconnect - start config portal if autoconnect failed + boolean _disableConfigPortal = true; // FOR autoconnect - stop config portal if cp wifi save + String _hostname = ""; // hostname for esp8266 for dhcp, and or MDNS - const char* _customHeadElement = ""; // store custom head element html from user + const char* _customHeadElement = ""; // store custom head element html from user isnide + const char* _customMenuHTML = ""; // store custom head element html from user inside <> String _bodyClass = ""; // class to add to body + String _title = FPSTR(S_brand); // app title - default WiFiManager // internal options // wifiscan notes + // currently disabled due to issues with caching, sometimes first scan is empty esp32 wifi not init yet race, or portals hit server nonstop flood // The following are background wifi scanning optimizations // experimental to make scans faster, preload scans after starting cp, and visiting home page, so when you click wifi its already has your list // ideally we would add async and xhr here but I am holding off on js requirements atm @@ -446,7 +543,8 @@ class WiFiManager // cache time helps throttle this // async enables asyncronous scans, so they do not block anything // the refresh button bypasses cache - boolean _preloadwifiscan = true; // preload wifiscan if true + // no aps found is problematic as scans are always going to want to run, leading to page load delays + boolean _preloadwifiscan = false; // preload wifiscan if true boolean _asyncScan = false; // perform wifi network scan async unsigned int _scancachetime = 30000; // ms cache time for background scans @@ -470,17 +568,20 @@ class WiFiManager #endif bool startAP(); + void setupDNSD(); + void setupHTTPServer(); - uint8_t connectWifi(String ssid, String pass); + uint8_t connectWifi(String ssid, String pass, bool connect = true); bool setSTAConfig(); bool wifiConnectDefault(); - bool wifiConnectNew(String ssid, String pass); + bool wifiConnectNew(String ssid, String pass,bool connect = true); uint8_t waitForConnectResult(); - uint8_t waitForConnectResult(uint16_t timeout); + uint8_t waitForConnectResult(uint32_t timeout); void updateConxResult(uint8_t status); // webserver handlers + void HTTPSend(String content); void handleRoot(); void handleWifi(boolean scan); void handleWifiSave(); @@ -501,6 +602,11 @@ class WiFiManager boolean configPortalHasTimeout(); uint8_t processConfigPortal(); void stopCaptivePortal(); + // OTA Update handler + void handleUpdate(); + void handleUpdating(); + void handleUpdateDone(); + // wifi platform abstractions bool WiFi_Mode(WiFiMode_t m); @@ -512,8 +618,8 @@ class WiFiManager uint8_t WiFi_softap_num_stations(); bool WiFi_hasAutoConnect(); void WiFi_autoReconnect(); - String WiFi_SSID(bool persistent = false) const; - String WiFi_psk(bool persistent = false) const; + String WiFi_SSID(bool persistent = true) const; + String WiFi_psk(bool persistent = true) const; bool WiFi_scanNetworks(); bool WiFi_scanNetworks(bool force,bool async); bool WiFi_scanNetworks(unsigned int cachetime,bool async); @@ -522,7 +628,33 @@ class WiFiManager bool WiFiSetCountry(); #ifdef ESP32 - void WiFiEvent(WiFiEvent_t event, system_event_info_t info); + + // check for arduino or system event system, handle esp32 arduino v2 and IDF + #if defined(ESP_ARDUINO_VERSION) && defined(ESP_ARDUINO_VERSION_VAL) + + #define WM_ARDUINOVERCHECK ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(2, 0, 0) + + #ifdef WM_ARDUINOVERCHECK + #define WM_ARDUINOEVENTS + #else + #define WM_NOSOFTAPSSID + #define WM_NOCOUNTRY + #endif + + #else + #define WM_NOCOUNTRY + #endif + + #ifdef WM_NOCOUNTRY + #warning "ESP32 set country unavailable" + #endif + + + #ifdef WM_ARDUINOEVENTS + void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info); + #else + void WiFiEvent(WiFiEvent_t event, system_event_info_t info); + #endif #endif // output helpers @@ -541,15 +673,15 @@ class WiFiManager String getInfoData(String id); // flags - boolean connect; - boolean abort; + boolean connect = false; + boolean abort = false; boolean reset = false; boolean configPortalActive = false; boolean webPortalActive = false; boolean portalTimeoutResult = false; boolean portalAbortResult = false; boolean storeSTAmode = true; // option store persistent STA mode in connectwifi - int timer = 0; + int timer = 0; // timer for debug throttle for numclients, and portal timeout messages // WiFiManagerParameter int _paramsCount = 0; @@ -566,20 +698,34 @@ class WiFiManager } wm_debuglevel_t; boolean _debug = true; - + String _debugPrefix = FPSTR(S_debugPrefix); + + wm_debuglevel_t debugLvlShow = DEBUG_VERBOSE; // at which level start showing [n] level tags + // build debuglevel support // @todo use DEBUG_ESP_x? + + // Set default debug level + #ifndef WM_DEBUG_LEVEL + #define WM_DEBUG_LEVEL DEBUG_VERBOSE // development default, not release + #endif + + // override debug level OFF + #ifdef WM_NODEBUG + #undef WM_DEBUG_LEVEL + #endif + #ifdef WM_DEBUG_LEVEL uint8_t _debugLevel = (uint8_t)WM_DEBUG_LEVEL; #else - uint8_t _debugLevel = DEBUG_DEV; // default debug level + uint8_t _debugLevel = DEBUG_VERBOSE; // default debug level #endif // @todo use DEBUG_ESP_PORT ? #ifdef WM_DEBUG_PORT - Stream& _debugPort = WM_DEBUG_PORT; + Print& _debugPort = WM_DEBUG_PORT; #else - Stream& _debugPort = Serial; // debug output stream ref + Print& _debugPort = Serial; // debug output stream ref #endif template @@ -597,9 +743,11 @@ class WiFiManager std::function _apcallback; std::function _webservercallback; std::function _savewificallback; - std::function _presavecallback; + std::function _presavewificallback; + std::function _presaveparamscallback; std::function _saveparamscallback; std::function _resetcallback; + std::function _preotaupdatecallback; template auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { @@ -609,8 +757,9 @@ class WiFiManager // DEBUG_WM("NO fromString METHOD ON IPAddress, you need ESP8266 core 2.1.0 or newer for Custom IP configuration to work."); return false; } + }; #endif -#endif \ No newline at end of file +#endif diff --git a/lib/WiFiManager-2.0.3-alpha/strings_en.h b/lib/WiFiManager-2.0.3-alpha/strings_en.h index d56d0b1..386571d 100644 --- a/lib/WiFiManager-2.0.3-alpha/strings_en.h +++ b/lib/WiFiManager-2.0.3-alpha/strings_en.h @@ -3,7 +3,7 @@ * engligh strings for * WiFiManager, a library for the ESP8266/Arduino platform * for configuration of WiFi credentials using a Captive Portal - * + * * @author Creator tzapu * @author tablatronix * @version 0.0.0 @@ -13,20 +13,32 @@ #ifndef _WM_STRINGS_H_ #define _WM_STRINGS_H_ + #ifndef WIFI_MANAGER_OVERRIDE_STRINGS -// !!! THIS DOES NOT WORK, you cannot define in a sketch, if anyone one knows how to order includes to be able to do this help! +// !!! ABOVE WILL NOT WORK if you define in your sketch, must be build flag, if anyone one knows how to order includes to be able to do this it would be neat.. I have seen it done.. + +const char WM_VERSION_STR[] PROGMEM = "v2.0.12-beta"; + +const char HTTP_HEAD_START[] PROGMEM = "" +"" +"" +"" +"" +"{v}"; -const char HTTP_HEAD_START[] PROGMEM = "{v}"; const char HTTP_SCRIPT[] PROGMEM = ""; +"if(p)document.getElementById('p').focus();};" +"function f() {var x = document.getElementById('p');x.type==='password'?x.type='text':x.type='password';}" +""; // @todo add button states, disable on click , show ack , spinner etc -const char HTTP_HEAD_END[] PROGMEM = "
"; +const char HTTP_HEAD_END[] PROGMEM = "
"; // {c} = _bodyclass // 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 HTTP_ROOT_MAIN[] PROGMEM = "

{t}

{v}

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

\n", // MENU_WIFI "

\n", // MENU_WIFINOSCAN @@ -36,34 +48,36 @@ const char * const HTTP_PORTAL_MENU[] PROGMEM = { "

\n",// MENU_RESTART "

\n", // MENU_EXIT "

\n", // MENU_ERASE +"

\n",// MENU_UPDATE "

" // MENU_SEP }; // const char HTTP_PORTAL_OPTIONS[] PROGMEM = strcat(HTTP_PORTAL_MENU[0] , HTTP_PORTAL_MENU[3] , HTTP_PORTAL_MENU[7]); const char HTTP_PORTAL_OPTIONS[] PROGMEM = ""; const char HTTP_ITEM_QI[] PROGMEM = ""; // rssi icons -const char HTTP_ITEM_QP[] PROGMEM = "
{r}%
"; // rssi percentage -const char HTTP_ITEM[] PROGMEM = "
{v}{qi}{qp}
"; // {q} = HTTP_ITEM_QI, {r} = HTTP_ITEM_QP +const char HTTP_ITEM_QP[] PROGMEM = "
{r}%
"; // rssi percentage {h} = hidden showperc pref +const char HTTP_ITEM[] PROGMEM = "
{v}{qi}{qp}
"; // {q} = HTTP_ITEM_QI, {r} = HTTP_ITEM_QP // const char HTTP_ITEM[] PROGMEM = "
{v} {R} {r}% {q} {e}
"; // test all tokens const char HTTP_FORM_START[] PROGMEM = "
"; -const char HTTP_FORM_WIFI[] PROGMEM = "
"; +const char HTTP_FORM_WIFI[] PROGMEM = "
Show Password"; const char HTTP_FORM_WIFI_END[] PROGMEM = ""; 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 = "
\n"; // do not remove newline! 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
"; const char HTTP_PARAMSAVED[] PROGMEM = "
Saved
"; const char HTTP_END[] PROGMEM = "
"; const char HTTP_ERASEBTN[] PROGMEM = "
"; +const char HTTP_UPDATEBTN[] PROGMEM = "
"; const char HTTP_BACKBTN[] PROGMEM = "

"; const char HTTP_STATUS_ON[] PROGMEM = "
Connected to {v}
with IP {i}
"; -const char HTTP_STATUS_OFF[] PROGMEM = "
Not Connected to {v}{r}
"; +const char HTTP_STATUS_OFF[] PROGMEM = "
Not Connected to {v}{r}
"; // {c=class} {v=ssid} {r=status_off} const char HTTP_STATUS_OFFPW[] PROGMEM = "
Authentication Failure"; // STATION_WRONG_PASSWORD, no eps32 const char HTTP_STATUS_OFFNOAP[] PROGMEM = "
AP not found"; // WL_NO_SSID_AVAIL const char HTTP_STATUS_OFFFAIL[] PROGMEM = "
Could not Connect"; // WL_CONNECT_FAILED @@ -71,8 +85,8 @@ const char HTTP_STATUS_NONE[] PROGMEM = "
No AP set
"; const char HTTP_BR[] PROGMEM = "
"; const char HTTP_STYLE[] PROGMEM = ""; +#ifndef WM_NOHELP const char HTTP_HELP[] PROGMEM = "

Available Pages


" "" @@ -113,19 +130,28 @@ const char HTTP_HELP[] PROGMEM = "" "" "" + "" + "" "" "" - "" + "" "" - "" + "" "" - "" + "" "" "
Parameter page
/infoInformation page
/uOTA Update
/closeClose the captiveportal popup,configportal will remain active
/exit
/exitExit Config Portal, configportal will close
/restart
/restartReboot the device
/erase
/eraseErase WiFi configuration and reboot Device. Device will not reconnect to a network until new WiFi configuration data is entered.
" - "

More information about WiFiManager at https://github.com/tzapu/WiFiManager."; + "

Github https://github.com/tzapu/WiFiManager."; +#else +const char HTTP_HELP[] PROGMEM = ""; +#endif + +const char HTTP_UPDATE[] PROGMEM = "Upload New Firmware

* May not function inside captive portal, Open in browser http://192.168.4.1"; +const char HTTP_UPDATE_FAIL[] PROGMEM = "
Update Failed!
Reboot device and try again
"; +const char HTTP_UPDATE_SUCCESS[] PROGMEM = "
Update Successful.
Device Rebooting now...
"; #ifdef WM_JSTEST -const char HTTP_JS[] PROGMEM = +const char HTTP_JS[] PROGMEM = "