diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index a7dbf8b..6760b62 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -7,3 +7,6 @@ Please test against development branch before submitting issues, issues against PRs against master may be kept open if provides something useful to other members. Please open issues before sumbitting PRs against development, as commits might be occuring very frequently. + +### Documentation is in progress +https://github.com/tzapu/WiFiManager/issues/500 diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 5700570..2deb942 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,3 +1,6 @@ +## PLEASE TRY DEVELOPMENT BRANCH before submitting bugs on release or master, in case they were already fixed. ## + +Issues without basic info will be ignored or closed! Please fill the info fields, it helps to get you faster support ;) @@ -14,6 +17,8 @@ https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/debugging.rst #### Hardware WiFimanager Branch/Release: Development +Esp8266/Esp32: + Hardware: ESP-12e, esp01, esp25 Core Version: 2.4.0, staging diff --git a/.travis.yml b/.travis.yml index 97d018f..d41a13b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ before_install: install: - ln -s $PWD /usr/local/share/arduino/libraries/WiFiManager - arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json" --save-prefs - - arduino --install-library "ArduinoJson" + - arduino --install-library "ArduinoJson:5.13.2" - arduino --install-boards esp8266:esp8266 - arduino --pref "compiler.warning_level=all" --save-prefs # install esp32 @@ -38,8 +38,7 @@ script: - build_examples - arduino --board espressif:esp32:esp32doit-devkit-v1:FlashFreq=80,DebugLevel=info --save-prefs # some examples fail (SPIFFS defines differ esp32 vs esp8266) so we exclude them - - excludes=("AutoConnectWithFSParametersAndCustomIP.ino" "AutoConnectWithFSParameters.ino") - - build_examples "${excludes[@]}" + - build_examples # - arduino -v --verbose-build --verify $PWD/examples/AutoConnect/AutoConnect.ino # no coverage generated, no need to run diff --git a/README.md b/README.md index 5d6110a..7e53338 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +## Current development going on here :arrow_right: [Development Branch](https://github.com/tzapu/WiFiManager/tree/development) + # WiFiManager ESP8266 WiFi Connection manager with fallback web configuration portal @@ -14,12 +16,11 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are [https://github.com/esp8266/Arduino](https://github.com/esp8266/Arduino) -**This works with the ESP32 Arduino platform with staging , with caveats below** +**This works with the ESP32 Arduino platform with staging** [https://github.com/espressif/arduino-esp32](https://github.com/espressif/arduino-esp32) ### Known Issues -* :exclamation: ESP32 must be patched with webserver library, see [https://github.com/tzapu/WiFiManager/issues/513](https://github.com/tzapu/WiFiManager/issues/513) * Documentation needs to be updated, see [https://github.com/tzapu/WiFiManager/issues/500](https://github.com/tzapu/WiFiManager/issues/500) ## Contents @@ -27,8 +28,9 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - [Wishlist](#wishlist) - [Quick start](#quick-start) - Installing - - [Through Library Manager](#install-through-library-manager) - - [From Github](#checkout-from-github) + - [Arduino - Through Library Manager](#install-through-library-manager) + - [Arduino - From Github](#checkout-from-github) + - [PlatformIO] - [Using](#using) - [Documentation](#documentation) - [Access Point Password](#password-protect-the-configuration-access-point) @@ -45,12 +47,13 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are ## How It Works -- when your ESP starts up, it sets it up in Station mode and tries to connect to a previously saved Access Point +- When your ESP starts up, it sets it up in Station mode and tries to connect to a previously saved Access Point - if this is unsuccessful (or no previous network saved) it moves the ESP into Access Point mode and spins up a DNS and WebServer (default ip 192.168.4.1) - using any wifi enabled device with a browser (computer, phone, tablet) connect to the newly created Access Point - because of the Captive Portal and the DNS server you will either get a 'Join to network' type of popup or get any domain you try to access redirected to the configuration portal - choose one of the access points scanned, enter password, click save - ESP will try to connect. If successful, it relinquishes control back to your app. If not, reconnect to AP and reconfigure. +- There are options to change this behavior or manually start the configportal and webportal independantly as well as run them in non blocking mode. ## How It Looks ![ESP8266 WiFi Captive Portal Homepage](http://i.imgur.com/YPvW9eql.png) ![ESP8266 WiFi Captive Portal Configuration](http://i.imgur.com/oicWJ4gl.png) @@ -66,9 +69,35 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - [x] add to PlatformIO - [ ] add multiple sets of network credentials - [x] allow users to customize CSS -- [ ] ESP32 support or instructions - [ ] rewrite documentation for simplicity, based on scenarios/goals -- [ ] rely on the SDK's built in auto connect more than forcing a connect + +### Development +- [x] ESP32 support +- [x] rely on the SDK's built in auto connect more than forcing a connect +- [x] add non blocking mode +- [x] easy customization of strings +- [x] hostname support +- [x] fix various bugs and workarounds for esp SDK issues +- [x] additional info page items +- [x] last status display / faiilure reason +- [x] customizeable menu +- [x] seperate custom params page +- [x] ondemand webportal +- [x] complete refactor of code to segment functions +- [x] wiif scan icons or percentage display +- [x] invert class for dark mode +- [x] more template tokens +- [x] progmem for all strings +- [ ] new callbacks +- [ ] new callouts / filters +- [ ] shared web server instance +- [x] latest esp idf/sdk support +- [x] wm is now non persistent, will not erase or change stored esp config on esp8266 +- [x] tons of debugging output / levels +- [ ] disable captiveportal +- [ ] preload wiifscans, faster page loads +- [ ] softap stability fixes when sta is not connected + ## Quick Start @@ -76,7 +105,7 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are You can either install through the Arduino Library Manager or checkout the latest changes or a release from github #### Install through Library Manager -__Currently version 0.8+ works with release 2.0.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ +__Currently version 0.8+ works with release 2.4.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ - in Arduino IDE got to Sketch/Include Library/Manage Libraries ![Manage Libraries](http://i.imgur.com/9BkEBkR.png) @@ -86,20 +115,16 @@ __Currently version 0.8+ works with release 2.0.0 or newer of the [ESP8266 core - click Install and start [using it](#using) #### Checkout from github -__Github version works with release 2.0.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ +__Github version works with release 2.4.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ - Checkout library to your Arduino libraries folder ### Using - Include in your sketch ```cpp -#include //ESP8266 Core WiFi Library (you most likely already have this in your sketch) - -#include //Local DNS Server used for redirecting all requests to the configuration portal -#include //Local WebServer used to serve the configuration portal #include //https://github.com/tzapu/WiFiManager WiFi Configuration Magic ``` -- Initialize library, in your setup function add +- Initialize library, in your setup function add, NOTEif you are using non blocking you will make sure you create this in global scope or handle appropriatly , it will not work if in setup and using non blocking mode. ```cpp WiFiManager wifiManager; ``` @@ -239,7 +264,7 @@ wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddr ##### Custom Station (client) Static IP Configuration This will make use the specified IP configuration instead of using DHCP in station mode. ```cpp -wifiManager.setSTAStaticIPConfig(IPAddress(192,168,0,99), IPAddress(192,168,0,1), IPAddress(255,255,255,0)); +wifiManager.setSTAStaticIPConfig(IPAddress(192,168,0,99), IPAddress(192,168,0,1), IPAddress(255,255,255,0)); // optional DNS 4th argument ``` There are a couple of examples in the examples folder that show you how to set a static IP and even how to configure it through the web configuration portal. @@ -251,7 +276,7 @@ You can use this to any html bit to the head of the configuration portal. If you ```cpp wifiManager.setCustomHeadElement(""); ``` -- inject a custom bit of html in the configuration form +- inject a custom bit of html in the configuration/param form ```cpp WiFiManagerParameter custom_text("

This is just a text paragraph

"); wifiManager.addParameter(&custom_text); @@ -262,6 +287,14 @@ Just add the bit you want added as the last parameter to the custom parameter co WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "iot.eclipse", 40, " readonly"); ``` +#### Theming +You can customize certain elements of the default template with some builtin classes +```CPP +wifiManager.setClass("invert"); // dark theme +wifiManager.setScanDispPerc(true); // display percentages instead of graphs for RSSI +``` +There are additional classes in the css you can use in your custom html , see the example template. + #### Filter Networks You can filter networks based on signal quality and show/hide duplicate networks. @@ -278,11 +311,24 @@ wifiManager.setRemoveDuplicateAPs(false); ``` #### Debug -Debug is enabled by default on Serial. To disable add before autoConnect +Debug is enabled by default on `Serial` in non-stable releases. To disable add before autoConnect/startConfigPortal ```cpp wifiManager.setDebugOutput(false); ``` +You can pass in a custom stream via constructor +```CPP +WiFiManager wifiManager(Serial1); +``` + +You can customize the debug level by changing `_debugLevel` in source +options are: +* DEBUG_ERROR +* DEBUG_NOTIFY +* DEBUG_VERBOSE +* DEBUG_DEV +* DEBUG_MAX + ## Troubleshooting If you get compilation errors, more often than not, you may need to install a newer version of the ESP8266 core for Arduino. @@ -294,7 +340,122 @@ If you connect to the created configuration Access Point but the configuration p If trying to connect ends up in an endless loop, try to add `setConnectTimeout(60)` before `autoConnect();`. The parameter is timeout to try connecting in seconds. +I get stuck in ap mode when the power goes out or modem resets, try a setConfigPortalTimeout(seconds). This will cause the configportal to close after no activity, and you can reboot or attempt reconnection in your code. + ## Releases +### 1.0.1 + +### Development Overview + +#### Added Public Methods +`setConfigPortalBlocking` + +`setShowStaticFields` + +`setCaptivePortalEnable` + +`setRestorePersistent` + +`setCaptivePortalClientCheck` + +`setWebPortalClientCheck` + +`startWebPortal` + +`stopWebPortal` + +`process` + +`disconnect` + +`erase` + +` debugSoftAPConfig` + +` debugPlatformInfo` + +`setScanDispPerc` + +`setHostname` + +`setMenu(menu_page_t[])` + +`setWiFiAutoReconnect` + +` setSTAStaticIPConfig(..,dns)` + +`setShowDnsFields` + +`getLastConxResult` + +`getWLStatusString` + +`getModeString` + +`getWiFiIsSaved` + +`setShowInfoErase` + +`setEnableConfigPortal` + +`setCountry` + +`setClass` + +`htmleEtities` + + +#### WiFiManagerParameter +`WiFiManagerParameter(id,label)` + +`WiFiManagerParameter.setValue(value,length)` + +`getParameters` + +`getParametersCount` + + +#### Constructors +`WiFiManager(Stream& consolePort)` + +#### define flags +❗️ **Defines cannot be set in user sketches** +`#define WM_MDNS // use MDNS` + +`#define WM_FIXERASECONFIG // use erase flash fix, esp8266 2.4.0` + +`#define WM_ERASE_NVS // esp32 erase(true) will erase NVS` + +`#include // esp32 info page will show last reset reasons if this file is included` + +#### Changes Overview +- ESP32 support ( fairly stable ) +- complete refactor of strings `strings_en.h` +- adds new tokens for wifiscan, and some classes (left , invert icons, MSG color) +- adds status callout panel default, primary, special colors +- adds tons of info on info page, and erase capability +- adds signal icons, replaces percentage ( has hover titles ) +- adds labels to all inputs (replaces placeholders) +- all html ( and eventually all strings except debug) moved to `strings_en.h` +- added additional debugging, compressed debug lines, debuglevels +- persistent disabled, and restored via de/con-stuctor (uses `setRestorePersistent`) +- should retain all user modes including AP, should not overwrite or persist user modes or configs,even STA (`storeSTAmode`) (BUGGY) +- ⚠️ return values may have changed depending on portal abort, or timeout ( `portalTimeoutResult`,`portalAbortResult`) +- params memory is auto allocated by increment of `WIFI_MANAGER_MAX_PARAMS(5)` when exceeded, user no longer needs to specify this at all. +- addparameter now returns bool, and it returns false if param ID is not alphanum [0-9,A-Z,a-z,_] +- param field ids allow {I} token to use param_n instead of string in case someones wants to change this due to i18n or character issues +- provides `#DEFINE FIXERASECONFIG` to help deal with https://github.com/esp8266/Arduino/pull/3635 +- failure reason reporting on portal +- set esp8266 sta hostname, esp32 sta+ap hostname ( DHCP client id) +- pass in debug stream in constructor WiFiManager(Stream& consolePort) +- you can force ip fields off with showxfields(false) if you set _disableIpFields=true +- param menu/page (setup) added to separate params from wifi page, handled automatically by setMenu +- set custom root menu +- disable configportal on autoconnect +- wm parameters init is now protected, allowing child classes, example included +- wifiscans are precached and async for faster page loads, refresh forces rescan +- adds esp32 gettemperature ( currently commented out, useful for relative measurement only ) + #### 0.12 - removed 204 header response - fixed incompatibility with other libs using isnan and other std:: functions without namespace @@ -313,53 +474,20 @@ If trying to connect ends up in an endless loop, try to add `setConnectTimeout(6 - added an alternative to waitForConnectResult() for debugging - changed `setTimeout(seconds)` to `setConfigPortalTimeout(seconds)` -##### 0.9 - - fixed support for encoded characters in ssid/pass - -##### 0.8 - - made it compile on older versions of ESP8266 core as well, tested down to 2.0.0 - - added simple example for Custom IP - -##### 0.7 - - added static IP in station mode - - added example of persisting custom IP to FS config.json - - more option on portal homepage - - added on PlatformIO - -##### 0.6 - - custom parameters - - prettier - - on demand config portal - - commit #100 :D - -##### 0.5 - - Added to Arduino Boards Manager - Thanks Max - - moved most stuff to PROGMEM - - added signal quality and a nice little padlock to show which networks are encrypted - -##### v0.4 - all of it user contributed changes - Thank you - - added ability to password protect the configuration Access Point - - callback for enter configuration mode - - memory allocation improvements - -##### v0.3 - - removed the need for EEPROM and works with the 2.0.0 and above stable release of the ESP8266 for Arduino IDE package - - removed restart on save of credentials - - updated examples - -##### v0.2 -needs the latest staging version (or at least a recent release of the staging version) to work - -##### v0.1 -works with the staging release ver. 1.6.5-1044-g170995a, built on Aug 10, 2015 of the ESP8266 Arduino library. - - ### Contributions and thanks The support and help I got from the community has been nothing short of phenomenal. I can't thank you guys enough. This is my first real attept in developing open source stuff and I must say, now I understand why people are so dedicated to it, it is because of all the wonderful people involved. __THANK YOU__ -[Shawn A](https://github.com/tablatronix) +The esp8266 and esp32 arduino and idf maintainers! + +[Shawn A aka tablatronix](https://github.com/tablatronix) + +[liebman](https://github.com/liebman) + +[Evgeny Dontsov](https://github.com/dontsovcmc) + +[Chris Marrin](https://github.com/cmarrin) [bbx10](https://github.com/bbx10) @@ -396,3 +524,4 @@ And countless others * https://github.com/chriscook8/esp-arduino-apboot * https://github.com/esp8266/Arduino/tree/master/libraries/DNSServer/examples/CaptivePortalAdvanced * Built by AlexT https://github.com/tzapu + diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 7a199c8..260d021 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -22,34 +22,38 @@ uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS; * -------------------------------------------------------------------------------- **/ +WiFiManagerParameter::WiFiManagerParameter() { + WiFiManagerParameter(""); +} + WiFiManagerParameter::WiFiManagerParameter(const char *custom) { _id = NULL; - _placeholder = NULL; - _length = 0; + _label = NULL; + _length = 1; _value = NULL; _labelPlacement = WFM_LABEL_BEFORE; _customHTML = custom; } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder) { - init(id, placeholder, "", 0, "", WFM_LABEL_BEFORE); +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label) { + init(id, label, "", 0, "", WFM_LABEL_BEFORE); } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length) { - init(id, placeholder, defaultValue, length, "", WFM_LABEL_BEFORE); +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length) { + init(id, label, defaultValue, length, "", WFM_LABEL_BEFORE); } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom) { - init(id, placeholder, defaultValue, length, custom, WFM_LABEL_BEFORE); +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom) { + init(id, label, defaultValue, length, custom, WFM_LABEL_BEFORE); } -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) { - init(id, placeholder, defaultValue, length, custom, labelPlacement); +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { + init(id, label, defaultValue, length, custom, labelPlacement); } -void WiFiManagerParameter::init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) { +void WiFiManagerParameter::init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { _id = id; - _placeholder = placeholder; + _label = label; _labelPlacement = labelPlacement; _customHTML = custom; setValue(defaultValue,length); @@ -59,16 +63,27 @@ WiFiManagerParameter::~WiFiManagerParameter() { if (_value != NULL) { delete[] _value; } + _length=0; // setting length 0, ideally the entire parameter should be removed, or added to wifimanager scope so it follows } +// @note debug is not available in wmparameter class void WiFiManagerParameter::setValue(const char *defaultValue, int length) { - _length = length; - _value = new char[length + 1]; - for (int i = 0; i < length + 1; i++) { - _value[i] = 0; + if(!_id){ + // Serial.println("cannot set value of this parameter"); + return; } + + // if(strlen(defaultValue) > length){ + // // Serial.println("defaultValue length mismatch"); + // // return false; //@todo bail + // } + + _length = length; + _value = new char[_length + 1]; + memset(_value, 0, _length + 1); // explicit null + if (defaultValue != NULL) { - strncpy(_value, defaultValue, length + 1); // length+1 due to null terminated string + strncpy(_value, defaultValue, _length); } } const char* WiFiManagerParameter::getValue() { @@ -78,7 +93,10 @@ const char* WiFiManagerParameter::getID() { return _id; } const char* WiFiManagerParameter::getPlaceholder() { - return _placeholder; + return _label; +} +const char* WiFiManagerParameter::getLabel() { + return _label; } int WiFiManagerParameter::getValueLength() { return _length; @@ -137,6 +155,22 @@ bool WiFiManager::addParameter(WiFiManagerParameter *p) { return true; } +/** + * [getParameters description] + * @access public + */ +WiFiManagerParameter** WiFiManager::getParameters() { + return _params; +} + +/** + * [getParametersCount description] + * @access public + */ +int WiFiManager::getParametersCount() { + return _paramsCount; +} + /** * -------------------------------------------------------------------------------- * WiFiManager @@ -154,32 +188,41 @@ WiFiManager::WiFiManager():WiFiManager(Serial) { void WiFiManager::WiFiManagerInit(){ setMenu(_menuIdsDefault); if(_debug && _debugLevel > DEBUG_DEV) debugPlatformInfo(); - - _usermode = WiFi.getMode(); - WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites - _max_params = WIFI_MANAGER_MAX_PARAMS; } // destructor WiFiManager::~WiFiManager() { - if(_userpersistent) WiFi.persistent(true); // reenable persistent, there is no getter we rely on _userpersistent - // if(_usermode != WIFI_OFF) WiFi.mode(_usermode); - + _end(); // parameters // @todo belongs to wifimanagerparameter if (_params != NULL){ DEBUG_WM(DEBUG_DEV,F("freeing allocated params!")); free(_params); + _params = NULL; } DEBUG_WM(DEBUG_DEV,F("unloading")); } +void WiFiManager::_begin(){ + if(_hasBegun) return; + _usermode = WiFi.getMode(); + + #ifndef ESP32 + WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites + #endif +} + +void WiFiManager::_end(){ + if(_userpersistent) WiFi.persistent(true); // reenable persistent, there is no getter we rely on _userpersistent + // if(_usermode != WIFI_OFF) WiFi.mode(_usermode); +} + // AUTOCONNECT boolean WiFiManager::autoConnect() { - String ssid = _wifissidprefix + "_" + String(WIFI_getChipId()); + String ssid = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); return autoConnect(ssid.c_str(), NULL); } @@ -192,6 +235,7 @@ boolean WiFiManager::autoConnect() { */ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { DEBUG_WM(F("AutoConnect")); + _begin(); // attempt to connect using saved settings, on fail fallback to AP config portal if(!WiFi.enableSTA(true)){ @@ -199,6 +243,12 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { DEBUG_WM(DEBUG_ERROR,"[FATAL] Unable to enable wifi!"); return false; } + + WiFiSetCountry(); + + #ifdef ESP32 + if(esp32persistent) WiFi.persistent(false); // disable persistent for esp32 after esp_wifi_start or else saves wont work + #endif _usermode = WIFI_STA; @@ -207,8 +257,6 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { // so we must force it on else, if not connectimeout then waitforconnectionresult gets stuck endless loop WiFi_autoReconnect(); - getMenuOut(); - // set hostname before stating if((String)_hostname != ""){ DEBUG_WM(DEBUG_VERBOSE,"Setting hostname:",_hostname); @@ -245,7 +293,15 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { // if already connected, or try stored connect // @note @todo ESP32 has no autoconnect, so connectwifi will always be called unless user called begin etc before - if (WiFi.status() == WL_CONNECTED || connectWifi("", "") == WL_CONNECTED) { + // @todo check if correct ssid == saved ssid when already connected + bool connected = false; + if (WiFi.status() == WL_CONNECTED){ + connected = true; + DEBUG_WM(F("AutoConnect: ESP Already Connected")); + setSTAConfig(); + } + + if(connected || connectWifi("", "") == WL_CONNECTED){ //connected DEBUG_WM(F("AutoConnect: SUCCESS")); DEBUG_WM(F("STA IP Address:"),WiFi.localIP()); @@ -277,14 +333,6 @@ bool WiFiManager::startAP(){ bool ret = true; DEBUG_WM(F("StartAP with SSID: "),_apName); - // setup optional soft AP static ip config - if (_ap_static_ip) { - DEBUG_WM(F("Custom AP IP/GW/Subnet:")); - if(!WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn)){ - DEBUG_WM(DEBUG_ERROR,"[ERROR] softAPConfig failed!"); - } - } - #ifdef ESP8266 // @bug workaround for bug #4372 https://github.com/esp8266/Arduino/issues/4372 if(!WiFi.enableAP(true)) { @@ -294,18 +342,42 @@ bool WiFiManager::startAP(){ delay(500); // workaround delay #endif + // setup optional soft AP static ip config + if (_ap_static_ip) { + DEBUG_WM(F("Custom AP IP/GW/Subnet:")); + if(!WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn)){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] softAPConfig failed!"); + } + } + + //@todo add callback here if needed to modify ap but cannot use setAPStaticIPConfig + + if(_channelSync){ + DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",WiFi.channel()); + } + // start soft AP with password or anonymous if (_apPassword != "") { - ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str());//password option + if(_channelSync){ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),WiFi.channel()); + } + else{ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str());//password option + } } else { DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!")); - ret = WiFi.softAP(_apName.c_str()); + if(_channelSync){ + ret = WiFi.softAP(_apName.c_str(),"",WiFi.channel()); + } + else{ + ret = WiFi.softAP(_apName.c_str()); + } } if(_debugLevel > DEBUG_DEV) debugSoftAPConfig(); if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] There was a problem starting the AP"); - // @tood add softAP retry here + // @todo add softAP retry here delay(500); // slight delay to make sure we get an AP IP DEBUG_WM(F("AP IP address:"),WiFi.softAPIP()); @@ -320,11 +392,6 @@ bool WiFiManager::startAP(){ } #endif - // do AP callback if set - if ( _apcallback != NULL) { - _apcallback(this); - } - return ret; } @@ -348,12 +415,12 @@ void WiFiManager::stopWebPortal() { if(!configPortalActive && !webPortalActive) return; DEBUG_WM(DEBUG_VERBOSE,F("Stopping Web Portal")); webPortalActive = false; - stopConfigPortal(); + shutdownConfigPortal(); } boolean WiFiManager::configPortalHasTimeout(){ - if(_configPortalTimeout == 0 || (_cpClientCheck && (WiFi_softap_num_stations() > 0))){ + if(_configPortalTimeout == 0 || (_apClientCheck && (WiFi_softap_num_stations() > 0))){ if(millis() - timer > 30000){ timer = millis(); DEBUG_WM(DEBUG_VERBOSE,"NUM CLIENTS: " + (String)WiFi_softap_num_stations()); @@ -395,31 +462,39 @@ void WiFiManager::setupConfigPortal() { DEBUG_WM(DEBUG_DEV,"dns server started with ip: ",WiFi.softAPIP()); dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); + // @todo new callback, webserver started, callback cannot override handlers, but can grab them first + + if ( _webservercallback != NULL) { + _webservercallback(); + } + /* Setup httpd callbacks, web pages: root, wifi config pages, SO captive portal detectors and not found. */ - server->on((String)FPSTR(R_root), std::bind(&WiFiManager::handleRoot, this)); - server->on((String)FPSTR(R_wifi), std::bind(&WiFiManager::handleWifi, this, true)); - server->on((String)FPSTR(R_wifinoscan), std::bind(&WiFiManager::handleWifi, this, false)); - server->on((String)FPSTR(R_wifisave), std::bind(&WiFiManager::handleWifiSave, this)); - server->on((String)FPSTR(R_info), std::bind(&WiFiManager::handleInfo, this)); - server->on((String)FPSTR(R_param), std::bind(&WiFiManager::handleParam, this)); - server->on((String)FPSTR(R_paramsave), std::bind(&WiFiManager::handleParamSave, this)); + + server->on(String(FPSTR(R_root)).c_str(), std::bind(&WiFiManager::handleRoot, this)); + server->on(String(FPSTR(R_wifi)).c_str(), std::bind(&WiFiManager::handleWifi, this, true)); + server->on(String(FPSTR(R_wifinoscan)).c_str(), std::bind(&WiFiManager::handleWifi, this, false)); + server->on(String(FPSTR(R_wifisave)).c_str(), std::bind(&WiFiManager::handleWifiSave, this)); + server->on(String(FPSTR(R_info)).c_str(), std::bind(&WiFiManager::handleInfo, this)); + server->on(String(FPSTR(R_param)).c_str(), std::bind(&WiFiManager::handleParam, this)); + server->on(String(FPSTR(R_paramsave)).c_str(), std::bind(&WiFiManager::handleParamSave, this)); + server->on(String(FPSTR(R_restart)).c_str(), std::bind(&WiFiManager::handleReset, this)); + server->on(String(FPSTR(R_exit)).c_str(), std::bind(&WiFiManager::handleExit, this)); + server->on(String(FPSTR(R_close)).c_str(), std::bind(&WiFiManager::handleClose, this)); + server->on(String(FPSTR(R_erase)).c_str(), std::bind(&WiFiManager::handleErase, this, false)); + server->on(String(FPSTR(R_status)).c_str(), std::bind(&WiFiManager::handleWiFiStatus, this)); + server->onNotFound (std::bind(&WiFiManager::handleNotFound, this)); + server->on((String)FPSTR(R_update), std::bind(&WiFiManager::handleUpdate, this)); server->on((String)FPSTR(R_updatedone), HTTP_POST, std::bind(&WiFiManager::handleUpdateDone, this), std::bind(&WiFiManager::handleUpdating, this)); - server->on((String)FPSTR(R_restart), std::bind(&WiFiManager::handleReset, this)); - server->on((String)FPSTR(R_exit), std::bind(&WiFiManager::handleExit, this)); - server->on((String)FPSTR(R_close), std::bind(&WiFiManager::handleClose, this)); - server->on((String)FPSTR(R_erase), std::bind(&WiFiManager::handleErase, this, false)); - server->on((String)FPSTR(R_status), std::bind(&WiFiManager::handleWiFiStatus, this)); - server->onNotFound (std::bind(&WiFiManager::handleNotFound, this)); server->begin(); // Web server start DEBUG_WM(DEBUG_VERBOSE,F("HTTP server started")); - if(_preloadwifiscan) WiFi_scanNetworks(); // preload wifiscan + if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan , async } boolean WiFiManager::startConfigPortal() { - String ssid = _wifissidprefix + "_" + String(WIFI_getChipId()); + String ssid = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); return startConfigPortal(ssid.c_str(), NULL); } @@ -431,18 +506,18 @@ boolean WiFiManager::startConfigPortal() { * @return {[type]} [description] */ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { + _begin(); + //setup AP _apName = apName; // @todo check valid apname ? _apPassword = apPassword; - if(_apName == "") _apName = _wifissidprefix + "_" + String(WIFI_getChipId()); + if(_apName == "") _apName = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); if(!validApPassword()) return false; - bool disableSTA = false; // debug, always disable sta - // HANDLE issues with STA connections, shutdown sta if not connected, or else this will hang channel scanning and softap will not respond // @todo sometimes still cannot connect to AP for no known reason, no events in log either - if(!WiFi.isConnected() || disableSTA){ + if(_disableSTA || (!WiFi.isConnected() && _disableSTAConn)){ // this fixes most ap problems, however, simply doing mode(WIFI_AP) does not work if sta connection is hanging, must `wifi_station_disconnect` WiFi_Disconnect(); WiFi_enableSTA(false); @@ -463,6 +538,12 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo // start access point DEBUG_WM(DEBUG_VERBOSE,F("Enabling AP")); startAP(); + WiFiSetCountry(); + + // do AP callback if set + if ( _apcallback != NULL) { + _apcallback(this); + } // init configportal DEBUG_WM(DEBUG_DEV,F("setupConfigPortal")); @@ -480,7 +561,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo // if timed out or abort, break if(configPortalHasTimeout() || abort){ DEBUG_WM(DEBUG_DEV,F("configportal abort")); - stopConfigPortal(); + shutdownConfigPortal(); result = abort ? portalAbortResult : portalTimeoutResult; // false, false break; } @@ -526,33 +607,41 @@ uint8_t WiFiManager::processConfigPortal(){ DEBUG_WM(DEBUG_VERBOSE,F("process connect")); if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast. - // attempt sta connection to submitted _ssid, _pass - if (connectWifi(_ssid, _pass) == WL_CONNECTED) { - - DEBUG_WM(F("Connect to new AP [SUCCESS]")); - DEBUG_WM(F("Got IP Address:")); - DEBUG_WM(WiFi.localIP()); - - if ( _savecallback != NULL) { - _savecallback(); - } - stopConfigPortal(); - return WL_CONNECTED; // CONNECT SUCCESS + // skip wifi if no ssid + if(_ssid == ""){ + DEBUG_WM(DEBUG_VERBOSE,F("No ssid, skipping wifi")); } + else{ + // attempt sta connection to submitted _ssid, _pass + if (connectWifi(_ssid, _pass) == WL_CONNECTED) { + + DEBUG_WM(F("Connect to new AP [SUCCESS]")); + DEBUG_WM(F("Got IP Address:")); + DEBUG_WM(WiFi.localIP()); - DEBUG_WM(DEBUG_ERROR,F("[ERROR] Connect to new AP Failed")); - + if ( _savewificallback != NULL) { + _savewificallback(); + } + shutdownConfigPortal(); + return WL_CONNECTED; // CONNECT SUCCESS + } + DEBUG_WM(DEBUG_ERROR,F("[ERROR] Connect to new AP Failed")); + } + if (_shouldBreakAfterConfig) { // do save callback // @todo this is more of an exiting callback than a save, clarify when this should actually occur // confirm or verify data was saved to make this more accurate callback - if ( _savecallback != NULL) { - _savecallback(); + if ( _savewificallback != NULL) { + _savewificallback(); } - stopConfigPortal(); + shutdownConfigPortal(); return WL_CONNECT_FAILED; // CONNECT FAIL } else{ + // clear save strings + _ssid = ""; + _pass = ""; // if connect fails, turn sta off to stabilize AP WiFi_Disconnect(); WiFi_enableSTA(false); @@ -564,11 +653,11 @@ uint8_t WiFiManager::processConfigPortal(){ } /** - * [stopConfigPortal description] + * [shutdownConfigPortal description] * @access public - * @return {[type]} [description] + * @return bool success (softapdisconnect) */ -boolean WiFiManager::stopConfigPortal(){ +bool WiFiManager::shutdownConfigPortal(){ if(webPortalActive) return false; //DNS handler @@ -579,8 +668,11 @@ boolean WiFiManager::stopConfigPortal(){ // @todo what is the proper way to shutdown and free the server up server->stop(); server.reset(); + dnsServer->stop(); // free heap ? dnsServer.reset(); + WiFi.scanDelete(); // free wifi scan results + if(!configPortalActive) return false; // turn off AP @@ -592,11 +684,17 @@ boolean WiFiManager::stopConfigPortal(){ bool ret = false; ret = WiFi.softAPdisconnect(false); if(!ret)DEBUG_WM(DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); - // WiFi_Mode(_usermode); // restore users wifi mode, BUG https://github.com/esp8266/Arduino/issues/4372 - // DEBUG_WM("usermode",_usermode); - // DEBUG_WM(getWLStatusString(WiFi.status())); - if(WiFi.status()==WL_IDLE_STATUS) WiFi.reconnect(); // restart wifi since we disconnected it in startconfigportal + delay(1000); + DEBUG_WM(DEBUG_VERBOSE,"restoring usermode",getModeString(_usermode)); + WiFi_Mode(_usermode); // restore users wifi mode, BUG https://github.com/esp8266/Arduino/issues/4372 + if(WiFi.status()==WL_IDLE_STATUS){ + WiFi.reconnect(); // restart wifi since we disconnected it in startconfigportal + DEBUG_WM(DEBUG_VERBOSE,"WiFi Reconnect, was idle"); + } + DEBUG_WM(DEBUG_VERBOSE,"wifi status:",getWLStatusString(WiFi.status())); + DEBUG_WM(DEBUG_VERBOSE,"wifi mode:",getModeString(WiFi.getMode())); configPortalActive = false; + _end(); return ret; } @@ -612,7 +710,8 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { //@todo catch failures in set_config // make sure sta is on before `begin` so it does not call enablesta->mode while persistent is ON ( which would save WM AP state to eeprom !) - WiFi_Disconnect(); // disconnect before begin, in case anything is hung + if(_cleanConnect) WiFi_Disconnect(); // disconnect before begin, in case anything is hung, this causes a 2 seconds delay for connect + // @todo find out what status is when this is needed, can we detect it and handle it, say in between states or idle_status // if ssid argument provided connect to that if (ssid != "") { @@ -637,6 +736,8 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { DEBUG_WM(DEBUG_VERBOSE,F("Connection result:"),getWLStatusString(connRes)); +// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 +#ifdef NO_EXTRA_4K_HEAP // do WPS, if WPS options enabled and not connected and no password was supplied // @todo this seems like wrong place for this, is it a fallback or option? if (_tryWPS && connRes != WL_CONNECTED && pass == "") { @@ -644,6 +745,7 @@ uint8_t WiFiManager::connectWifi(String ssid, String pass) { // should be connected at the end of WPS connRes = waitForConnectResult(); } +#endif if(connRes != WL_SCAN_COMPLETED){ updateConxResult(connRes); @@ -705,6 +807,8 @@ bool WiFiManager::setSTAConfig(){ if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi config failed"); else DEBUG_WM(F("STA IP set:"),WiFi.localIP()); + } else { + DEBUG_WM(DEBUG_VERBOSE,F("setSTAConfig static ip not set")); } return ret; } @@ -765,6 +869,8 @@ uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) { return status; } +// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 +#ifdef NO_EXTRA_4K_HEAP void WiFiManager::startWPS() { DEBUG_WM(F("START WPS")); #ifdef ESP8266 @@ -774,16 +880,25 @@ void WiFiManager::startWPS() { #endif DEBUG_WM(F("END WPS")); } - +#endif String WiFiManager::getHTTPHead(String title){ String page; - page += FPSTR(HTTP_HEAD); + page += FPSTR(HTTP_HEAD_START); page.replace(FPSTR(T_v), title); page += FPSTR(HTTP_SCRIPT); page += FPSTR(HTTP_STYLE); page += _customHeadElement; - page += FPSTR(HTTP_HEAD_END); + + if(_bodyClass != ""){ + String p = FPSTR(HTTP_HEAD_END); + p.replace(FPSTR(T_c), _bodyClass); // add class str + page += p; + } + else { + page += FPSTR(HTTP_HEAD_END); + } + return page; } @@ -813,7 +928,10 @@ void WiFiManager::handleRoot() { server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); server->send(200, FPSTR(HTTP_HEAD_CT), page); // server->close(); // testing reliability fix for content length mismatches during mutiple flood hits WiFi_scanNetworks(); // preload wifiscan - if(_preloadwifiscan) WiFi_scanNetworks((unsigned)10000); // preload wifiscan throttled + if(_preloadwifiscan) WiFi_scanNetworks((unsigned)20000,true); // preload wifiscan throttled, async + // @todo buggy, captive portals make a query on every page load, causing this to run every time in addition to the real page load + // I dont understand why, when you are already in the captive portal, I guess they want to know that its still up and not done or gone + // if we can detect these and ignore them that would be great, since they come from the captive portal redirect maybe there is a refferer } /** @@ -824,7 +942,8 @@ void WiFiManager::handleWifi(boolean scan) { handleRequest(); String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi if (scan) { - WiFi_scanNetworks(server->hasArg(F("refresh"))); //wifiscan, force if arg refresh + // DEBUG_WM(DEBUG_DEV,"refresh flag:",server->hasArg(F("refresh"))); + WiFi_scanNetworks(server->hasArg(F("refresh")),false); //wifiscan, force if arg refresh page += getScanItemOut(); } String pitem = ""; @@ -884,7 +1003,7 @@ void WiFiManager::handleParam(){ String WiFiManager::getMenuOut(){ String page; - for(auto& menuId :_menuIds ){ + for(auto menuId :_menuIds ){ if(((String)menuId == "param") && (_paramsCount == 0)) continue; // no params set, omit params page += HTTP_PORTAL_MENU[menuId]; } @@ -892,21 +1011,66 @@ String WiFiManager::getMenuOut(){ return page; } +// // is it possible in softap mode to detect aps without scanning +// bool WiFiManager::WiFi_scanNetworksForAP(bool force){ +// WiFi_scanNetworks(force); +// } + +void WiFiManager::WiFi_scanComplete(int networksFound){ + _lastscan = millis(); + _numNetworks = networksFound; + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC completed"), "in "+(String)(_lastscan - _startscan)+" ms"); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC found:"),_numNetworks); +} + bool WiFiManager::WiFi_scanNetworks(){ - return WiFi_scanNetworks(false); + return WiFi_scanNetworks(false,false); +} + +bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime,bool async){ + return WiFi_scanNetworks(millis()-_lastscan > cachetime,async); } bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime){ - return WiFi_scanNetworks(millis()-_lastscan > cachetime); + return WiFi_scanNetworks(millis()-_lastscan > cachetime,false); } -bool WiFiManager::WiFi_scanNetworks(bool force){ - // DEBUG_WM("scanNetworks force:",force == true); - // DEBUG_WM(_numNetworks,(millis()-_lastscan )); +bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ + // DEBUG_WM(DEBUG_DEV,"scanNetworks async:",async == true); + // DEBUG_WM(DEBUG_DEV,_numNetworks,(millis()-_lastscan )); + // DEBUG_WM(DEBUG_DEV,"scanNetworks force:",force == true); if(force || _numNetworks == 0 || (millis()-_lastscan > 60000)){ - _numNetworks = WiFi.scanNetworks(); + int8_t res; + _startscan = millis(); + if(async){ + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); + #ifdef ESP8266 + #ifndef WM_NOASYNC // no async available < 2.4.0 + using namespace std::placeholders; // for `_1` + WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); + #else + res = WiFi.scanNetworks(); + #endif + #else + res = WiFi.scanNetworks(true); + #endif + return false; + } + else{ + res = WiFi.scanNetworks(); + } + if(res == WIFI_SCAN_FAILED) DEBUG_WM(DEBUG_ERROR,"[ERROR] scan failed"); + else if(res == WIFI_SCAN_RUNNING){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] scan waiting"); + while(WiFi.scanComplete() == WIFI_SCAN_RUNNING){ + DEBUG_WM(DEBUG_ERROR,"."); + delay(100); + } + _numNetworks = WiFi.scanComplete(); + } + else if(res >=0 ) _numNetworks = res; _lastscan = millis(); - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan done")); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); return true; - } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached"); + } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+" ms ago"); return false; } @@ -1029,6 +1193,7 @@ String WiFiManager::getIpForm(String id, String title, String value){ String WiFiManager::getStaticOut(){ String page; if ((_staShowStaticFields || _sta_static_ip) && _staShowStaticFields>=0) { + DEBUG_WM(DEBUG_DEV,"_staShowStaticFields"); page += FPSTR(HTTP_FORM_STATIC_HEAD); // @todo how can we get these accurate settings from memory , wifi_get_ip_info does not seem to reveal if struct ip_info is static or not page += getIpForm(FPSTR(S_ip),FPSTR(S_staticip),(_sta_static_ip ? _sta_static_ip.toString() : "")); // @token staticip @@ -1055,7 +1220,7 @@ String WiFiManager::getParamOut(){ String HTTP_PARAM_temp = FPSTR(HTTP_FORM_LABEL); HTTP_PARAM_temp += FPSTR(HTTP_FORM_PARAM); - bool tok_I = HTTP_PARAM_temp.indexOf(FPSTR(T_i)) > 0; + bool tok_I = HTTP_PARAM_temp.indexOf(FPSTR(T_I)) > 0; bool tok_i = HTTP_PARAM_temp.indexOf(FPSTR(T_i)) > 0; bool tok_n = HTTP_PARAM_temp.indexOf(FPSTR(T_n)) > 0; bool tok_p = HTTP_PARAM_temp.indexOf(FPSTR(T_p)) > 0; @@ -1064,14 +1229,15 @@ String WiFiManager::getParamOut(){ bool tok_v = HTTP_PARAM_temp.indexOf(FPSTR(T_v)) > 0; bool tok_c = HTTP_PARAM_temp.indexOf(FPSTR(T_c)) > 0; - char parLength[5]; + char valLength[5]; // add the extra parameters to the form for (int i = 0; i < _paramsCount; i++) { - if (_params[i] == NULL) { + if (_params[i] == NULL || _params[i]->_length == 0) { + DEBUG_WM(DEBUG_ERROR,"[ERROR] WiFiManagerParameter is out of scope"); break; } - // label before or after, this could probably be done via floats however + // label before or after, @todo this could be done via floats or CSS and eliminated String pitem; switch (_params[i]->getLabelPlacement()) { case WFM_LABEL_BEFORE: @@ -1088,17 +1254,19 @@ String WiFiManager::getParamOut(){ break; } + // Input templating + // "
"; // if no ID use customhtml for item, else generate from param string if (_params[i]->getID() != NULL) { - if(tok_I)pitem.replace(FPSTR(T_i), (String)FPSTR(S_parampre)+(String)i); - if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); - if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); - if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); - if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getPlaceholder()); - snprintf(parLength, 5, "%d", _params[i]->getValueLength()); - if(tok_l)pitem.replace(FPSTR(T_l), parLength); - if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); - if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // meant for additional attributes, not html + if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); // T_I id number + if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); // T_i id name + if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); // T_n id name alias + if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); // T_p replace legacy placeholder token + if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getLabel()); // T_t title/label + snprintf(valLength, 5, "%d", _params[i]->getValueLength()); + if(tok_l)pitem.replace(FPSTR(T_l), valLength); // T_l value length + if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); // T_v value + if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // T_c meant for additional attributes, not html, but can stuff } else { pitem = _params[i]->getCustomHTML(); } @@ -1130,6 +1298,11 @@ void WiFiManager::handleWifiSave() { DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); handleRequest(); + // @todo use new callback for before paramsaves + if ( _presavecallback != NULL) { + _presavecallback(); + } + //SAVE/connect here _ssid = server->arg(F("s")).c_str(); _pass = server->arg(F("p")).c_str(); @@ -1163,11 +1336,12 @@ 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); DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); - connect = true; //signal ready to connect/reset + connect = true; //signal ready to connect/reset process in processConfigPortal } void WiFiManager::handleParamSave() { @@ -1175,6 +1349,7 @@ void WiFiManager::handleParamSave() { DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); handleRequest(); + doParamSave(); String page = getHTTPHead(FPSTR(S_titleparamsaved)); // @token titleparamsaved @@ -1188,18 +1363,27 @@ void WiFiManager::handleParamSave() { } void WiFiManager::doParamSave(){ + // @todo use new callback for before paramsaves, is this really needed? + if ( _presavecallback != NULL) { + _presavecallback(); + } + //parameters if(_paramsCount > 0){ DEBUG_WM(DEBUG_VERBOSE,F("Parameters")); DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); for (int i = 0; i < _paramsCount; i++) { if (_params[i] == NULL) { - break; + break; // @todo might not be needed anymore } //read parameter from server + String name = (String)FPSTR(S_parampre)+(String)i; String value; - if(server->arg((String)FPSTR(S_parampre)+(String)i) != NULL) value = server->arg((String)FPSTR(S_parampre)+(String)i).c_str(); - else value = server->arg(_params[i]->getID()).c_str(); + if(server->hasArg(name)) { + value = server->arg(name); + } else { + value = server->arg(_params[i]->getID()); + } //store it in params array value.toCharArray(_params[i]->_value, _params[i]->_length+1); // length+1 null terminated @@ -1207,6 +1391,11 @@ void WiFiManager::doParamSave(){ } DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); } + + if ( _saveparamscallback != NULL) { + _saveparamscallback(); + } + } /** @@ -1218,8 +1407,11 @@ void WiFiManager::handleInfo() { String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo reportStatus(page); - //@todo convert to enum + uint16_t infos = 0; + + //@todo convert to enum or refactor to strings #ifdef ESP8266 + infos = 27; String infoids[] = { F("esphead"), F("uptime"), @@ -1250,28 +1442,19 @@ void WiFiManager::handleInfo() { F("autoconx") }; - for(size_t i=0; i<27;i++){ - if(infoids[i] != NULL) page += getInfoData(infoids[i]); - } - page += F(""); - #elif defined(ESP32) + infos = 22; String infoids[] = { F("esphead"), F("uptime"), F("chipid"), - F("chiprev"), // esp32 - // "fchipid)", //esp8266 - F("idesize"), //esp8266 - // "flashsize)", //esp8266 + F("chiprev"), + F("idesize"), F("sdkver"), - // "corever)", //esp8266 - // "bootver)", //esp8266 F("cpufreq"), F("freeheap"), - // "memsketch)", //esp8266 - // "memsmeter)", //esp8266 - F("lastreset"), //esp8266 + F("lastreset"), + // F("temp"), F("wifihead"), F("apip"), F("apmac"), @@ -1284,16 +1467,14 @@ void WiFiManager::handleInfo() { F("dnss"), F("host"), F("stamac"), - F("conx"), - F("autoconx") + F("conx") }; - - for(size_t i=0; i<23;i++){ - if(infoids[i] != NULL) page += getInfoData(infoids[i]); - } - page += F(""); #endif + for(size_t i=0; i"); if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); page += FPSTR(HTTP_HELP); page += FPSTR(HTTP_END); @@ -1318,7 +1499,7 @@ String WiFiManager::getInfoData(String id){ } else if(id==F("chipid")){ p = FPSTR(HTTP_INFO_chipid); - p.replace(FPSTR(T_1),(String)WIFI_getChipId()); + p.replace(FPSTR(T_1),String(WIFI_getChipId(),HEX)); } #ifdef ESP32 else if(id==F("chiprev")){ @@ -1477,10 +1658,20 @@ String WiFiManager::getInfoData(String id){ p = FPSTR(HTTP_INFO_conx); p.replace(FPSTR(T_1),WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); } + #ifdef ESP8266 else if(id==F("autoconx")){ p = FPSTR(HTTP_INFO_autoconx); p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); } + #endif + #ifdef ESP32 + else if(id==F("temp")){ + // temperature is not calibrated, varying large offsets are present, use for relative temp changes only + p = FPSTR(HTTP_INFO_temp); + p.replace(FPSTR(T_1),(String)temperatureRead()); + p.replace(FPSTR(T_2),(String)((temperatureRead()+32)*1.8)); + } + #endif return p; } @@ -1526,7 +1717,6 @@ void WiFiManager::handleErase(boolean opt) { DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Erase")); handleRequest(); String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase - page += FPSTR(HTTP_HEAD_END); bool ret = erase(opt); @@ -1654,6 +1844,18 @@ void WiFiManager::reportStatus(String &page){ * reset wifi settings, clean stored ap password */ +/** + * [stopConfigPortal description] + * @return {[type]} [description] + */ +bool WiFiManager::stopConfigPortal(){ + if(_configPortalIsBlocking){ + abort = true; + return true; + } + return shutdownConfigPortal(); +} + /** * disconnect * @access public @@ -1694,13 +1896,14 @@ bool WiFiManager::erase(bool opt){ if(opt){ DEBUG_WM("Erasing NVS"); int err; + esp_err_t err; err = nvs_flash_init(); - DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_init: ",err==ESP_OK ? (String)err : "Success"); + DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_init: ",err!=ESP_OK ? (String)err : "Success"); err = nvs_flash_erase(); - DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_erase: ", err==ESP_OK ? (String)err : "Success"); + DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_erase: ", err!=ESP_OK ? (String)err : "Success"); return err == ESP_OK; } - #else + #else (void)opt; #endif @@ -1709,14 +1912,23 @@ bool WiFiManager::erase(bool opt){ /** * [resetSettings description] + * ERASES STA CREDENTIALS * @access public */ void WiFiManager::resetSettings() { DEBUG_WM(F("SETTINGS ERASED")); - WiFi_enableSTA(true,true); - WiFi.persistent(true); - WiFi.disconnect(true); - WiFi.persistent(false); + WiFi_enableSTA(true,true); // must be sta to disconnect erase + + if (_resetcallback != NULL) + _resetcallback(); + + #ifdef ESP32 + WiFi.disconnect(true,true); + #else + WiFi.persistent(true); + WiFi.disconnect(true); + WiFi.persistent(false); + #endif } // SETTERS @@ -1827,20 +2039,58 @@ void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { /** * setAPCallback, set a callback when softap is started * @access public - * @param {[type]} void (*func)(WiFiManager* myWiFiManager) [description] + * @param {[type]} void (*func)(WiFiManager* wminstance) */ -void WiFiManager::setAPCallback( void (*func)(WiFiManager* myWiFiManager) ) { +void WiFiManager::setAPCallback( std::function func ) { _apcallback = func; } /** - * setSaveConfigCallback, set a save config callback after closing configportal - * @todo only calls if configportal stopped - * @access public - * @param {[type]} void (*func)(void) [description] + * setWebServerCallback, set a callback after webserver is reset, and before routes are setup + * if we set webserver handlers before wm, they are used and wm is not by esp webserver + * on events cannot be overrided once set, and are not mutiples + * @access public + * @param {[type]} void (*func)(void) */ -void WiFiManager::setSaveConfigCallback( void (*func)(void) ) { - _savecallback = func; +void WiFiManager::setWebServerCallback( std::function func ) { + _webservercallback = func; +} + +/** + * setSaveConfigCallback, set a save config callback after closing configportal + * @note calls only if wifi is saved or changed, or setBreakAfterConfig(true) + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setSaveConfigCallback( std::function func ) { + _savewificallback = func; +} + +/** + * setConfigResetCallback, set a callback to occur when a resetSettings() occurs + * @access public + * @param {[type]} void(*func)(void) + */ +void WiFiManager::setConfigResetCallback( std::function func ) { + _resetcallback = func; +} + +/** + * setSaveParamsCallback, set a save params callback on params save in wifi or params pages + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setSaveParamsCallback( std::function func ) { + _saveparamscallback = func; +} + +/** + * setPreSaveConfigCallback, set a callback to fire before saving wifi or params + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreSaveConfigCallback( std::function func ) { + _presavecallback = func; } /** @@ -1853,10 +2103,9 @@ void WiFiManager::setCustomHeadElement(const char* element) { _customHeadElement = element; } -//if this is true, remove duplicated Access Points - defaut true /** * toggle wifiscan hiding of duplicate ssid names - * if enabled, then the webportal wifiscan page will show all aps + * if this is false, wifiscan will remove duplicat Access Points - defaut true * @access public * @param boolean removeDuplicates [true] */ @@ -1946,8 +2195,8 @@ void WiFiManager::setWiFiAutoReconnect(boolean enabled){ * @access public * @param boolean enabled [false] */ -void WiFiManager::setCaptivePortalClientCheck(boolean enabled){ - _cpClientCheck = enabled; +void WiFiManager::setAPClientCheck(boolean enabled){ + _apClientCheck = enabled; } /** @@ -2007,11 +2256,15 @@ void WiFiManager::setShowInfoErase(boolean enabled){ /** * set menu items and order - * if param is present, it will be removed from wifi + * if param is present in menu , params will be removed from wifi page automatically + * eg. + * const char * menu[] = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); * @since $dev * @param uint8_t menu[] array of menu ids */ void WiFiManager::setMenu(const char * menu[], uint8_t size){ + // DEBUG_WM(DEBUG_VERBOSE,"setmenu array"); _menuIds.clear(); for(size_t i = 0; i < size; i++){ for(size_t j = 0; j < _nummenutokens; j++){ @@ -2021,10 +2274,20 @@ void WiFiManager::setMenu(const char * menu[], uint8_t size){ } } } - // DEBUG_WM(getMenuOut()); + // DEBUG_WM(getMenuOut()); } +/** + * setMenu with vector + * eg. + * std::vector menu = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); + * tokens can be found in _menutokens array in strings_en.h + * @shiftIncrement $dev + * @param {[type]} std::vector& menu [description] + */ void WiFiManager::setMenu(std::vector& menu){ + // DEBUG_WM(DEBUG_VERBOSE,"setmenu vector"); _menuIds.clear(); for(auto menuitem : menu ){ for(size_t j = 0; j < _nummenutokens; j++){ @@ -2072,7 +2335,23 @@ bool WiFiManager::getWiFiIsSaved(){ return WiFi_hasAutoConnect(); } +/** + * setCountry + * @since $dev + * @param String cc country code, must be defined in WiFiSetCountry, US, JP, CN + */ +void WiFiManager::setCountry(String cc){ + _wificountry = cc; +} +/** + * setClass + * @param String str body class string + */ +void WiFiManager::setClass(String str){ + _bodyClass = str; +} + // HELPERS // DEBUG @@ -2094,25 +2373,22 @@ void WiFiManager::DEBUG_WM(Generic text,Genericb textb) { template void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { - if(_debugLevel < level) return; + if(!_debug || _debugLevel < level) return; - if (_debug) { - if(_debugLevel >= DEBUG_MAX){ - _debugPort.print("MEM: "); - _debugPort.println((String)ESP.getFreeHeap()); - } - _debugPort.print("*WM: "); - if(_debugLevel == DEBUG_DEV) _debugPort.print("["+(String)level+"] "); - _debugPort.print(text); - if(textb){ - _debugPort.print(" "); - _debugPort.print(textb); - } - _debugPort.print("\n"); + if(_debugLevel >= DEBUG_MAX){ + _debugPort.print("MEM: "); + _debugPort.println((String)ESP.getFreeHeap()); } + _debugPort.print("*WM: "); + if(_debugLevel == DEBUG_DEV) _debugPort.print("["+(String)level+"] "); + _debugPort.print(text); + if(textb){ + _debugPort.print(" "); + _debugPort.print(textb); + } + _debugPort.println(); } - /** * [debugSoftAPConfig description] * @access public @@ -2199,7 +2475,7 @@ boolean WiFiManager::validApPassword(){ if (_apPassword == NULL) _apPassword = ""; if (_apPassword != "") { if (_apPassword.length() < 8 || _apPassword.length() > 63) { - DEBUG_WM(F("AccessPoint set password is INVALID")); + DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); _apPassword = ""; return false; // @todo FATAL or fallback to empty ? } @@ -2248,21 +2524,41 @@ String WiFiManager::getModeString(uint8_t mode){ return FPSTR(S_NA); } +bool WiFiManager::WiFiSetCountry(){ + bool ret = false; + #ifdef ESP32 + // @todo check if wifi is init, no idea how, doesnt seem to be exposed + if(_wificountry == "") return ret; // skip not set + else if(WiFi.getMode() == WIFI_MODE_NULL); // exception if wifi not init! + else if(_wificountry == "US") ret = esp_wifi_set_country(&WM_COUNTRY_US) == ESP_OK; + else if(_wificountry == "JP") ret = esp_wifi_set_country(&WM_COUNTRY_JP) == ESP_OK; + else if(_wificountry == "CN") ret = esp_wifi_set_country(&WM_COUNTRY_CN) == ESP_OK; + else DEBUG_WM(DEBUG_ERROR,"[ERROR] country code not found"); + + if(ret) DEBUG_WM(DEBUG_VERBOSE,"esp_wifi_set_country: " + _wificountry); + else DEBUG_WM(DEBUG_ERROR,"[ERROR] esp_wifi_set_country failed"); + #endif + return ret; +} + + // set mode ignores WiFi.persistent bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { + bool ret; #ifdef ESP8266 if((wifi_get_opmode() == (uint8) m ) && !persistent) { return true; } - bool ret; ETS_UART_INTR_DISABLE(); if(persistent) ret = wifi_set_opmode(m); else ret = wifi_set_opmode_current(m); ETS_UART_INTR_ENABLE(); - return ret; #elif defined(ESP32) - return WiFi.mode(m); // @todo persistent not implemented? + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.mode(m); // @todo persistent check persistant mode , NI + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; #endif } bool WiFiManager::WiFi_Mode(WiFiMode_t m) { @@ -2274,25 +2570,22 @@ bool WiFiManager::WiFi_Disconnect() { #ifdef ESP8266 if((WiFi.getMode() & WIFI_STA) != 0) { bool ret; - DEBUG_WM(DEBUG_DEV,F("wifi station disconnect")); + DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); ETS_UART_INTR_DISABLE(); // @todo probably not needed ret = wifi_station_disconnect(); ETS_UART_INTR_ENABLE(); return ret; } #elif defined(ESP32) - DEBUG_WM(DEBUG_DEV,F("wifi station disconnect")); - // @todo why does disconnect call these, might be needed - // WiFi.getMode(); // @todo wifiLowLevelInit(), probably not needed, for save config only - // esp_wifi_start(); // @todo can only disconnect if enabled perhaps, prevent failure, or correct for previous call ? - return esp_wifi_disconnect() == ESP_OK; - // return WiFi.disconnect(); + DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); + return WiFi.disconnect(); // not persistent atm #endif return false; } // toggle STA without persistent bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { + DEBUG_WM(DEBUG_DEV,F("WiFi station enable")); #ifdef ESP8266 WiFiMode_t newMode; WiFiMode_t currentMode = WiFi.getMode(); @@ -2311,7 +2604,11 @@ bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { return true; } #elif defined(ESP32) - return WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform + bool ret; + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; #endif } bool WiFiManager::WiFi_enableSTA(bool enable) { @@ -2336,8 +2633,12 @@ bool WiFiManager::WiFi_eraseConfig() { return true; #endif #elif defined(ESP32) + bool ret; WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! - return WiFi.disconnect(true); + WiFi.persistent(true); + ret = WiFi.disconnect(true,true); + WiFi.persistent(false); + return ret; #endif } @@ -2366,16 +2667,21 @@ String WiFiManager::WiFi_SSID(){ #ifdef ESP32 void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ - // WiFiManager _WiFiManager; - // Serial.print("WM: EVENT: ");Serial.println(event); + DEBUG_WM(DEBUG_VERBOSE,"[EVENT]",event); if(event == SYSTEM_EVENT_STA_DISCONNECTED){ - // Serial.print("WM: EVENT: WIFI_REASON: ");Serial.println(info.disconnected.reason); + DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON:",info.disconnected.reason); if(info.disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.disconnected.reason == WIFI_REASON_AUTH_FAIL){ _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail } else _lastconxresulttmp = WiFi.status(); - // if(info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) Serial.println("*WM: EVENT: WIFI_REASON: NO_AP_FOUND"); - // Serial.println("*WM: Event: SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); - WiFi.reconnect(); + if(info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON: NO_AP_FOUND"); + #ifdef esp32autoreconnect + DEBUG_WM(DEBUG_VERBOSE,"[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); + WiFi.reconnect(); + #endif + } + else if(event == SYSTEM_EVENT_SCAN_DONE){ + uint16_t scans = WiFi.scanComplete(); + WiFi_scanComplete(scans); } } #endif @@ -2384,10 +2690,11 @@ void WiFiManager::WiFi_autoReconnect(){ #ifdef ESP8266 WiFi.setAutoReconnect(_wifiAutoReconnect); #elif defined(ESP32) - if(_wifiAutoReconnect){ + // if(_wifiAutoReconnect){ DEBUG_WM(DEBUG_VERBOSE,"ESP32 event handler enabled"); - WiFi.onEvent(WiFiEvent); - } + using namespace std::placeholders; + WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); + // } #endif } diff --git a/WiFiManager.h b/WiFiManager.h index a18ccf0..5b49519 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -13,6 +13,10 @@ #ifndef WiFiManager_h #define WiFiManager_h +#ifdef ESP8266 +#include +#endif + #include // #define WM_MDNS // also set MDNS with sethostname @@ -20,8 +24,16 @@ // #define WM_ERASE_NVS // esp32 erase(true) will erase NVS // #define WM_RTC // esp32 info page will include reset reasons +#ifdef ARDUINO_ESP8266_RELEASE_2_3_0 +#warning "ARDUINO_ESP8266_RELEASE_2_3_0, some WM features disabled" +#define WM_NOASYNC // esp8266 no async scan wifi +#endif + // #include "soc/efuse_reg.h" // include to add efuse chip rev to info, getChipRevision() is almost always the same though, so not sure why it matters. +// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge, @DEPRECATED +// autoreconnect is WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 + #define WM_WEBSERVERSHIM // use webserver shim lib #ifdef ESP8266 @@ -49,12 +61,11 @@ #define WM_WIFIOPEN WIFI_AUTH_OPEN #ifndef WEBSERVER_H - #warning "WEBSERVER not implemented in espressif/esp32, see readme notes" #ifdef WM_WEBSERVERSHIM #include #else #include - // Forthcoming official + // Forthcoming official ? // https://github.com/esp8266/ESPWebServer #endif #endif @@ -94,31 +105,35 @@ class WiFiManagerParameter { Create custom parameters that can be added to the WiFiManager setup web page @id is used for HTTP queries and must not contain spaces nor other special characters */ + WiFiManagerParameter(); WiFiManagerParameter(const char *custom); - WiFiManagerParameter(const char *id, const char *placeholder); - WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length); - WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom); - WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement); + WiFiManagerParameter(const char *id, const char *label); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); ~WiFiManagerParameter(); const char *getID(); const char *getValue(); - const char *getPlaceholder(); + const char *getLabel(); + const char *getPlaceholder(); // @deprecated, use getLabel int getValueLength(); int getLabelPlacement(); const char *getCustomHTML(); void setValue(const char *defaultValue, int length); + + protected: + void init(const char *id, const char *label, const char *defaultValue, int length, const char *custom); + void init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); + private: const char *_id; - const char *_placeholder; + const char *_label; char *_value; int _length; int _labelPlacement; const char *_customHTML; - void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom); - void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement); - friend class WiFiManager; }; @@ -138,6 +153,9 @@ class WiFiManager //manually start the config portal, autoconnect does this automatically on connect failure boolean startConfigPortal(); // auto generates apname boolean startConfigPortal(char const *apName, char const *apPassword = NULL); + + //manually stop the config portal if started manually, stop immediatly if non blocking, flag abort if blocking + bool stopConfigPortal(); //manually start the web portal, autoconnect does this automatically on connect failure void startWebPortal(); @@ -159,9 +177,33 @@ class WiFiManager bool erase(); bool erase(bool opt); + //adds a custom parameter, returns false on failure + bool addParameter(WiFiManagerParameter *p); + //returns the list of Parameters + WiFiManagerParameter** getParameters(); + // returns the Parameters Count + int getParametersCount(); + + + // 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 ); + + //sets timeout before AP,webserver loop ends and exits even if there has been no setup. //useful for devices that failed to connect at some point and got stuck in a webserver loop - //in seconds setConfigPortalTimeout is a new name for setTimeout + //in seconds setConfigPortalTimeout is a new name for setTimeout, ! not used if setConfigPortalBlocking void setConfigPortalTimeout(unsigned long seconds); void setTimeout(unsigned long seconds); // @deprecated, alias @@ -171,7 +213,7 @@ class WiFiManager void setSaveConnectTimeout(unsigned long seconds); // toggle debug output void setDebugOutput(boolean debug); - //defaults to not showing anything under 8% signal quality if called + //set min quality percentage to include in scan, defaults to 8% if not specified void setMinimumSignalQuality(int quality = 8); //sets a custom ip /gateway /subnet configuration void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); @@ -179,15 +221,11 @@ class WiFiManager void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); //sets config for a static IP with DNS void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns); - //called when AP mode and config portal is started - void setAPCallback( void (*func)(WiFiManager*) ); - //called when settings have been changed and connection was successful - void setSaveConfigCallback( void (*func)(void) ); - //adds a custom parameter, returns false on failure - bool addParameter(WiFiManagerParameter *p); //if this is set, it will exit after config, even if connection is unsuccessful. void setBreakAfterConfig(boolean shouldBreak); - //if this is set, portal will be blocking and wait until save or exit, is false user must manually `process()` to handle config portal + // if this is set, portal will be blocking and wait until save or exit, + // is false user must manually `process()` to handle config portal, + // setConfigPortalTimeout is ignored in this mode, user is responsible for closing configportal void setConfigPortalBlocking(boolean shouldBlock); //if this is set, customise style void setCustomHeadElement(const char* element); @@ -201,8 +239,8 @@ class WiFiManager void setShowDnsFields(boolean alwaysShow); //if false, disable captive portal redirection void setCaptivePortalEnable(boolean enabled); - //if false, timeout captive portal even if a STA client connected (false), suggest disabling if captiveportal is open - void setCaptivePortalClientCheck(boolean enabled); + //if false, timeout captive portal even if a STA client connected to softAP (false), suggest disabling if captiveportal is open + void setAPClientCheck(boolean enabled); //if true, reset timeout when webclient connects (true), suggest disabling if captiveportal is open void setWebPortalClientCheck(boolean enabled); // if true, enable autoreconnecting @@ -234,8 +272,12 @@ class WiFiManager // debug output platform info and versioning void debugPlatformInfo(); String htmlEntities(String str); + + // set the country code for wifi settings + void setCountry(String cc); + // set body class (invert) + void setClass(String str); - private: std::unique_ptr dnsServer; #if defined(ESP32) && defined(WM_WEBSERVERSHIM) @@ -243,8 +285,10 @@ class WiFiManager #else using WM_WebServer = ESP8266WebServer; #endif - std::unique_ptr server; + + std::unique_ptr server; + private: std::vector _menuIds; std::vector _menuIdsDefault = {"wifi","info","exit"}; @@ -275,8 +319,14 @@ class WiFiManager String _wifissidprefix = FPSTR(S_ssidpre); // auto apname prefix prefix+chipid uint8_t _lastconxresult = WL_IDLE_STATUS; int _numNetworks = 0; - unsigned long _lastscan = 0; // ms + unsigned long _lastscan = 0; // ms for timing wifi scans + unsigned long _startscan = 0; // ms for timing wifi scans int _cpclosedelay = 2000; // delay before wifisave, prevents captive portal from closing to fast. + bool _cleanConnect = true; // disconnect before connect in connectwifi, increases stability on connects + + bool _disableSTA = false; // disable sta when starting ap, always + bool _disableSTAConn = true; // disable sta when starting ap, if sta is not connected ( stability ) + bool _channelSync = false; // use wifi channel when starting ap #ifdef ESP32 static uint8_t _lastconxresulttmp; // tmp var for esp32 callback @@ -292,12 +342,11 @@ class WiFiManager int _staShowDns = 0; // ternary always show dns, only if not set in code, never(cannot change dns via web!) boolean _removeDuplicateAPs = true; // remove dup aps from wifiscan boolean _shouldBreakAfterConfig = false; // stop configportal on save failure - boolean _tryWPS = false; // try WPS on save failure, unsupported boolean _configPortalIsBlocking = true; // configportal enters blocking loop boolean _enableCaptivePortal = true; // enable captive portal redirection boolean _userpersistent = true; // users preffered persistence to restore boolean _wifiAutoReconnect = true; // there is no platform getter for this, we must assume its true and make it so - boolean _cpClientCheck = false; // keep cp alive if cp have station + boolean _apClientCheck = false; // keep cp alive if ap have station boolean _webClientCheck = true; // keep cp alive if web have client boolean _scanDispOptions = false; // show percentage in scans not icons boolean _paramsInWifi = true; // show custom parameters on wifi page @@ -306,13 +355,28 @@ class WiFiManager const char * _hostname = ""; const char* _customHeadElement = ""; // store custom head element html from user + String _bodyClass = ""; // class to add to body // internal options boolean _preloadwifiscan = true; // preload wifiscan if true boolean _disableIpFields = false; // edge case, if true, showxFields(false) forces ip fields off instead of default show when set + 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; + void _begin(); + void _end(); + void setupConfigPortal(); + bool shutdownConfigPortal(); + +#ifdef NO_EXTRA_4K_HEAP + boolean _tryWPS = false; // try WPS on save failure, unsupported void startWPS(); +#endif + bool startAP(); uint8_t connectWifi(String ssid, String pass); @@ -343,7 +407,6 @@ class WiFiManager boolean captivePortal(); boolean configPortalHasTimeout(); - boolean stopConfigPortal(); uint8_t processConfigPortal(); void stopCaptivePortal(); // OTA Update handler @@ -364,11 +427,14 @@ class WiFiManager void WiFi_autoReconnect(); String WiFi_SSID(); bool WiFi_scanNetworks(); - bool WiFi_scanNetworks(bool force); + bool WiFi_scanNetworks(bool force,bool async); + bool WiFi_scanNetworks(unsigned int cachetime,bool async); bool WiFi_scanNetworks(unsigned int cachetime); + void WiFi_scanComplete(int networksFound); + bool WiFiSetCountry(); #ifdef ESP32 - static void WiFiEvent(WiFiEvent_t event, system_event_info_t info); + void WiFiEvent(WiFiEvent_t event, system_event_info_t info); #endif // output helpers @@ -413,11 +479,12 @@ class WiFiManager } wm_debuglevel_t; boolean _debug = true; - uint8_t _debugLevel = DEBUG_VERBOSE; + uint8_t _debugLevel = DEBUG_DEV; Stream& _debugPort; // debug output stream ref template void DEBUG_WM(Generic text); + template void DEBUG_WM(wm_debuglevel_t level,Generic text); template @@ -426,8 +493,13 @@ class WiFiManager void DEBUG_WM(wm_debuglevel_t level, Generic text,Genericb textb); // callbacks - void (*_apcallback)(WiFiManager*) = NULL; - void (*_savecallback)(void) = NULL; + // @todo use cb list (vector) maybe event ids, allow no return value + std::function _apcallback; + std::function _webservercallback; + std::function _savewificallback; + std::function _presavecallback; + std::function _saveparamscallback; + std::function _resetcallback; template auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { diff --git a/examples/Advanced/Advanced.ino b/examples/Advanced/Advanced.ino new file mode 100644 index 0000000..267bcbb --- /dev/null +++ b/examples/Advanced/Advanced.ino @@ -0,0 +1,133 @@ +/** + * WiFiManager advanced demo, contains advanced configurartion options + * Implements TRIGGEN_PIN button press, press for ondemand configportal, hold for 3 seconds for reset settings. + */ +#include // https://github.com/tzapu/WiFiManager + +#define TRIGGER_PIN 0 + +WiFiManager wm; // global wm instance +WiFiManagerParameter custom_field; // global param ( for non blocking w params ) + +void setup() { + Serial.begin(115200); + Serial.setDebugOutput(true); + delay(3000); + Serial.println("\n Starting"); + + pinMode(TRIGGER_PIN, INPUT); + + // wm.resetSettings(); // wipe settings + + // add a custom input field + int customFieldLength = 40; + + + // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\""); + + // test custom html input type(checkbox) + // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\" type=\"checkbox\""); // custom html type + + // test custom html(radio) + const char* custom_radio_str = "
One
Two
Three"; + new (&custom_field) WiFiManagerParameter(custom_radio_str); // custom html input + + wm.addParameter(&custom_field); + wm.setSaveParamsCallback(saveParamCallback); + + // custom menu via array or vector + // + // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (sep is seperator) (if param is in menu, params will not show up in wifi page!) + // const char* menu[] = {"wifi","info","param","sep","restart","exit"}; + // wm.setMenu(menu,6); + std::vector menu = {"wifi","info","param","sep","restart","exit"}; + wm.setMenu(menu); + + // set dark theme + wm.setClass("invert"); + + + //set static ip + // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn + // wm.setShowStaticFields(true); // force show static ip fields + // wm.setShowDnsFields(true); // force show dns field always + + // wm.setConnectTimeout(20); // how long to try to connect for before continuing + wm.setConfigPortalTimeout(30); // auto close configportal after n seconds + // wm.setCaptivePortalEnable(false); // disable captive portal redirection + // wm.setAPClientCheck(true); // avoid timeout if client connected to softap + + // wifi scan settings + // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) + // wm.setMinimumSignalQuality(20); // set min RSSI (percentage) to show in scans, null = 8% + // wm.setShowInfoErase(false); // do not show erase button on info page + // wm.setScanDispPerc(true); // show RSSI as percentage not graph icons + + // wm.setBreakAfterConfig(true); // always exit configportal even if wifi save fails + + bool res; + // res = wm.autoConnect(); // auto generated AP name from chipid + // res = wm.autoConnect("AutoConnectAP"); // anonymous ap + res = wm.autoConnect("AutoConnectAP","password"); // password protected ap + + if(!res) { + Serial.println("Failed to connect or hit timeout"); + // ESP.restart(); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } +} + +void checkButton(){ + // check for button press + if ( digitalRead(TRIGGER_PIN) == LOW ) { + // poor mans debounce/press-hold, code not ideal for production + delay(50); + if( digitalRead(TRIGGER_PIN) == LOW ){ + Serial.println("Button Pressed"); + // still holding button for 3000 ms, reset settings, code not ideaa for production + delay(3000); // reset delay hold + if( digitalRead(TRIGGER_PIN) == LOW ){ + Serial.println("Button Held"); + Serial.println("Erasing Config, restarting"); + wm.resetSettings(); + ESP.restart(); + } + + // start portal w delay + Serial.println("Starting config portal"); + wm.setConfigPortalTimeout(120); + + if (!wm.startConfigPortal("OnDemandAP","password")) { + Serial.println("failed to connect or hit timeout"); + delay(3000); + // ESP.restart(); + } else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + } + } +} + + +String getParam(String name){ + //read parameter from server, for customhmtl input + String value; + if(wm.server->hasArg(name)) { + value = wm.server->arg(name); + } + return value; +} + +void saveParamCallback(){ + Serial.println("[CALLBACK] saveParamCallback fired"); + Serial.println("PARAM customfieldid = " + getParam("customfieldid")); +} + +void loop() { + checkButton(); + // put your main code here, to run repeatedly: +} diff --git a/examples/AutoConnect/AutoConnect.ino b/examples/AutoConnect/AutoConnect.ino deleted file mode 100644 index 0f58900..0000000 --- a/examples/AutoConnect/AutoConnect.ino +++ /dev/null @@ -1,32 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - //reset saved settings - //wifiManager.resetSettings(); - - //set custom ip for portal - //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - - //fetches ssid and pass from eeprom and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - wifiManager.autoConnect("AutoConnectAP"); - //or use this for auto generated name ESP + ChipID - //wifiManager.autoConnect(); - - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino similarity index 58% rename from examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino rename to examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index 51b1d80..fea3287 100644 --- a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -8,8 +8,13 @@ //define your default values here, if there are different values in config.json, they are overwritten. char mqtt_server[40]; -char mqtt_port[6] = "8080"; -char blynk_token[34] = "YOUR_BLYNK_TOKEN"; +char mqtt_port[6] = "8080"; +char api_token[32] = "YOUR_API_TOKEN"; + +//default custom static IP +char static_ip[16] = "10.0.1.56"; +char static_gw[16] = "10.0.1.1"; +char static_sn[16] = "255.255.255.0"; //flag for saving data bool shouldSaveConfig = false; @@ -20,14 +25,9 @@ void saveConfigCallback () { shouldSaveConfig = true; } - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println(); - +void setupSpiffs(){ //clean FS, for testing - //SPIFFS.format(); + // SPIFFS.format(); //read configuration from FS json Serial.println("mounting FS..."); @@ -53,7 +53,17 @@ void setup() { strcpy(mqtt_server, json["mqtt_server"]); strcpy(mqtt_port, json["mqtt_port"]); - strcpy(blynk_token, json["blynk_token"]); + strcpy(api_token, json["api_token"]); + + // if(json["ip"]) { + // Serial.println("setting custom ip from config"); + // strcpy(static_ip, json["ip"]); + // strcpy(static_gw, json["gateway"]); + // strcpy(static_sn, json["subnet"]); + // Serial.println(static_ip); + // } else { + // Serial.println("no custom ip in config"); + // } } else { Serial.println("failed to load json config"); @@ -64,62 +74,68 @@ void setup() { Serial.println("failed to mount FS"); } //end read +} +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + setupSpiffs(); + // WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + //set config save notify callback + wm.setSaveConfigCallback(saveConfigCallback); + + // setup custom parameters + // // The extra parameters to be configured (can be either global or just in the setup) // After connecting, parameter.getValue() will get you the configured value // id/name placeholder/prompt default length WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); - WiFiManagerParameter custom_blynk_token("blynk", "blynk token", "", 0); + WiFiManagerParameter custom_api_token("api", "api token", "", 32); - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - - //set config save notify callback - wifiManager.setSaveConfigCallback(saveConfigCallback); - - //set static ip - wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - //add all your parameters here - wifiManager.addParameter(&custom_mqtt_server); - wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_blynk_token); + wm.addParameter(&custom_mqtt_server); + wm.addParameter(&custom_mqtt_port); + wm.addParameter(&custom_api_token); - //reset settings - for testing - //wifiManager.resetSettings(); + // set static ip + // IPAddress _ip,_gw,_sn; + // _ip.fromString(static_ip); + // _gw.fromString(static_gw); + // _sn.fromString(static_sn); + // wm.setSTAStaticIPConfig(_ip, _gw, _sn); - //set minimu quality of signal so it ignores AP's under that quality - //defaults to 8% - //wifiManager.setMinimumSignalQuality(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - //wifiManager.setConfigPortalTimeout(120); + //reset settings - wipe credentials for testing + //wm.resetSettings(); - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + //here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect("AutoConnectAP", "password")) { + if (!wm.autoConnect("AutoConnectAP", "password")) { Serial.println("failed to connect and hit timeout"); delay(3000); - //reset and try again, or maybe put it to deep sleep + // if we still have not connected restart and try all over again ESP.restart(); delay(5000); } + // always start configportal for a little while + // wm.setConfigPortalTimeout(60); + // wm.startConfigPortal("AutoConnectAP","password"); + //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); //read updated parameters strcpy(mqtt_server, custom_mqtt_server.getValue()); strcpy(mqtt_port, custom_mqtt_port.getValue()); - strcpy(blynk_token, custom_blynk_token.getValue()); + strcpy(api_token, custom_api_token.getValue()); //save the custom parameters to FS if (shouldSaveConfig) { @@ -127,23 +143,29 @@ void setup() { DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["mqtt_server"] = mqtt_server; - json["mqtt_port"] = mqtt_port; - json["blynk_token"] = blynk_token; + json["mqtt_port"] = mqtt_port; + json["api_token"] = api_token; + + // json["ip"] = WiFi.localIP().toString(); + // json["gateway"] = WiFi.gatewayIP().toString(); + // json["subnet"] = WiFi.subnetMask().toString(); File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } - json.printTo(Serial); + json.prettyPrintTo(Serial); json.printTo(configFile); configFile.close(); //end save + shouldSaveConfig = false; } Serial.println("local ip"); Serial.println(WiFi.localIP()); - + Serial.println(WiFi.gatewayIP()); + Serial.println(WiFi.subnetMask()); } void loop() { diff --git a/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino b/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino similarity index 66% rename from examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino rename to examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino index 3fa9bcd..35b32ed 100644 --- a/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino +++ b/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino @@ -7,10 +7,10 @@ #endif //define your default values here, if there are different values in config.json, they are overwritten. -//length should be max size + 1 char mqtt_server[40]; -char mqtt_port[6] = "8080"; -char blynk_token[33] = "YOUR_BLYNK_TOKEN"; +char mqtt_port[6] = "8080"; +char api_token[32] = "YOUR_API_TOKEN"; + //default custom static IP char static_ip[16] = "10.0.1.56"; char static_gw[16] = "10.0.1.1"; @@ -25,13 +25,9 @@ void saveConfigCallback () { shouldSaveConfig = true; } -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println(); - +void setupSpiffs(){ //clean FS, for testing - //SPIFFS.format(); + // SPIFFS.format(); //read configuration from FS json Serial.println("mounting FS..."); @@ -57,24 +53,18 @@ void setup() { strcpy(mqtt_server, json["mqtt_server"]); strcpy(mqtt_port, json["mqtt_port"]); - strcpy(blynk_token, json["blynk_token"]); + strcpy(api_token, json["api_token"]); if(json["ip"]) { Serial.println("setting custom ip from config"); - //static_ip = json["ip"]; strcpy(static_ip, json["ip"]); strcpy(static_gw, json["gateway"]); strcpy(static_sn, json["subnet"]); - //strcat(static_ip, json["ip"]); - //static_gw = json["gateway"]; - //static_sn = json["subnet"]; Serial.println(static_ip); -/* Serial.println("converting ip"); - IPAddress ip = ipFromCharArray(static_ip); - Serial.println(ip);*/ } else { Serial.println("no custom ip in config"); } + } else { Serial.println("failed to load json config"); } @@ -84,58 +74,53 @@ void setup() { Serial.println("failed to mount FS"); } //end read - Serial.println(static_ip); - Serial.println(blynk_token); - Serial.println(mqtt_server); +} +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + setupSpiffs(); + + // WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + //set config save notify callback + wm.setSaveConfigCallback(saveConfigCallback); + + // setup custom parameters + // // The extra parameters to be configured (can be either global or just in the setup) // After connecting, parameter.getValue() will get you the configured value // id/name placeholder/prompt default length WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); - WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5); - WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 34); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); + WiFiManagerParameter custom_api_token("api", "api token", "", 32); - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; + //add all your parameters here + wm.addParameter(&custom_mqtt_server); + wm.addParameter(&custom_mqtt_port); + wm.addParameter(&custom_api_token); - //set config save notify callback - wifiManager.setSaveConfigCallback(saveConfigCallback); - - //set static ip + // set static ip IPAddress _ip,_gw,_sn; _ip.fromString(static_ip); _gw.fromString(static_gw); _sn.fromString(static_sn); + wm.setSTAStaticIPConfig(_ip, _gw, _sn); - wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); - - //add all your parameters here - wifiManager.addParameter(&custom_mqtt_server); - wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_blynk_token); + //reset settings - wipe credentials for testing + //wm.resetSettings(); - //reset settings - for testing - //wifiManager.resetSettings(); - - //set minimu quality of signal so it ignores AP's under that quality - //defaults to 8% - wifiManager.setMinimumSignalQuality(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - //wifiManager.setConfigPortalTimeout(120); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + //here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect("AutoConnectAP", "password")) { + if (!wm.autoConnect("AutoConnectAP", "password")) { Serial.println("failed to connect and hit timeout"); delay(3000); - //reset and try again, or maybe put it to deep sleep + // if we still have not connected restart and try all over again ESP.restart(); delay(5000); } @@ -146,7 +131,7 @@ void setup() { //read updated parameters strcpy(mqtt_server, custom_mqtt_server.getValue()); strcpy(mqtt_port, custom_mqtt_port.getValue()); - strcpy(blynk_token, custom_blynk_token.getValue()); + strcpy(api_token, custom_api_token.getValue()); //save the custom parameters to FS if (shouldSaveConfig) { @@ -154,12 +139,12 @@ void setup() { DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["mqtt_server"] = mqtt_server; - json["mqtt_port"] = mqtt_port; - json["blynk_token"] = blynk_token; + json["mqtt_port"] = mqtt_port; + json["api_token"] = api_token; - json["ip"] = WiFi.localIP().toString(); - json["gateway"] = WiFi.gatewayIP().toString(); - json["subnet"] = WiFi.subnetMask().toString(); + json["ip"] = WiFi.localIP().toString(); + json["gateway"] = WiFi.gatewayIP().toString(); + json["subnet"] = WiFi.subnetMask().toString(); File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { @@ -170,6 +155,7 @@ void setup() { json.printTo(configFile); configFile.close(); //end save + shouldSaveConfig = false; } Serial.println("local ip"); diff --git a/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino b/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino similarity index 80% rename from examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino rename to examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino index df74e42..532ceec 100644 --- a/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino +++ b/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino @@ -1,14 +1,16 @@ +// LED will blink when in config mode + #include // https://github.com/tzapu/WiFiManager //for LED status #include Ticker ticker; +int LED = BUILTIN_LED; void tick() { //toggle state - int state = digitalRead(BUILTIN_LED); // get the current state of GPIO1 pin - digitalWrite(BUILTIN_LED, !state); // set pin to the opposite state + digitalWrite(LED, !digitalRead(LED)); // set pin to the opposite state } //gets called when WiFiManager enters configuration mode @@ -26,24 +28,24 @@ void setup() { Serial.begin(115200); //set led pin as output - pinMode(BUILTIN_LED, OUTPUT); + pinMode(LED, OUTPUT); // start ticker with 0.5 because we start in AP mode and try to connect ticker.attach(0.6, tick); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; + WiFiManager wm; //reset settings - for testing - //wifiManager.resetSettings(); + // wm.resetSettings(); //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode - wifiManager.setAPCallback(configModeCallback); + wm.setAPCallback(configModeCallback); //fetches ssid and pass and tries to connect //if it does not connect it starts an access point with the specified name //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect()) { + if (!wm.autoConnect()) { Serial.println("failed to connect and hit timeout"); //reset and try again, or maybe put it to deep sleep ESP.restart(); @@ -54,7 +56,7 @@ void setup() { Serial.println("connected...yeey :)"); ticker.detach(); //keep LED on - digitalWrite(BUILTIN_LED, LOW); + digitalWrite(LED, LOW); } void loop() { diff --git a/examples/AutoConnectWithTimeout/platformio.ini b/examples/AutoConnectWithTimeout/platformio.ini deleted file mode 100644 index 7e80288..0000000 --- a/examples/AutoConnectWithTimeout/platformio.ini +++ /dev/null @@ -1,18 +0,0 @@ -; PlatformIO Project Configuration File -; -; Build options: build flags, source filter -; Upload options: custom upload port, speed and extra flags -; Library options: dependencies, extra library storages -; Advanced options: extra scripting -; -; Please visit documentation for the other options and examples -; http://docs.platformio.org/page/projectconf.html - -[env:nodemcuv2] -platform=espressif8266 -board=nodemcuv2 -framework=arduino - -[platformio] -src_dir=AutoConnectWithTimeout -lib_dir=/Users/shawn/projects/microcontrollers/dev/libraries diff --git a/examples/Basic/Basic.ino b/examples/Basic/Basic.ino new file mode 100644 index 0000000..26ec6d4 --- /dev/null +++ b/examples/Basic/Basic.ino @@ -0,0 +1,37 @@ +#include // https://github.com/tzapu/WiFiManager + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + + // Automatically connect using saved credentials, + // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"), + // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect()) + // then goes into a blocking loop awaiting configuration and will return success result + + bool res; + // res = wm.autoConnect(); // auto generated AP name from chipid + // res = wm.autoConnect("AutoConnectAP"); // anonymous ap + res = wm.autoConnect("AutoConnectAP","password"); // password protected ap + + if(!res) { + Serial.println("Failed to connect"); + // ESP.restart(); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + +} + +void loop() { + // put your main code here, to run repeatedly: + +} diff --git a/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino new file mode 100644 index 0000000..4e14584 --- /dev/null +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -0,0 +1,208 @@ +/** + * This is a kind of unit test for DEV for now + */ +#include // https://github.com/tzapu/WiFiManager +#include + +#define TRIGGER_PIN 0 +const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; + +WiFiManager wm; +bool TEST_CP = false; // always start the configportal +bool TEST_NET = true; // do a network test, get ntp time +char ssid[] = "*************"; // your network SSID (name) +char pass[] = "********"; // your network password + +void saveWifiCallback(){ + Serial.println("[CALLBACK] saveCallback fired"); +} + +//gets called when WiFiManager enters configuration mode +void configModeCallback (WiFiManager *myWiFiManager) { + Serial.println("[CALLBACK] configModeCallback fired"); + // myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // Serial.println(WiFi.softAPIP()); + //if you used auto generated SSID, print it + // Serial.println(myWiFiManager->getConfigPortalSSID()); +} + +void saveParamCallback(){ + Serial.println("[CALLBACK] saveParamCallback fired"); + // wm.stopConfigPortal(); +} + +void bindServerCallback(){ + wm.server->on("/custom",handleRoute); + // wm.server->on("/info",handleRoute); // can override wm! +} + +void handleRoute(){ + Serial.println("[HTTP] handle route"); + wm.server->send(200, "text/plain", "hello from user code"); +} + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.setDebugOutput(true); + // delay(3000); + Serial.println("\n Starting"); + // WiFi.setSleepMode(WIFI_NONE_SLEEP); // disable sleep, can improve ap stability + + 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(); + + wm.setClass("invert"); + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep + //in seconds + // wm.setConfigPortalTimeout(600); + // wm.setConnectTimeout(5); + // wm.setShowStaticFields(true); + + WiFiManagerParameter custom_html("

This Is Custom HTML

"); // only custom html + WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); + WiFiManagerParameter custom_token("api_token", "api token", "", 16); + WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces + WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // custom input attrs (ip mask) + + // callbacks + wm.setAPCallback(configModeCallback); + wm.setWebServerCallback(bindServerCallback); + wm.setSaveConfigCallback(saveWifiCallback); + wm.setSaveParamsCallback(saveParamCallback); + + //add all your parameters here + wm.addParameter(&custom_html); + wm.addParameter(&custom_mqtt_server); + wm.addParameter(&custom_mqtt_port); + wm.addParameter(&custom_token); + wm.addParameter(&custom_tokenb); + wm.addParameter(&custom_ipaddress); + + 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 + + std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; + wm.setMenu(menu); // custom menu, pass vector + + // set static sta ip + // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // wm.setShowStaticFields(false); + // wm.setShowDnsFields(false); + + // set static ip + // wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // wm.setAPStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + + // WiFi.mode(WIFI_STA); + // const wifi_country_t COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; + // const wifi_country_t COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; + // const wifi_country_t COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; + // esp_wifi_set_country(&COUNTRY_US); + + // wm.setCountry("US"); + + wm.setConfigPortalTimeout(120); + // wm.startConfigPortal("AutoConnectAP", "password"); + + //fetches ssid and pass and tries to connect + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + + if(!wm.autoConnect("AutoConnectAP")) { + Serial.println("failed to connect and hit timeout"); + } + else if(TEST_CP) { + // start configportal always + wm.setConfigPortalTimeout(60); + wm.startConfigPortal(); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + pinMode(TRIGGER_PIN, INPUT); +} + +void loop() { + // is configuration portal requested? + if ( digitalRead(TRIGGER_PIN) == LOW ) { + Serial.println("BUTTON PRESSED"); + wm.setConfigPortalTimeout(120); + + // disable captive portal redirection + // wm.setCaptivePortalEnable(false); + + if (!wm.startConfigPortal("OnDemandAP")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + } else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + getTime(); + } + } + + if(WiFi.status() == WL_CONNECTED) getTime(); + // put your main code here, to run repeatedly: + delay(5000); +} + +void getTime() { + int tz = -5; + int dst = 0; + time_t now = time(nullptr); + unsigned timeout = 5000; + unsigned start = millis(); + configTime(tz * 3600, dst * 3600, "pool.ntp.org", "time.nist.gov"); + Serial.print("Waiting for NTP time sync: "); + while (now < 8 * 3600 * 2 ) { + delay(100); + Serial.print("."); + now = time(nullptr); + if((millis() - start) > timeout){ + Serial.println("[ERROR] Failed to get NTP time."); + return; + } + } + Serial.println(""); + struct tm timeinfo; + gmtime_r(&now, &timeinfo); + Serial.print("Current time: "); + Serial.print(asctime(&timeinfo)); +} + +void debugchipid(){ + // WiFi.mode(WIFI_STA); + // WiFi.printDiag(Serial); + // Serial.println(modes[WiFi.getMode()]); + + // ESP.eraseConfig(); + // wm.resetSettings(); + // wm.erase(true); + WiFi.mode(WIFI_AP); + // WiFi.softAP(); + WiFi.enableAP(true); + delay(500); + // esp_wifi_start(); + delay(1000); + WiFi.printDiag(Serial); + delay(60000); + ESP.restart(); + + // AP esp_267751 + // 507726A4AE30 + // ESP32 Chip ID = 507726A4AE30 +} \ No newline at end of file diff --git a/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino b/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino new file mode 100644 index 0000000..3187bec --- /dev/null +++ b/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino @@ -0,0 +1,26 @@ +#include // https://github.com/tzapu/WiFiManager +WiFiManager wm; + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + + wm.setConfigPortalBlocking(false); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + if(wm.autoConnect("AutoConnectAP")){ + Serial.println("connected...yeey :)"); + } + else { + Serial.println("Configportal running"); + } +} + +void loop() { + wm.process(); + // put your main code here, to run repeatedly: +} diff --git a/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino b/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino new file mode 100644 index 0000000..f5d4881 --- /dev/null +++ b/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino @@ -0,0 +1,35 @@ +#include // https://github.com/tzapu/WiFiManager +WiFiManager wm; +WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + wm.addParameter(&custom_mqtt_server); + wm.setConfigPortalBlocking(false); + wm.setSaveParamsCallback(saveParamsCallback); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + if(wm.autoConnect("AutoConnectAP")){ + Serial.println("connected...yeey :)"); + } + else { + Serial.println("Configportal running"); + } +} + +void loop() { + wm.process(); + // put your main code here, to run repeatedly: +} + +void saveParamsCallback () { + Serial.println("Get Params:"); + Serial.print(custom_mqtt_server.getID()); + Serial.print(" : "); + Serial.println(custom_mqtt_server.getValue()); +} diff --git a/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino new file mode 100644 index 0000000..ef8e1eb --- /dev/null +++ b/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino @@ -0,0 +1,63 @@ +/** + * OnDemandNonBlocking.ino + * example of running the webportal or configportal manually and non blocking + * trigger pin will start a webportal for 120 seconds then turn it off. + * startCP = true will start both the configportal AP and webportal + */ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +WiFiManager wm; + +unsigned int timeout = 120; // seconds to run for +unsigned int startTime = millis(); +bool portalRunning = false; +bool startCP = false; // start AP and webserver if true, else start only webserver + +void setup() { + // put your setup code here, to run once + Serial.begin(115200); + Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); +} + +void loop() { + doWiFiManager(); + // put your main code here, to run repeatedly: +} + +void doWiFiManager(){ + // is auto timeout portal running + if(portalRunning){ + wm.process(); + if((millis()-startTime) > (timeout*1000)){ + Serial.println("portaltimeout"); + portalRunning = false; + if(startCP){ + wm.stopConfigPortal(); + } + else{ + wm.stopWebPortal(); + } + } + } + + // is configuration portal requested? + if(digitalRead(TRIGGER_PIN) == LOW && (!portalRunning)) { + if(startCP){ + Serial.println("Button Pressed, Starting Config Portal"); + wm.setConfigPortalBlocking(false); + wm.startConfigPortal(); + } + else{ + Serial.println("Button Pressed, Starting Web Portal"); + wm.startWebPortal(); + } + portalRunning = true; + startTime = millis(); + } +} + + diff --git a/examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino b/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino similarity index 100% rename from examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino rename to examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino diff --git a/examples/AutoConnectWithReset/AutoConnectWithReset.ino b/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino similarity index 100% rename from examples/AutoConnectWithReset/AutoConnectWithReset.ino rename to examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino diff --git a/examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino b/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino similarity index 100% rename from examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino rename to examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino diff --git a/examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino b/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino similarity index 100% rename from examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino rename to examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino diff --git a/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino new file mode 100644 index 0000000..e9252c3 --- /dev/null +++ b/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -0,0 +1,46 @@ +/** + * OnDemandConfigPortal.ino + * example of running the configPortal AP manually, independantly from the captiveportal + * trigger pin will start a configPortal AP for 120 seconds then turn it off. + * + */ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +int timeout = 120; // seconds to run for + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); +} + +void loop() { + // is configuration portal requested? + if ( digitalRead(TRIGGER_PIN) == LOW) { + WiFiManager wm; + + //reset settings - for testing + //wifiManager.resetSettings(); + + // set configportal timeout + wm.setConfigPortalTimeout(timeout); + + if (!wm.startConfigPortal("OnDemandAP")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + //reset and try again, or maybe put it to deep sleep + ESP.restart(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + + } + + // put your main code here, to run repeatedly: +} diff --git a/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino b/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino new file mode 100644 index 0000000..d3cbe3f --- /dev/null +++ b/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino @@ -0,0 +1,50 @@ +/** + * OnDemandWebPortal.ino + * example of running the webportal (always NON blocking) + */ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +WiFiManager wm; + +bool portalRunning = false; + +void setup() { + // put your setup code here, to run once + Serial.begin(115200); + Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); +} + +void loop() { + checkButton(); + // put your main code here, to run repeatedly: +} + +void checkButton(){ + // is auto timeout portal running + if(portalRunning){ + wm.process(); + } + + // is configuration portal requested? + if(digitalRead(TRIGGER_PIN) == LOW) { + delay(50); + if(digitalRead(TRIGGER_PIN) == LOW) { + if(!portalRunning){ + Serial.println("Button Pressed, Starting Portal"); + wm.startWebPortal(); + portalRunning = true; + } + else{ + Serial.println("Button Pressed, Stopping Portal"); + wm.startWebPortal(); + portalRunning = false; + } + } + } +} + + diff --git a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino deleted file mode 100644 index c9b1fe7..0000000 --- a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ /dev/null @@ -1,125 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - -// select which pin will trigger the configuration portal when set to LOW -// ESP-01 users please note: the only pins available (0 and 2), are shared -// with the bootloader, so always set them HIGH at power-up -#define TRIGGER_PIN 0 -const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; - -WiFiManager wifiManager; - - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.setDebugOutput(true); - delay(3000); - Serial.println("\n Starting"); - - // Serial.println(modes[WiFi.getMode()]); - // WiFi.printDiag(Serial); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - - //Local intialization. Once its business is done, there is no need to keep it around - //reset settings - for testing - //wifiManager.resetSettings(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - wifiManager.setConfigPortalTimeout(20); - wifiManager.setConnectTimeout(10); - // wifiManager.setShowStaticFields(true); - - // uint8_t menu[] = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE}; - // wifiManager.setMenu(menu); - - // std::vector menu = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE,wifiManager.MENU_SEP,wifiManager.MENU_ERASE,wifiManager.MENU_EXIT}; - // wifiManager.setMenu(menu); - -// std::vector menu = {wifiManager.MENU_WIFI,wifiManager.MENU_INFO,wifiManager.MENU_PARAM,wifiManager.MENU_CLOSE,wifiManager.MENU_SEP,wifiManager.MENU_ERASE,wifiManager.MENU_EXIT}; - // wifiManager.setMenu(menu); - - - WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); - WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); - WiFiManagerParameter custom_token("api_token", "api token", "", 0); - WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); - - //add all your parameters here - wifiManager.addParameter(&custom_mqtt_server); - wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_token); - wifiManager.addParameter(&custom_tokenb); - - // MENU_WIFI = 0, - // MENU_WIFINOSCAN = 1, - // MENU_INFO = 2, - // MENU_PARAM = 3, - // MENU_CLOSE = 4, - // MENU_RESTART = 5, - // MENU_EXIT = 6, - // MENU_ERASE = 7, - // MENU_SEP = 8 - - // const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - // wifiManager.setMenu(menu,9); - - std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - wifiManager.setMenu(menu); - - //set static ip - wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - // wifiManager.setShowStaticFields(false); - // wifiManager.setShowDnsFields(false); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - if(!wifiManager.autoConnect("AutoConnectAP")) { - Serial.println("failed to connect and hit timeout"); - } - - pinMode(TRIGGER_PIN, INPUT); -} - - -void loop() { - // is configuration portal requested? - if ( digitalRead(TRIGGER_PIN) == LOW ) { - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - - //reset settings - for testing - //wifiManager.resetSettings(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - wifiManager.setConfigPortalTimeout(120); - - //it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - - //WITHOUT THIS THE AP DOES NOT SEEM TO WORK PROPERLY WITH SDK 1.5 , update to at least 1.5.1 - //WiFi.mode(WIFI_STA); - - // disable captive portal redirection - // wifiManager.setCaptivePortalEnable(false); - - if (!wifiManager.startConfigPortal("OnDemandAP")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - } else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - } - } - - // put your main code here, to run repeatedly: -} diff --git a/examples/OnDemandWebPortal/OnDemandWebPortal.ino b/examples/OnDemandWebPortal/OnDemandWebPortal.ino deleted file mode 100644 index b45e4a0..0000000 --- a/examples/OnDemandWebPortal/OnDemandWebPortal.ino +++ /dev/null @@ -1,47 +0,0 @@ -/** - * OnDemandWebPortal.ino - * example of running the webportal manually, independantly from the captiveportal - * trigger pin will start a webportal for 120 seconds then turn it off. - * - */ -#include // https://github.com/tzapu/WiFiManager - -// select which pin will trigger the configuration portal when set to LOW -// ESP-01 users please note: the only pins available (0 and 2), are shared -// with the bootloader, so always set them HIGH at power-up -#define TRIGGER_PIN 0 - -int timeout = 120; // seconds - -WiFiManager wifiManager; - -bool webportalrunning = false; -int start = millis(); - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println("\n Starting"); - pinMode(TRIGGER_PIN, INPUT_PULLUP); -} - - -void loop() { - - if(webportalrunning){ - wifiManager.process(); - if(millis()-start > timeout*1000){ - Serial.println("webportaltimeout"); - webportalrunning = false; - wifiManager.stopWebPortal(); // auto off - } - } - - // is configuration portal requested? - if ( digitalRead(TRIGGER_PIN) == LOW && !webportalrunning) { - wifiManager.startWebPortal(); - webportalrunning = true; - start = millis(); - } - // put your main code here, to run repeatedly: -} diff --git a/examples/ParamsChildClass/ParamsChildClass.ino b/examples/ParamsChildClass/ParamsChildClass.ino new file mode 100644 index 0000000..c5d991a --- /dev/null +++ b/examples/ParamsChildClass/ParamsChildClass.ino @@ -0,0 +1,140 @@ +/** + * WiFiManagerParameter child class example + */ +#include // https://github.com/tzapu/WiFiManager +#include +#include + +#define SETUP_PIN 0 + +class IPAddressParameter : public WiFiManagerParameter { +public: + IPAddressParameter(const char *id, const char *placeholder, IPAddress address) + : WiFiManagerParameter("") { + init(id, placeholder, address.toString().c_str(), 16, "", WFM_LABEL_BEFORE); + } + + bool getValue(IPAddress &ip) { + return ip.fromString(WiFiManagerParameter::getValue()); + } +}; + +class IntParameter : public WiFiManagerParameter { +public: + IntParameter(const char *id, const char *placeholder, long value, const uint8_t length = 10) + : WiFiManagerParameter("") { + init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); + } + + long getValue() { + return String(WiFiManagerParameter::getValue()).toInt(); + } +}; + +class FloatParameter : public WiFiManagerParameter { +public: + FloatParameter(const char *id, const char *placeholder, float value, const uint8_t length = 10) + : WiFiManagerParameter("") { + init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); + } + + float getValue() { + return String(WiFiManagerParameter::getValue()).toFloat(); + } +}; + +struct Settings { + float f; + int i; + char s[20]; + uint32_t ip; +} sett; + + +void setup() { + pinMode(SETUP_PIN, INPUT_PULLUP); + Serial.begin(9600); + + //Delay to push SETUP button + Serial.println("Press setup button"); + for (int sec = 3; sec > 0; sec--) { + Serial.print(sec); + Serial.print(".."); + delay(1000); + } + + EEPROM.begin( 512 ); + EEPROM.get(0, sett); + Serial.println("Settings loaded"); + + if (digitalRead(SETUP_PIN) == LOW) { + // Button pressed + Serial.println("SETUP"); + + WiFiManager wm; + + sett.s[19] = '\0'; //add null terminator at the end cause overflow + WiFiManagerParameter param_str( "str", "param_string", sett.s, 20); + FloatParameter param_float( "float", "param_float", sett.f); + IntParameter param_int( "int", "param_int", sett.i); + + IPAddress ip(sett.ip); + IPAddressParameter param_ip("ip", "param_ip", ip); + + wm.addParameter( ¶m_str ); + wm.addParameter( ¶m_float ); + wm.addParameter( ¶m_int ); + wm.addParameter( ¶m_ip ); + + //SSID & password parameters already included + wm.startConfigPortal(); + + strncpy(sett.s, param_str.getValue(), 20); + sett.s[19] = '\0'; + sett.f = param_float.getValue(); + sett.i = param_int.getValue(); + + Serial.print("String param: "); + Serial.println(sett.s); + Serial.print("Float param: "); + Serial.println(sett.f); + Serial.print("Int param: "); + Serial.println(sett.i, DEC); + + if (param_ip.getValue(ip)) { + sett.ip = ip; + + Serial.print("IP param: "); + Serial.println(ip); + } else { + Serial.println("Incorrect IP"); + } + + EEPROM.put(0, sett); + if (EEPROM.commit()) { + Serial.println("Settings saved"); + } else { + Serial.println("EEPROM error"); + } + } + else { + Serial.println("WORK"); + + //connect to saved SSID + WiFi.begin(); + + //do smth + Serial.print("String param: "); + Serial.println(sett.s); + Serial.print("Float param: "); + Serial.println(sett.f); + Serial.print("Int param: "); + Serial.println(sett.i, DEC); + Serial.print("IP param: "); + IPAddress ip(sett.ip); + Serial.println(ip); + } +} + +void loop() { +} diff --git a/extras/WiFiManager.template.html b/extras/WiFiManager.template.html index e3b6ee9..9a0b082 100644 --- a/extras/WiFiManager.template.html +++ b/extras/WiFiManager.template.html @@ -7,6 +7,25 @@ @@ -150,7 +166,7 @@ button.D{ - +
diff --git a/library.json b/library.json index 99b43c3..0ceb4c8 100644 --- a/library.json +++ b/library.json @@ -1,8 +1,20 @@ { "name": "WifiManager", - "keywords": "wifi, wi-fi", - "description": "ESP8266 WiFi Connection manager with fallback web configuration portal", - "repository": + "keywords": "wifi,wi-fi,esp,esp8266,esp32,espressif8266,espressif32,nodemcu,wemos,arduino", + "description": "WiFi Configuration manager with web configuration portal for ESP boards", +"authors": +[ + { + "name": "tzapu", + "url": "https://github.com/tzapu" + }, + { + "name": "tablatronix", + "url": "https://github.com/tablatronix", + "maintainer": true + } +], +"repository": { "type": "git", "url": "https://github.com/tzapu/WiFiManager.git" @@ -13,5 +25,5 @@ "espressif8266", "espressif32" ], - "version": "0.12" + "version": "1.0.0" } diff --git a/library.properties b/library.properties index 382a56a..5ee6e46 100644 --- a/library.properties +++ b/library.properties @@ -1,9 +1,9 @@ name=WiFiManager -version=0.12 -author=tzapu -maintainer=tzapu -sentence=WiFi Connection manager with fallback web configuration portal for ESP boards -paragraph=Library for configuring ESP8266 modules WiFi credentials at runtime. +version=1.0.0 +author=tzapu,tablatronix +maintainer=tablatronix +sentence=WiFi Configuration manager with web configuration portal for ESP boards +paragraph=Library for configuring ESP8266/ESP32 modules WiFi credentials and custom parameters at runtime. category=Communication url=https://github.com/tzapu/WiFiManager.git architectures=esp8266,esp32 diff --git a/strings_en.h b/strings_en.h index 05f0f3d..92cf235 100644 --- a/strings_en.h +++ b/strings_en.h @@ -11,15 +11,11 @@ */ #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! -// To override the strings below in your project, make the following changes above the line that includes "WiFIManager.h" -// Add the following line: -// #define WIFI_MANAGER_OVERRIDE_STRINGS -// Copy and paste ALL of the const char lines below and modify to suit. - -const char HTTP_HEAD[] PROGMEM = "{v}"; +const char HTTP_HEAD_START[] PROGMEM = "{v}"; const char HTTP_SCRIPT[] PROGMEM = ""; -const char HTTP_HEAD_END[] PROGMEM = "
"; +const char HTTP_HEAD_END[] PROGMEM = "
"; const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

"; const char * const HTTP_PORTAL_MENU[] PROGMEM = { @@ -49,7 +45,7 @@ const char HTTP_FORM_STATIC_HEAD[] PROGMEM = "

"; const char HTTP_FORM_END[] PROGMEM = "

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

"; -const char HTTP_FORM_PARAM[] PROGMEM = "
"; +const char HTTP_FORM_PARAM[] PROGMEM = "
"; const char HTTP_SCAN_LINK[] PROGMEM = "
"; const char HTTP_SAVED[] PROGMEM = "
Saving Credentials
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; @@ -71,19 +67,23 @@ const char HTTP_STYLE[] PROGMEM = ""; const char HTTP_HELP[] PROGMEM = @@ -141,7 +141,7 @@ const char HTTP_JS[] PROGMEM = #ifdef ESP32 const char HTTP_INFO_esphead[] PROGMEM = "

esp32


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

esp8266


"; @@ -173,6 +173,7 @@ const char HTTP_INFO_host[] PROGMEM = "
Hostname
{1}
"; const char HTTP_INFO_stamac[] PROGMEM = "
Station MAC
{1}
"; const char HTTP_INFO_conx[] PROGMEM = "
Connected
{1}
"; const char HTTP_INFO_autoconx[] PROGMEM = "
Autoconnect
{1}
"; +const char HTTP_INFO_temp[] PROGMEM = "
Temperature
{1} C° / {2} F°
"; // Strings const char S_y[] PROGMEM = "Yes"; @@ -254,11 +255,11 @@ const char S_dns[] PROGMEM = "dns"; // softap ssid default prefix #ifdef ESP8266 - const char S_ssidpre[] PROGMEM = "ESP"; + const char S_ssidpre[] PROGMEM = "ESP"; #elif defined(ESP32) - const char S_ssidpre[] PROGMEM = "ESP32"; + const char S_ssidpre[] PROGMEM = "ESP32"; #else - const char S_ssidpre[] PROGMEM = "WM"; + const char S_ssidpre[] PROGMEM = "WM"; #endif //Tokens @@ -285,6 +286,8 @@ const char T_h[] PROGMEM = "{h}"; // @token h const char HTTP_HEAD_CL[] PROGMEM = "Content-Length"; const char HTTP_HEAD_CT[] PROGMEM = "text/html"; const char HTTP_HEAD_CT2[] PROGMEM = "text/plain"; +const char HTTP_HEAD_CORS[] PROGMEM = "Access-Control-Allow-Origin"; +const char HTTP_HEAD_CORS_ALLOW_ALL[] PROGMEM = "*"; const char * const WIFI_STA_STATUS[] PROGMEM { @@ -324,4 +327,10 @@ const char * const AUTH_MODE_NAMES[] PROGMEM }; #endif -const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; \ No newline at end of file +const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; + +#ifdef ESP32 +const wifi_country_t WM_COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; +#endif