diff --git a/README.md b/README.md index 34f19cb..9405479 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,11 @@ # WiFiManager +## DEVELOPMENT BRANCH + ESP8266 WiFi Connection manager with fallback web configuration portal +:warning: This Documentation is out of date for this branch, see notes below + [![Build Status](https://travis-ci.org/tzapu/WiFiManager.svg?branch=development)](https://travis-ci.org/tzapu/WiFiManager) ![ESP8266](https://img.shields.io/badge/ESP-8266-000000.svg?longCache=true&style=flat&colorA=CC101F) @@ -11,11 +15,11 @@ The configuration portal is of the captive variety, so on various devices it wil First attempt at a library. Lots more changes and fixes to do. Contributions are welcome. -**This works with the ESP8266 Arduino platform with a recent stable release(2.0.0 or newer)** +**This works with the ESP8266 Arduino platform** [https://github.com/esp8266/Arduino](https://github.com/esp8266/Arduino) -**This works with the ESP32 Arduino platform with staging** +**This works with the ESP32 Arduino platform** [https://github.com/espressif/arduino-esp32](https://github.com/espressif/arduino-esp32) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 993726e..51df76c 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -302,9 +302,9 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { if((String)_hostname != ""){ #ifdef ESP8266 - DEBUG_WM(DEBUG_DEV,"hostname: STA",WiFi.hostname()); + DEBUG_WM(DEBUG_DEV,"hostname: STA: ",WiFi.hostname()); #elif defined(ESP32) - DEBUG_WM(DEBUG_DEV,"hostname: STA",WiFi.getHostname()); + DEBUG_WM(DEBUG_DEV,"hostname: STA: ",WiFi.getHostname()); #endif } @@ -326,16 +326,17 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { } bool WiFiManager::setupHostname(bool restart){ - DEBUG_WM(DEBUG_VERBOSE,"Setting hostname:",_hostname); if((String)_hostname == "") { - DEBUG_WM(DEBUG_VERBOSE,"No Hostname to set"); + DEBUG_WM(DEBUG_DEV,"No Hostname to set"); return false; - } + } else DEBUG_WM(DEBUG_DEV,"setupHostname: ",_hostname); bool res = true; #ifdef ESP8266 + DEBUG_WM(DEBUG_VERBOSE,"Setting WiFi hostname"); res = WiFi.hostname(_hostname); - #ifdef ESP8266MDNS_H - DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname"); + // #ifdef ESP8266MDNS_H + #ifdef WM_MDNS + DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname, tcp 80"); if(MDNS.begin(_hostname)){ MDNS.addService("http", "tcp", 80); } @@ -344,8 +345,9 @@ bool WiFiManager::setupHostname(bool restart){ // @note hostname must be set after STA_START delay(200); // do not remove, give time for STA_START res = WiFi.setHostname(_hostname); - #ifdef ESP32MDNS_H - DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname"); + // #ifdef ESP32MDNS_H + #ifdef WM_MDNS + DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname, tcp 80"); if(MDNS.begin(_hostname)){ MDNS.addService("http", "tcp", 80); } @@ -354,7 +356,6 @@ bool WiFiManager::setupHostname(bool restart){ if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: set failed!")); - // in sta mode restart , not sure about softap if(restart && (WiFi.status() == WL_CONNECTED)){ DEBUG_WM(DEBUG_VERBOSE,F("reconnecting to set new hostname")); // WiFi.reconnect(); // This does not reset dhcp @@ -431,7 +432,7 @@ bool WiFiManager::startAP(){ DEBUG_WM(DEBUG_VERBOSE,"setting softAP Hostname:",_hostname); bool res = WiFi.softAPsetHostname(_hostname); if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: AP set failed!")); - DEBUG_WM(DEBUG_DEV,F("hostname: AP"),WiFi.softAPgetHostname()); + DEBUG_WM(DEBUG_DEV,F("hostname: AP: "),WiFi.softAPgetHostname()); } #endif @@ -635,6 +636,11 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo * @return {[type]} [description] */ 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; @@ -753,7 +759,7 @@ bool WiFiManager::shutdownConfigPortal(){ // clean up, flow is convoluted, and causes bugs uint8_t WiFiManager::connectWifi(String ssid, String pass) { DEBUG_WM(DEBUG_VERBOSE,F("Connecting as wifi client...")); - + uint8_t retry = 1; uint8_t connRes = (uint8_t)WL_NO_SSID_AVAIL; setSTAConfig(); @@ -764,6 +770,10 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { 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 + while(retry <= _connectRetries){ + if(_connectRetries > 1){ + DEBUG_WM(F("Connect Wifi, ATTEMPT #"),(String)retry+" of "+(String)_connectRetries); + } // if ssid argument provided connect to that if (ssid != "") { wifiConnectNew(ssid,pass); @@ -781,11 +791,13 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { connRes = waitForConnectResult(); } else { - DEBUG_WM(F("No wifi save required, skipping")); + DEBUG_WM(F("No wifi saved, skipping")); } } DEBUG_WM(DEBUG_VERBOSE,F("Connection result:"),getWLStatusString(connRes)); + retry++; +} // WPS enabled? https://github.com/esp8266/Arduino/pull/4889 #ifdef NO_EXTRA_4K_HEAP @@ -835,6 +847,8 @@ bool WiFiManager::wifiConnectDefault(){ DEBUG_WM(F("Connecting to SAVED AP:"),WiFi_SSID(true)); DEBUG_WM(DEBUG_DEV,F("Using Password:"),WiFi_psk(true)); ret = WiFi_enableSTA(true,storeSTAmode); + delay(500); // THIS DELAY ? + DEBUG_WM(DEBUG_DEV,"Mode after delay: "+getModeString(WiFi.getMode())); if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi enableSta failed"); ret = WiFi.begin(); if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed"); @@ -1027,6 +1041,7 @@ void WiFiManager::handleWifi(boolean scan) { } page += FPSTR(HTTP_FORM_END); page += FPSTR(HTTP_SCAN_LINK); + if(_showBack) page += FPSTR(HTTP_BACKBTN); reportStatus(page); page += FPSTR(HTTP_END); @@ -1053,6 +1068,7 @@ void WiFiManager::handleParam(){ page += getParamOut(); page += FPSTR(HTTP_FORM_END); + if(_showBack) page += FPSTR(HTTP_BACKBTN); reportStatus(page); page += FPSTR(HTTP_END); @@ -1347,7 +1363,7 @@ void WiFiManager::handleWiFiStatus(){ handleRequest(); String page; // String page = "{\"result\":true,\"count\":1}"; - #ifdef JSTEST + #ifdef WM_JSTEST page = FPSTR(HTTP_JS); #endif server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); @@ -1551,6 +1567,7 @@ void WiFiManager::handleInfo() { } page += F(""); if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); + if(_showBack) page += FPSTR(HTTP_BACKBTN); page += FPSTR(HTTP_HELP); page += FPSTR(HTTP_END); @@ -2050,6 +2067,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] @@ -2430,7 +2457,8 @@ void WiFiManager::setMenu(std::vector& menu){ /** * set params as sperate page not in wifi - * NOT COMPATIBLE WITH setMenu! @todo scan menuids and insert param after wifi or something + * NOT COMPATIBLE WITH setMenu! + * @todo scan menuids and insert param after wifi or something, same for ota * @param bool enable * @since $dev */ @@ -2546,12 +2574,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. @@ -2562,9 +2590,9 @@ 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 } @@ -2584,13 +2612,16 @@ 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; @@ -2606,7 +2637,9 @@ 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); + #if !defined(WM_NOCOUNTRY) + DEBUG_WM(F("country: "),(String)country.cc); + #endif DEBUG_WM(F("beacon_interval: "),(String)config.beacon_interval + "(ms)"); DEBUG_WM(FPSTR(D_HR)); } @@ -2624,7 +2657,6 @@ void WiFiManager::debugPlatformInfo(){ DEBUG_WM(F("system_get_boot_version():"),system_get_boot_version()); DEBUG_WM(F("getFreeHeap(): "),(String)ESP.getFreeHeap()); #elif defined(ESP32) - size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); DEBUG_WM("Free heap: ", ESP.getFreeHeap()); DEBUG_WM("ESP SDK version: ", ESP.getSdkVersion()); // esp_chip_info_t chipInfo; @@ -2737,7 +2769,7 @@ bool WiFiManager::WiFiSetCountry(){ else if(_wificountry == "CN") ret = esp_wifi_set_country(&WM_COUNTRY_CN) == ESP_OK; else DEBUG_WM(DEBUG_ERROR,"[ERROR] country code not found"); - #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); @@ -2778,14 +2810,14 @@ bool WiFiManager::WiFi_Disconnect() { #ifdef ESP8266 if((WiFi.getMode() & WIFI_STA) != 0) { bool ret; - DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); + DEBUG_WM(DEBUG_DEV,F("WiFi station disconnect")); ETS_UART_INTR_DISABLE(); // @todo probably not needed ret = wifi_station_disconnect(); ETS_UART_INTR_ENABLE(); return ret; } #elif defined(ESP32) - DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); + DEBUG_WM(DEBUG_DEV,F("WiFi station disconnect")); return WiFi.disconnect(); // not persistent atm #endif return false; @@ -2793,7 +2825,7 @@ bool WiFiManager::WiFi_Disconnect() { // toggle STA without persistent bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { - DEBUG_WM(DEBUG_DEV,F("WiFi station enable")); + DEBUG_WM(DEBUG_DEV,F("WiFi_enableSTA"),(String) enable? "enable" : "disable"); #ifdef ESP8266 WiFiMode_t newMode; WiFiMode_t currentMode = WiFi.getMode(); diff --git a/WiFiManager.h b/WiFiManager.h index 80f8466..1e70e24 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -22,14 +22,18 @@ #include -// #define WM_MDNS // also set MDNS with sethostname +// #define WM_MDNS // includes MDNS, also set MDNS with sethostname // #define WM_FIXERASECONFIG // use erase flash fix // #define WM_ERASE_NVS // esp32 erase(true) will erase NVS // #define WM_RTC // esp32 info page will include reset reasons +// #define WM_JSTEST // build flag for enabling js xhr tests +// #define WIFI_MANAGER_OVERRIDE_STRINGS // build flag for using own strings include + #ifdef ARDUINO_ESP8266_RELEASE_2_3_0 #warning "ARDUINO_ESP8266_RELEASE_2_3_0, some WM features disabled" #define WM_NOASYNC // esp8266 no async scan wifi +#define WM_NOCOUNTRY // esp8266 no country #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. @@ -68,7 +72,7 @@ #include #else #include - // Forthcoming official ? + // Forthcoming official ? probably never happening // https://github.com/esp8266/ESPWebServer #endif #endif @@ -86,7 +90,6 @@ #include #endif - #else #endif @@ -162,8 +165,10 @@ class WiFiManager //manually start the web portal, autoconnect does this automatically on connect failure void startWebPortal(); + //manually stop the web portal if started manually void stopWebPortal(); + // Run webserver processing, if setConfigPortalBlocking(false) boolean process(); @@ -173,34 +178,43 @@ class WiFiManager // erase wifi credentials void resetSettings(); + // reboot esp void reboot(); + // disconnect wifi, without persistent saving or erasing bool disconnect(); + // erase esp bool erase(); bool erase(bool opt); //adds a custom parameter, returns false on failure bool addParameter(WiFiManagerParameter *p); + //returns the list of Parameters WiFiManagerParameter** getParameters(); + // returns the Parameters Count int getParametersCount(); - // SET CALLBACKS //called after AP mode and config portal has started void setAPCallback( std::function func ); + //called after webserver has started void setWebServerCallback( std::function func ); + //called when settings reset have been triggered void setConfigResetCallback( std::function func ); + //called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) void setSaveConfigCallback( std::function func ); + //called when settings have been changed and connection was successful void setSaveParamsCallback( std::function func ); + //called when settings before have been changed and connection was successful void setPreSaveConfigCallback( std::function func ); @@ -213,61 +227,89 @@ 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); + // toggle debug output void setDebugOutput(boolean debug); + //set min quality percentage to include in scan, defaults to 8% if not specified void setMinimumSignalQuality(int quality = 8); + //sets a custom ip /gateway /subnet configuration void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + //sets config for a static IP void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + //sets config for a static IP with DNS void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns); + //if this is set, it will exit after config, even if connection is unsuccessful. void setBreakAfterConfig(boolean shouldBreak); + // if this is set, portal will be blocking and wait until save or exit, // is false user must manually `process()` to handle config portal, // setConfigPortalTimeout is ignored in this mode, user is responsible for closing configportal void setConfigPortalBlocking(boolean shouldBlock); + //if this is set, customise style void setCustomHeadElement(const char* element); + //if this is true, remove duplicated Access Points - defaut true void setRemoveDuplicateAPs(boolean removeDuplicates); + //setter for ESP wifi.persistent so we can remember it and restore user preference, as WIFi._persistent is protected void setRestorePersistent(boolean persistent); + //if true, always show static net inputs, IP, subnet, gateway, else only show if set via setSTAStaticIPConfig void setShowStaticFields(boolean alwaysShow); + //if true, always show static dns, esle only show if set via setSTAStaticIPConfig void setShowDnsFields(boolean alwaysShow); + // toggle showing the saved wifi password in wifi form, could be a security issue. void setShowPassword(boolean show); + //if false, disable captive portal redirection void setCaptivePortalEnable(boolean enabled); + //if false, timeout captive portal even if a STA client connected to softAP (false), suggest disabling if captiveportal is open void setAPClientCheck(boolean enabled); + //if true, reset timeout when webclient connects (true), suggest disabling if captiveportal is open void setWebPortalClientCheck(boolean enabled); + // if true, enable autoreconnecting void setWiFiAutoReconnect(boolean enabled); + // if true, wifiscan will show percentage instead of quality icons, until we have better templating void setScanDispPerc(boolean enabled); + // if true (default) then start the config portal from autoConnect if connection failed void setEnableConfigPortal(boolean enable); + // set a custom hostname, sets sta and ap dhcp client id for esp32, and sta for esp8266 bool setHostname(const char * hostname); + // show erase wifi onfig button on info page, true void setShowInfoErase(boolean enabled); + // set ap channel void setWiFiAPChannel(int32_t channel); + // set ap hidden void setWiFiAPHidden(bool hidden); // default false + // clean connect, always disconnect before connecting void setCleanConnect(bool enable); // default false - // set custom menu - // set custom menu items and order + // set custom menu items and order, vector or arr + // see _menutokens for ids void setMenu(std::vector& menu); void setMenu(const char* menu[], uint8_t size); @@ -276,30 +318,41 @@ class WiFiManager // get last connection result, includes autoconnect and wifisave uint8_t getLastConxResult(); + // get a status as string String getWLStatusString(uint8_t status); + + // get wifi mode as string String getModeString(uint8_t mode); + // 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 + // helper to get saved password, 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 + + // helper to get saved ssid, if persistent get stored, else get current if connected String getWiFiSSID(bool persistent = false); // debug output the softap config void debugSoftAPConfig(); + // debug output platform info and versioning void debugPlatformInfo(); + + // helper for html String htmlEntities(String str); - // set the country code for wifi settings + // set the country code for wifi settings, CN void setCountry(String cc); - // set body class (invert) + + // set body class (invert), may be used for hacking in alt classes in the future void setClass(String str); + + // get default ap esp uses , esp_chipid etc String getDefaultAPName(); - // set port of webserver + // set port of webserver, 80 void setHttpPort(uint16_t port); std::unique_ptr dnsServer; @@ -343,8 +396,8 @@ class WiFiManager 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; - int _numNetworks = 0; + 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. @@ -355,7 +408,9 @@ class WiFiManager bool _channelSync = false; // use same wifi sta channel when starting ap int32_t _apChannel = 0; // channel to use for ap 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 #ifdef ESP32 wifi_event_id_t wm_event_id; @@ -382,23 +437,34 @@ 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 _showBack = false; // show back button boolean _enableConfigPortal = true; // use config portal if autoconnect failed - const char * _hostname = ""; + const char * _hostname = ""; // hostname for esp8266 for dhcp, and or MDNS const char* _customHeadElement = ""; // store custom head element html from user String _bodyClass = ""; // class to add to body // internal options + + // wifiscan notes + // 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 + // might be slightly buggy since captive portals hammer the home page, @todo workaround this somehow. + // 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 - boolean _asyncScan = false; + boolean _asyncScan = false; // perform wifi network scan async unsigned int _scancachetime = 30000; // ms cache time for background scans + boolean _disableIpFields = false; // modify function of setShow_X_Fields(false), forces ip fields off instead of default show if set, eg. _staShowStaticFields=-1 String _wificountry = ""; // country code, @todo define in strings lang // wrapper functions for handling setting and unsetting persistent for now. bool esp32persistent = false; - bool _hasBegun = false; + bool _hasBegun = false; // flag wm loaded,unloaded void _begin(); void _end(); @@ -560,4 +626,4 @@ class WiFiManager #endif -#endif \ No newline at end of file +#endif diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino index d7611b1..032bd10 100644 --- a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -18,54 +18,6 @@ const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; unsigned long mtime = 0; -// OLED TEST , untested -// // #define MYOLED - -// #include -// #include -// #include -// #ifdef MYOLED - -// #define SCREEN_WIDTH 128 // OLED display width, in pixels -// #define SCREEN_HEIGHT 32 // OLED display height, in pixels - -// // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) -// #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) -// Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); - -// void init_oled(){ -// Wire.begin(SCL,SDA); // begin(sda, scl) SWAP! -// // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally -// if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 -// Serial.println(F("SSD1306 allocation failed")); -// } - -// display.clearDisplay(); -// display.setTextSize(1); // Normal 1:1 pixepl scale -// display.setTextColor(WHITE); // Draw white text -// display.setCursor(0,0); // Start at top-left corner -// display.display(); -// } - -// void print_oled(String str,uint8_t size){ -// display.clearDisplay(); -// display.setTextSize(size); -// display.setTextColor(WHITE); -// display.setCursor(0,0); -// display.println(str); -// display.display(); -// } -// #else -// void print_oled(String str,uint8_t size){ -// (void)str; -// (void)size; -// } -// #endif - -void print_oled(String str,uint8_t size){ - (void)str; - (void)size; -} WiFiManager wm; @@ -88,9 +40,6 @@ void saveWifiCallback(){ //gets called when WiFiManager enters configuration mode void configModeCallback (WiFiManager *myWiFiManager) { Serial.println("[CALLBACK] configModeCallback fired"); - #ifdef ESP8266 - print_oled("WiFiManager Waiting\nIP: " + WiFi.softAPIP().toString() + "\nSSID: " + WiFi.softAPSSID(),1); - #endif // myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // Serial.println(WiFi.softAPIP()); //if you used auto generated SSID, print it @@ -104,7 +53,7 @@ void saveParamCallback(){ void bindServerCallback(){ wm.server->on("/custom",handleRoute); - // wm.server->on("/info",handleRoute); // can override wm! + // wm.server->on("/info",handleRoute); // you can override wm! } void handleRoute(){ @@ -114,30 +63,33 @@ void handleRoute(){ void setup() { WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: Serial.begin(115200); // Serial1.begin(115200); // Serial.setDebugOutput(true); delay(1000); - // Serial1.println("TXD1 Enabled"); Serial.println("\n Starting"); // WiFi.setSleepMode(WIFI_NONE_SLEEP); // disable sleep, can improve ap stability - - #ifdef OLED - init_oled(); - #endif - print_oled(F("Starting..."),2); + + Serial.println("Error - TEST"); + Serial.println("Information- - TEST"); + + Serial.println("[ERROR] TEST"); + Serial.println("[INFORMATION] TEST"); + wm.debugPlatformInfo(); - //Local intialization. Once its business is done, there is no need to keep it around //reset settings - for testing // wm.resetSettings(); // wm.erase(); + // invert theme, dark wm.setClass("invert"); + // setup some parameters WiFiManagerParameter custom_html("

This Is Custom HTML

"); // only custom html WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); @@ -154,7 +106,7 @@ void setup() { wm.setSaveConfigCallback(saveWifiCallback); wm.setSaveParamsCallback(saveParamCallback); - //add all your parameters here + // add all your parameters here wm.addParameter(&custom_html); wm.addParameter(&custom_mqtt_server); wm.addParameter(&custom_mqtt_port); @@ -163,51 +115,66 @@ void setup() { wm.addParameter(&custom_ipaddress); wm.addParameter(&custom_checkbox); + // set values later if you want custom_html.setValue("test",4); custom_token.setValue("test",4); - // Set cutom menu via menu[] or vector - // const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - // wm.setMenu(menu,9); // custom menu array must provide length +/* + Set cutom menu via menu[] or vector + const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; + wm.setMenu(menu,9); // custom menu array must provide length +*/ std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; // wm.setMenu(menu); // custom menu, pass vector // wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu! - // set static sta ip + // set STA static ip // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // wm.setShowStaticFields(false); // wm.setShowDnsFields(false); - // set static ip + // set AP static ip // wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // wm.setAPStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set country - wm.setCountry("US"); // setting wifi country seems to improve OSX soft ap connectivity, may help others as well - - // set channel + // setting wifi country seems to improve OSX soft ap connectivity, + // may help others as well, default is CN which has different channels + wm.setCountry("US"); + + // set Hostname + wm.setHostname("WIFIMANAGERTESTING"); + + // set custom channel // wm.setWiFiAPChannel(13); // set AP hidden // wm.setAPHidden(true); - // show password publicly! + // show password publicly in form // wm.setShowPassword(true); //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep in seconds wm.setConfigPortalTimeout(120); + // set connection timeout // wm.setConnectTimeout(20); + + // set wifi connect retries + // wm.setConnectRetries(2); + + // show static ip fields // wm.setShowStaticFields(true); // wm.startConfigPortal("AutoConnectAP", "password"); - // wm.setCleanConnect(true); // disconenct before connect, clean connect + // This is sometimes necessary, it is still unknown when and why this is needed but it may solve some race condition or bug in esp SDK/lib + // wm.setCleanConnect(true); // disconnect before connect, clean connect - wm.setBreakAfterConfig(true); + wm.setBreakAfterConfig(true); // needed to use saveWifiCallback // set custom webserver port, automatic captive portal does not work with custom ports! // wm.setHttpPort(8080); @@ -216,23 +183,22 @@ void setup() { //if it does not connect it starts an access point with the specified name //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration + wifiInfo(); - print_oled(F("Connecting..."),2); + if(!wm.autoConnect("WM_AutoConnectAP","12345678")) { Serial.println("failed to connect and hit timeout"); - print_oled("Not Connected",2); } else if(TEST_CP) { + // start configportal always delay(1000); Serial.println("TEST_CP ENABLED"); - // start configportal always wm.setConfigPortalTimeout(TESP_CP_TIMEOUT); wm.startConfigPortal("WM_ConnectAP"); } else { //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); - print_oled("Connected\nIP: " + WiFi.localIP().toString() + "\nSSID: " + WiFi.SSID(),1); } wifiInfo(); @@ -241,6 +207,7 @@ void setup() { #ifdef USEOTA ArduinoOTA.begin(); #endif + } void wifiInfo(){ @@ -274,7 +241,6 @@ void loop() { else { //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); - print_oled("Connected\nIP: " + WiFi.localIP().toString() + "\nSSID: " + WiFi.SSID(),1); getTime(); } } @@ -300,13 +266,13 @@ void getTime() { Serial.print("."); now = time(nullptr); if((millis() - start) > timeout){ - Serial.println("[ERROR] Failed to get NTP time."); + Serial.println("\n[ERROR] Failed to get NTP time."); return; } } Serial.println(""); struct tm timeinfo; - gmtime_r(&now, &timeinfo); + gmtime_r(&now, &timeinfo); // @NOTE doesnt work in esp2.3.0 Serial.print("Current time: "); Serial.print(asctime(&timeinfo)); } @@ -332,4 +298,4 @@ void debugchipid(){ // AP esp_267751 // 507726A4AE30 // ESP32 Chip ID = 507726A4AE30 -} \ No newline at end of file +} diff --git a/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino index b231cc3..3813356 100644 --- a/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino +++ b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino @@ -41,7 +41,9 @@ void setup() { } void loop() { + #ifdef ESP8266 MDNS.update(); + #endif doWiFiManager(); // put your main code here, to run repeatedly: } diff --git a/examples/Tests/AnonymousCB.ino b/examples/Tests/AnonymousCB.ino index ff44976..f34d80f 100644 --- a/examples/Tests/AnonymousCB.ino +++ b/examples/Tests/AnonymousCB.ino @@ -4,7 +4,7 @@ bool _enteredConfigMode = false; void setup(){ Serial.begin(115200); -WiFiManager wifiManager; + WiFiManager wifiManager; // wifiManager.setAPCallback([this](WiFiManager* wifiManager) { wifiManager.setAPCallback([&](WiFiManager* wifiManager) { @@ -16,9 +16,11 @@ WiFiManager wifiManager; wifiManager.resetSettings(); if (!wifiManager.autoConnect()) { Serial.printf("*** Failed to connect and hit timeout\n"); - ESP.reset(); + ESP.restart(); delay(1000); } } -void loop(){} +void loop(){ + +} diff --git a/extras/WiFiManager.template.html b/extras/WiFiManager.template.html index 07ba834..2f01e53 100644 --- a/extras/WiFiManager.template.html +++ b/extras/WiFiManager.template.html @@ -139,12 +139,12 @@ a:hover { .msg.P h4 { color: var(--primarycolor); } -/*.msg.S { +.msg.S { border-left-color: #5cb85c; } .msg.S h4 { color: #5cb85c; -}*/ +} .msg.D { border-left-color: #dc3630; } @@ -201,6 +201,7 @@ input:disabled {



+

/wifi


@@ -269,9 +270,12 @@ input:disabled {
No AP set
-

H4 Color Header

content
+

H4 Color Header P

content
+

H4 Color Header S

content
+ +

/info


Chip ID
123456
diff --git a/library.json b/library.json index 0ceb4c8..96c4164 100644 --- a/library.json +++ b/library.json @@ -25,5 +25,5 @@ "espressif8266", "espressif32" ], - "version": "1.0.0" + "version": "2.0.3-alpha" } diff --git a/library.properties b/library.properties index 5ee6e46..9ac084b 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=WiFiManager -version=1.0.0 +version=2.0.3-alpha author=tzapu,tablatronix maintainer=tablatronix sentence=WiFi Configuration manager with web configuration portal for ESP boards diff --git a/strings_en.h b/strings_en.h index 75c5fc9..373380f 100644 --- a/strings_en.h +++ b/strings_en.h @@ -20,7 +20,6 @@ const char HTTP_HEAD_START[] PROGMEM = ""; @@ -59,11 +58,12 @@ const char HTTP_FORM_PARAM[] PROGMEM = "
Update Failed!
Reboot device and try again"; const char HTTP_UPDATE_OK[] PROGMEM = "
Update OK! Device Rebooting now...
"; -#ifdef JSTEST +#ifdef WM_JSTEST const char HTTP_JS[] PROGMEM = "