diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index b209e5e..2deb942 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,7 +1,5 @@ ## PLEASE TRY DEVELOPMENT BRANCH before submitting bugs on release or master, in case they were already fixed. ## -## POST SERIAL OUTPUT ! - Issues without basic info will be ignored or closed! Please fill the info fields, it helps to get you faster support ;) @@ -17,24 +15,13 @@ https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/debugging.rst ### Basic Infos #### Hardware -**WiFimanager Branch/Release:** -- [ ] Master -- [ ] Development +WiFimanager Branch/Release: Development -**Esp8266/Esp32:** -- [ ] ESP8266 -- [ ] ESP32 +Esp8266/Esp32: -**Hardware: ESP-12e, esp01, esp25** -- [ ] ESP01 -- [ ] ESP12 E/F/S (nodemcu, wemos, feather) -- [ ] Other +Hardware: ESP-12e, esp01, esp25 - -**ESP Core Version: 2.4.0, staging** -- [ ] 2.3.0 -- [ ] 2.4.0 -- [ ] staging (master/dev) +Core Version: 2.4.0, staging ### Description diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d837572 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +platformio.ini diff --git a/.travis.yml b/.travis.yml index 64fb578..d41a13b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,34 +1,51 @@ language: c +sudo: false + before_install: - "/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16" - sleep 3 - export DISPLAY=:1.0 - - wget http://downloads.arduino.cc/arduino-1.6.5-linux64.tar.xz - - tar xf arduino-1.6.5-linux64.tar.xz - - sudo mv arduino-1.6.5 /usr/local/share/arduino + - wget http://downloads.arduino.cc/arduino-1.8.5-linux64.tar.xz + - tar xf arduino-1.8.5-linux64.tar.xz + - sudo mv arduino-1.8.5 /usr/local/share/arduino - sudo ln -s /usr/local/share/arduino/arduino /usr/local/bin/arduino + install: - ln -s $PWD /usr/local/share/arduino/libraries/WiFiManager -# boards manager not working on 1.6.7 - 1.6.8 - arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json" --save-prefs -# install lib arduino json not working in 1.6.5 -# - arduino --install-library "ArduinoJson" - - git clone https://github.com/bblanchon/ArduinoJson /usr/local/share/arduino/libraries/ArduinoJson + - arduino --install-library "ArduinoJson:5.13.2" - arduino --install-boards esp8266:esp8266 - - arduino --board esp8266:esp8266:generic --save-prefs - arduino --pref "compiler.warning_level=all" --save-prefs +# install esp32 + - pushd . + - mkdir -p ~/Arduino/hardware/espressif + - cd ~/Arduino/hardware/espressif + - git clone https://github.com/espressif/arduino-esp32.git esp32 + - cd esp32 + - git submodule update --init --recursive + - cd tools + - python2 get.py + - popd +# esp32 needs WebServer_tng for now + - git clone https://github.com/bbx10/WebServer_tng.git /usr/local/share/arduino/libraries/WebServer_tng + script: - "echo $PWD" - "echo $HOME" - "ls $PWD" - source $TRAVIS_BUILD_DIR/travis/common.sh + - arduino --board esp8266:esp8266:generic:CpuFrequency=80,CrystalFreq=26,FlashFreq=40,FlashMode=qio,FlashSize=4M1M,led=2,LwIPVariant=v2mss536,Debug=Serial,DebugLevel=CORE --save-prefs + - 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 - build_examples -# - "cat $PWD/examples/AutoConnect/AutoConnect.ino" # - arduino -v --verbose-build --verify $PWD/examples/AutoConnect/AutoConnect.ino -# - arduino --verify --board arduino:avr:uno $PWD/examples/IncomingCall/IncomingCall.ino -# - arduino --verify --board arduino:avr:uno $PWD/examples/AdafruitIO_GPS/AdafruitIO_GPS.ino -after_success: - - bash <(curl -s https://codecov.io/bash) + +# no coverage generated, no need to run +# +#after_success: +# - bash <(curl -s https://codecov.io/bash) + notifications: email: on_success: change diff --git a/README.md b/README.md index 3782339..e4c3857 100644 --- a/README.md +++ b/README.md @@ -3,21 +3,34 @@ # WiFiManager ESP8266 WiFi Connection manager with fallback web configuration portal -[![Build Status](https://travis-ci.org/tzapu/WiFiManager.svg?branch=master)](https://travis-ci.org/tzapu/WiFiManager) +[![Build Status](https://travis-ci.org/tzapu/WiFiManager.svg?branch=development)](https://travis-ci.org/tzapu/WiFiManager) + +![ESP8266](https://img.shields.io/badge/ESP-8266-000000.svg?longCache=true&style=flat&colorA=CC101F) +![ESP32](https://img.shields.io/badge/ESP-32-000000.svg?longCache=true&style=flat&colorA=CC101F) The configuration portal is of the captive variety, so on various devices it will present the configuration dialogue as soon as you connect to the created access point. First attempt at a library. Lots more changes and fixes to do. Contributions are welcome. -#### This works with the ESP8266 Arduino platform with a recent stable release(2.0.0 or newer) https://github.com/esp8266/Arduino +**This works with the ESP8266 Arduino platform with a recent stable release(2.0.0 or newer)** + +[https://github.com/esp8266/Arduino](https://github.com/esp8266/Arduino) + +**This works with the ESP32 Arduino platform with staging** + +[https://github.com/espressif/arduino-esp32](https://github.com/espressif/arduino-esp32) + +### Known Issues +* Documentation needs to be updated, see [https://github.com/tzapu/WiFiManager/issues/500](https://github.com/tzapu/WiFiManager/issues/500) ## Contents - [How it works](#how-it-works) - [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) @@ -34,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) @@ -55,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 @@ -65,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) @@ -75,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; ``` @@ -184,6 +220,12 @@ void loop() { ``` See example for a more complex version. [OnDemandConfigPortal](https://github.com/tzapu/WiFiManager/tree/master/examples/OnDemandConfigPortal) +#### Exiting from the Configuration Portal +Normally, once entered, the configuration portal will continue to loop until WiFi credentials have been successfully entered or a timeout is reached. +If you'd prefer to exit without joining a WiFi network, say becuase you're going to put the ESP into AP mode, then press the "Exit" button +on the main webpage. +If started via `autoConnect` or `startConfigPortal` then it will return `false (portalAbortResult)` + #### Custom Parameters You can use WiFiManager to collect more parameters than just SSID and password. This could be helpful for configuring stuff like MQTT host and port, [blynk](http://www.blynk.cc) or [emoncms](http://emoncms.org) tokens, just to name a few. @@ -191,18 +233,18 @@ This could be helpful for configuring stuff like MQTT host and port, [blynk](htt Usage scenario would be: - load values from somewhere (EEPROM/FS) or generate some defaults - add the custom parameters to WiFiManager using - ```cpp +```cpp // id/name, placeholder/prompt, default, length WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); wifiManager.addParameter(&custom_mqtt_server); - ``` +``` - if connection to AP fails, configuration portal starts and you can set /change the values (or use on demand configuration portal) - once configuration is done and connection is established [save config callback]() is called - once WiFiManager returns control to your application, read and save the new values using the `WiFiManagerParameter` object. - ```cpp +```cpp mqtt_server = custom_mqtt_server.getValue(); - ``` +``` This feature is a lot more involved than all the others, so here are some examples to fully show how it is done. You should also take a look at adding custom HTML to your form. @@ -266,6 +308,14 @@ Debug is enabled by default on Serial. To disable add before autoConnect wifiManager.setDebugOutput(false); ``` +You can customize the debug level by changing `_debugLevel` in source +options are: +* DEBUG_ERROR +* DEBUG_NOTIFY +* DEBUG_VERBOSE +* DEBUG_DEV +* DEBUG_MAX + ## Troubleshooting If you get compilation errors, more often than not, you may need to install a newer version of the ESP8266 core for Arduino. @@ -278,6 +328,8 @@ If you connect to the created configuration Access Point but the configuration p If trying to connect ends up in an endless loop, try to add `setConnectTimeout(60)` before `autoConnect();`. The parameter is timeout to try connecting in seconds. ## Releases +#### 1.0.1 + #### 0.12 - removed 204 header response - fixed incompatibility with other libs using isnan and other std:: functions without namespace @@ -342,7 +394,11 @@ The support and help I got from the community has been nothing short of phenomen __THANK YOU__ -[Shawn A](https://github.com/tablatronix) +[Shawn A aka tablatronix](https://github.com/tablatronix) + +[bbx10](https://github.com/bbx10) + +[kentaylor](https://github.com/kentaylor) [Maximiliano Duarte](https://github.com/domonetic) @@ -368,7 +424,10 @@ __THANK YOU__ [walthercarsten](https://github.com/walthercarsten) -Sorry if i have missed anyone. +And countless others #### Inspiration -- http://www.esp8266.com/viewtopic.php?f=29&t=2520 + * http://www.esp8266.com/viewtopic.php?f=29&t=2520 + * https://github.com/chriscook8/esp-arduino-apboot + * https://github.com/esp8266/Arduino/tree/master/libraries/DNSServer/examples/CaptivePortalAdvanced + * Built by AlexT https://github.com/tzapu diff --git a/WiFiManager.cpp b/WiFiManager.cpp index c56ff05..03d5050 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1,55 +1,87 @@ -/************************************************************** - WiFiManager is a library for the ESP8266/Arduino platform - (https://github.com/esp8266/Arduino) to enable easy - configuration and reconfiguration of WiFi credentials using a Captive Portal - inspired by: - http://www.esp8266.com/viewtopic.php?f=29&t=2520 - https://github.com/chriscook8/esp-arduino-apboot - https://github.com/esp8266/Arduino/tree/master/libraries/DNSServer/examples/CaptivePortalAdvanced - Built by AlexT https://github.com/tzapu - Licensed under MIT license - **************************************************************/ +/** + * WiFiManager.cpp + * + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ #include "WiFiManager.h" -WiFiManagerParameter::WiFiManagerParameter(const char *custom) { - _id = NULL; - _placeholder = NULL; - _length = 0; - _value = NULL; +#ifdef ESP32 +uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS; +#endif - _customHTML = custom; +/** + * -------------------------------------------------------------------------------- + * WiFiManagerParameter + * -------------------------------------------------------------------------------- +**/ + +WiFiManagerParameter::WiFiManagerParameter(const char *custom) { + _id = NULL; + _placeholder = 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 *placeholder, const char *defaultValue, int length) { - init(id, placeholder, defaultValue, length, ""); + init(id, placeholder, defaultValue, length, "", WFM_LABEL_BEFORE); } WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom) { - init(id, placeholder, defaultValue, length, custom); + init(id, placeholder, defaultValue, length, custom, WFM_LABEL_BEFORE); } -void WiFiManagerParameter::init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom) { - _id = id; - _placeholder = placeholder; - _length = length; - _value = new char[length + 1]; - for (int i = 0; i < length + 1; i++) { - _value[i] = 0; - } - if (defaultValue != NULL) { - strncpy(_value, defaultValue, length); - } +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); +} - _customHTML = custom; +void WiFiManagerParameter::init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement) { + _id = id; + _placeholder = placeholder; + _labelPlacement = labelPlacement; + _customHTML = custom; + setValue(defaultValue,length); } 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) { + 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); + } +} const char* WiFiManagerParameter::getValue() { return _value; } @@ -62,402 +94,980 @@ const char* WiFiManagerParameter::getPlaceholder() { int WiFiManagerParameter::getValueLength() { return _length; } +int WiFiManagerParameter::getLabelPlacement() { + return _labelPlacement; +} const char* WiFiManagerParameter::getCustomHTML() { return _customHTML; } - -WiFiManager::WiFiManager() { - _max_params = WIFI_MANAGER_MAX_PARAMS; - _params = (WiFiManagerParameter**)malloc(_max_params * sizeof(WiFiManagerParameter*)); -} - -WiFiManager::~WiFiManager() -{ - if (_params != NULL) - { - DEBUG_WM(F("freeing allocated params!")); - free(_params); - } -} - +/** + * [addParameter description] + * @access public + * @param {[type]} WiFiManagerParameter *p [description] + */ bool WiFiManager::addParameter(WiFiManagerParameter *p) { - if(_paramsCount + 1 > _max_params) - { - // rezise the params array + + // check param id is valid, unless null + if(p->getID()){ + for (size_t i = 0; i < strlen(p->getID()); i++){ + if(!(isAlphaNumeric(p->getID()[i])) && !(p->getID()[i]=='_')){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] parameter IDs can only contain alpha numeric chars"); + return false; + } + } + } + + // init params if never malloc + if(_params == NULL){ + DEBUG_WM(DEBUG_DEV,"allocating params bytes:",_max_params * sizeof(WiFiManagerParameter*)); + _params = (WiFiManagerParameter**)malloc(_max_params * sizeof(WiFiManagerParameter*)); + } + + // resize the params array by increment of WIFI_MANAGER_MAX_PARAMS + if(_paramsCount == _max_params){ _max_params += WIFI_MANAGER_MAX_PARAMS; - DEBUG_WM(F("Increasing _max_params to:")); - DEBUG_WM(_max_params); + DEBUG_WM(DEBUG_DEV,F("Updated _max_params:"),_max_params); + DEBUG_WM(DEBUG_DEV,"re-allocating params bytes:",_max_params * sizeof(WiFiManagerParameter*)); WiFiManagerParameter** new_params = (WiFiManagerParameter**)realloc(_params, _max_params * sizeof(WiFiManagerParameter*)); + // DEBUG_WM(WIFI_MANAGER_MAX_PARAMS); + // DEBUG_WM(_paramsCount); + // DEBUG_WM(_max_params); if (new_params != NULL) { _params = new_params; } else { - DEBUG_WM(F("ERROR: failed to realloc params, size not increased!")); + DEBUG_WM(DEBUG_ERROR,"[ERROR] failed to realloc params, size not increased!"); return false; } } _params[_paramsCount] = p; _paramsCount++; - DEBUG_WM(F("Adding parameter")); - DEBUG_WM(p->getID()); + + DEBUG_WM(DEBUG_VERBOSE,"Added Parameter:",p->getID()); return true; } -void WiFiManager::setupConfigPortal() { - dnsServer.reset(new DNSServer()); - server.reset(new ESP8266WebServer(80)); - - DEBUG_WM(F("")); - _configPortalStart = millis(); - - DEBUG_WM(F("Configuring access point... ")); - DEBUG_WM(_apName); - if (_apPassword != NULL) { - if (strlen(_apPassword) < 8 || strlen(_apPassword) > 63) { - // fail passphrase to short or long! - DEBUG_WM(F("Invalid AccessPoint password. Ignoring")); - _apPassword = NULL; - } - DEBUG_WM(_apPassword); - } - - //optional soft ip config - if (_ap_static_ip) { - DEBUG_WM(F("Custom AP IP/GW/Subnet")); - WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn); - } - - if (_apPassword != NULL) { - WiFi.softAP(_apName, _apPassword);//password option - } else { - WiFi.softAP(_apName); - } - - delay(500); // Without delay I've seen the IP address blank - DEBUG_WM(F("AP IP address: ")); - DEBUG_WM(WiFi.softAPIP()); - - /* Setup the DNS server redirecting all the domains to the apIP */ - dnsServer->setErrorReplyCode(DNSReplyCode::NoError); - dnsServer->start(DNS_PORT, "*", WiFi.softAPIP()); - - /* Setup web pages: root, wifi config pages, SO captive portal detectors and not found. */ - server->on(String(F("/")), std::bind(&WiFiManager::handleRoot, this)); - server->on(String(F("/wifi")), std::bind(&WiFiManager::handleWifi, this, true)); - server->on(String(F("/0wifi")), std::bind(&WiFiManager::handleWifi, this, false)); - server->on(String(F("/wifisave")), std::bind(&WiFiManager::handleWifiSave, this)); - server->on(String(F("/i")), std::bind(&WiFiManager::handleInfo, this)); - server->on(String(F("/r")), std::bind(&WiFiManager::handleReset, this)); - //server->on("/generate_204", std::bind(&WiFiManager::handle204, this)); //Android/Chrome OS captive portal check. - server->on(String(F("/fwlink")), std::bind(&WiFiManager::handleRoot, this)); //Microsoft captive portal. Maybe not needed. Might be handled by notFound handler. - server->onNotFound (std::bind(&WiFiManager::handleNotFound, this)); - server->begin(); // Web server start - DEBUG_WM(F("HTTP server started")); - +/** + * [getParameters description] + * @access public + */ +WiFiManagerParameter** WiFiManager::getParameters() { + return _params; } +/** + * [getParametersCount description] + * @access public + */ +int WiFiManager::getParametersCount() { + return _paramsCount; +} + +/** + * -------------------------------------------------------------------------------- + * WiFiManager + * -------------------------------------------------------------------------------- +**/ + +// constructors +WiFiManager::WiFiManager(Stream& consolePort):_debugPort(consolePort){ + WiFiManagerInit(); +} + +WiFiManager::WiFiManager():WiFiManager(Serial) { +} + +void WiFiManager::WiFiManagerInit(){ + setMenu(_menuIdsDefault); + if(_debug && _debugLevel > DEBUG_DEV) debugPlatformInfo(); + _max_params = WIFI_MANAGER_MAX_PARAMS; +} + +// destructor +WiFiManager::~WiFiManager() { + _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 = "ESP" + String(ESP.getChipId()); + String ssid = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); return autoConnect(ssid.c_str(), NULL); } +/** + * [autoConnect description] + * @access public + * @param {[type]} char const *apName [description] + * @param {[type]} char const *apPassword [description] + * @return {[type]} [description] + */ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { - DEBUG_WM(F("")); DEBUG_WM(F("AutoConnect")); + _begin(); - // read eeprom for ssid and pass - //String ssid = getSSID(); - //String pass = getPassword(); + // attempt to connect using saved settings, on fail fallback to AP config portal + if(!WiFi.enableSTA(true)){ + // handle failure mode Brownout detector etc. + DEBUG_WM(DEBUG_ERROR,"[FATAL] Unable to enable wifi!"); + return false; + } + + WiFiSetCountry(); - // attempt to connect; should it fail, fall back to AP - WiFi.mode(WIFI_STA); + #ifdef ESP32 + if(esp32persistent) WiFi.persistent(false); // disable persistent for esp32 after esp_wifi_start or else saves wont work + #endif - if (connectWifi("", "") == WL_CONNECTED) { - DEBUG_WM(F("IP Address:")); - DEBUG_WM(WiFi.localIP()); + _usermode = WIFI_STA; + + // no getter for autoreconnectpolicy before this + // https://github.com/esp8266/Arduino/pull/4359 + // so we must force it on else, if not connectimeout then waitforconnectionresult gets stuck endless loop + WiFi_autoReconnect(); + + // set hostname before stating + if((String)_hostname != ""){ + DEBUG_WM(DEBUG_VERBOSE,"Setting hostname:",_hostname); + bool res = true; + #ifdef ESP8266 + res = WiFi.hostname(_hostname); + #ifdef ESP8266MDNS_H + DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname"); + if(MDNS.begin(_hostname)){ + MDNS.addService("http", "tcp", 80); + } + #endif + #elif defined(ESP32) + // @note hostname must be set after STA_START + delay(200); // do not remove, give time for STA_START + res = WiFi.setHostname(_hostname); + #ifdef ESP32MDNS_H + DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname"); + if(MDNS.begin(_hostname)){ + MDNS.addService("http", "tcp", 80); + } + #endif + #endif + + if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: set failed!")); + + if(WiFi.status() == WL_CONNECTED){ + DEBUG_WM(DEBUG_VERBOSE,F("reconnecting to set new hostname")); + // WiFi.reconnect(); // This does not reset dhcp + WiFi_Disconnect(); + delay(200); // do not remove, need a delay for disconnect to change status() + } + } + + // if already connected, or try stored connect + // @note @todo ESP32 has no autoconnect, so connectwifi will always be called unless user called begin etc before + // @todo check if correct ssid == saved ssid when already connected + bool connected = false; + if (WiFi.status() == WL_CONNECTED){ + connected = true; + DEBUG_WM(F("AutoConnect: ESP Already Connected")); + setSTAConfig(); + } + + if(connected || connectWifi("", "") == WL_CONNECTED){ //connected + DEBUG_WM(F("AutoConnect: SUCCESS")); + DEBUG_WM(F("STA IP Address:"),WiFi.localIP()); + _lastconxresult = WL_CONNECTED; + + if((String)_hostname != ""){ + #ifdef ESP8266 + DEBUG_WM(DEBUG_DEV,"hostname: STA",WiFi.hostname()); + #elif defined(ESP32) + DEBUG_WM(DEBUG_DEV,"hostname: STA",WiFi.getHostname()); + #endif + } return true; } + // possibly skip the config portal + if (!_enableConfigPortal) { + return false; + } + + DEBUG_WM(F("AutoConnect: FAILED")); + + // not connected start configportal return startConfigPortal(apName, apPassword); } -boolean WiFiManager::configPortalHasTimeout(){ - if(_configPortalTimeout == 0 || wifi_softap_get_station_num() > 0){ - _configPortalStart = millis(); // kludge, bump configportal start time to skew timeouts - return false; - } - return (millis() > _configPortalStart + _configPortalTimeout); -} +// CONFIG PORTAL +bool WiFiManager::startAP(){ + bool ret = true; + DEBUG_WM(F("StartAP with SSID: "),_apName); -boolean WiFiManager::startConfigPortal() { - String ssid = "ESP" + String(ESP.getChipId()); - return startConfigPortal(ssid.c_str(), NULL); -} - -boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { - - if(!WiFi.isConnected()){ - WiFi.persistent(false); - // disconnect sta, start ap - WiFi.disconnect(); // this alone is not enough to stop the autoconnecter - WiFi.mode(WIFI_AP); - WiFi.persistent(true); - } - else { - //setup AP - WiFi.mode(WIFI_AP_STA); - DEBUG_WM(F("SET AP STA")); - } - - - _apName = apName; - _apPassword = apPassword; - - //notify we entered AP mode + // do AP callback if set if ( _apcallback != NULL) { _apcallback(this); } - connect = false; - setupConfigPortal(); - - while(1){ - - // check if timeout - if(configPortalHasTimeout()) break; - - //DNS - dnsServer->processNextRequest(); - //HTTP - server->handleClient(); - - - if (connect) { - connect = false; - delay(2000); - DEBUG_WM(F("Connecting to new AP")); - - // using user-provided _ssid, _pass in place of system-stored ssid and pass - if (connectWifi(_ssid, _pass) != WL_CONNECTED) { - DEBUG_WM(F("Failed to connect.")); - } else { - //connected - WiFi.mode(WIFI_STA); - //notify that configuration has changed and any optional parameters should be saved - if ( _savecallback != NULL) { - //todo: check if any custom parameters actually exist, and check if they really changed maybe - _savecallback(); - } - break; - } - - if (_shouldBreakAfterConfig) { - //flag set to exit after config after trying to connect - //notify that configuration has changed and any optional parameters should be saved - if ( _savecallback != NULL) { - //todo: check if any custom parameters actually exist, and check if they really changed maybe - _savecallback(); - } - break; - } + #ifdef ESP8266 + // @bug workaround for bug #4372 https://github.com/esp8266/Arduino/issues/4372 + if(!WiFi.enableAP(true)) { + DEBUG_WM(DEBUG_ERROR,"[ERROR] enableAP failed!"); + return false; + } + delay(500); // workaround delay + #endif + + // 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!"); } - yield(); } - server.reset(); - dnsServer.reset(); - return WiFi.status() == WL_CONNECTED; + if(_channelSync){ + DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",WiFi.channel()); + } + + // start soft AP with password or anonymous + if (_apPassword != "") { + if(_channelSync){ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),WiFi.channel()); + } + else{ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str());//password option + } + } else { + DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!")); + if(_channelSync){ + ret = WiFi.softAP(_apName.c_str(),"",WiFi.channel()); + } + else{ + ret = WiFi.softAP(_apName.c_str()); + } + } + + if(_debugLevel > DEBUG_DEV) debugSoftAPConfig(); + + if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] There was a problem starting the AP"); + // @todo add softAP retry here + + delay(500); // slight delay to make sure we get an AP IP + DEBUG_WM(F("AP IP address:"),WiFi.softAPIP()); + + // set ap hostname + #ifdef ESP32 + if(ret && (String)_hostname != ""){ + DEBUG_WM(DEBUG_VERBOSE,"setting softAP Hostname:",_hostname); + bool res = WiFi.softAPsetHostname(_hostname); + if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: AP set failed!")); + DEBUG_WM(DEBUG_DEV,F("hostname: AP"),WiFi.softAPgetHostname()); + } + #endif + + return ret; } +/** + * [startWebPortal description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::startWebPortal() { + if(configPortalActive || webPortalActive) return; + setupConfigPortal(); + webPortalActive = true; +} -int WiFiManager::connectWifi(String ssid, String pass) { - DEBUG_WM(F("Connecting as wifi client...")); +/** + * [stopWebPortal description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::stopWebPortal() { + if(!configPortalActive && !webPortalActive) return; + DEBUG_WM(DEBUG_VERBOSE,F("Stopping Web Portal")); + webPortalActive = false; + stopConfigPortal(); +} - // check if we've got static_ip settings, if we do, use those. - if (_sta_static_ip) { - DEBUG_WM(F("Custom STA IP/GW/Subnet")); - WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn); - DEBUG_WM(WiFi.localIP()); +boolean WiFiManager::configPortalHasTimeout(){ + + if(_configPortalTimeout == 0 || (_cpClientCheck && (WiFi_softap_num_stations() > 0))){ + if(millis() - timer > 30000){ + timer = millis(); + DEBUG_WM(DEBUG_VERBOSE,"NUM CLIENTS: " + (String)WiFi_softap_num_stations()); + } + _configPortalStart = millis(); // kludge, bump configportal start time to skew timeouts + return false; + } + // handle timeout + if(_webClientCheck && (_webPortalAccessed>_configPortalStart)>0) _configPortalStart = _webPortalAccessed; + + if(millis() > _configPortalStart + _configPortalTimeout){ + DEBUG_WM(F("config portal has timed out")); + return true; + } else if(_debugLevel > 0) { + // log timeout + if(_debug){ + uint16_t logintvl = 30000; // how often to emit timeing out counter logging + if((millis() - timer) > logintvl){ + timer = millis(); + DEBUG_WM(DEBUG_VERBOSE,F("Portal Timeout In"),(String)((_configPortalStart + _configPortalTimeout-millis())/1000) + (String)F(" seconds")); + } + } + } + + return false; +} + +void WiFiManager::setupConfigPortal() { + + DEBUG_WM(F("Starting Web Portal")); + + // setup dns and web servers + dnsServer.reset(new DNSServer()); + server.reset(new WM_WebServer(80)); + + /* Setup the DNS server redirecting all the domains to the apIP */ + dnsServer->setErrorReplyCode(DNSReplyCode::NoError); + // DEBUG_WM("dns server started port: ",DNS_PORT); + DEBUG_WM(DEBUG_DEV,"dns server started with ip: ",WiFi.softAPIP()); + dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); + + /* Setup httpd callbacks, web pages: root, wifi config pages, SO captive portal detectors and not found. */ + server->on(String(FPSTR(R_root)).c_str(), std::bind(&WiFiManager::handleRoot, this)); + server->on(String(FPSTR(R_wifi)).c_str(), std::bind(&WiFiManager::handleWifi, this, true)); + server->on(String(FPSTR(R_wifinoscan)).c_str(), std::bind(&WiFiManager::handleWifi, this, false)); + server->on(String(FPSTR(R_wifisave)).c_str(), std::bind(&WiFiManager::handleWifiSave, this)); + server->on(String(FPSTR(R_info)).c_str(), std::bind(&WiFiManager::handleInfo, this)); + server->on(String(FPSTR(R_param)).c_str(), std::bind(&WiFiManager::handleParam, this)); + server->on(String(FPSTR(R_paramsave)).c_str(), std::bind(&WiFiManager::handleParamSave, this)); + server->on(String(FPSTR(R_restart)).c_str(), std::bind(&WiFiManager::handleReset, this)); + server->on(String(FPSTR(R_exit)).c_str(), std::bind(&WiFiManager::handleExit, this)); + server->on(String(FPSTR(R_close)).c_str(), std::bind(&WiFiManager::handleClose, this)); + server->on(String(FPSTR(R_erase)).c_str(), std::bind(&WiFiManager::handleErase, this, false)); + server->on(String(FPSTR(R_status)).c_str(), std::bind(&WiFiManager::handleWiFiStatus, this)); + server->onNotFound (std::bind(&WiFiManager::handleNotFound, this)); + + server->begin(); // Web server start + DEBUG_WM(DEBUG_VERBOSE,F("HTTP server started")); + + if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan , async +} + +boolean WiFiManager::startConfigPortal() { + String ssid = _wifissidprefix + "_" + String(WIFI_getChipId(),HEX); + return startConfigPortal(ssid.c_str(), NULL); +} + +/** + * [startConfigPortal description] + * @access public + * @param {[type]} char const *apName [description] + * @param {[type]} char const *apPassword [description] + * @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(),HEX); + if(!validApPassword()) return false; + + // HANDLE issues with STA connections, shutdown sta if not connected, or else this will hang channel scanning and softap will not respond + // @todo sometimes still cannot connect to AP for no known reason, no events in log either + if(_disableSTA || (!WiFi.isConnected() && _disableSTAConn)){ + // this fixes most ap problems, however, simply doing mode(WIFI_AP) does not work if sta connection is hanging, must `wifi_station_disconnect` + WiFi_Disconnect(); + WiFi_enableSTA(false); + DEBUG_WM(DEBUG_VERBOSE,F("Disabling STA")); } - //fix for auto connect racing issue - if (WiFi.status() == WL_CONNECTED) { - DEBUG_WM(F("Already connected. Bailing out.")); - return WL_CONNECTED; + else { + // @todo even if sta is connected, it is possible that softap connections will fail, IOS says "invalid password", windows says "cannot connect to this network" researching + WiFi_enableSTA(true); } - //check if we have ssid and pass and force those, if not, try with last saved values + + // init configportal globals to known states + configPortalActive = true; + bool result = connect = abort = false; // loop flags, connect true success, abort true break + uint8_t state; + + _configPortalStart = millis(); + + // start access point + DEBUG_WM(DEBUG_VERBOSE,F("Enabling AP")); + startAP(); + WiFiSetCountry(); + + // init configportal + DEBUG_WM(DEBUG_DEV,F("setupConfigPortal")); + setupConfigPortal(); + + if(!_configPortalIsBlocking){ + DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, non blocking/processing")); + return result; + } + + DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, blocking, waiting for clients...")); + // blocking loop waiting for config + while(1){ + + // if timed out or abort, break + if(configPortalHasTimeout() || abort){ + DEBUG_WM(DEBUG_DEV,F("configportal abort")); + stopConfigPortal(); + result = abort ? portalAbortResult : portalTimeoutResult; // false, false + break; + } + + state = processConfigPortal(); + + // status change, break + if(state != WL_IDLE_STATUS){ + result = (state == WL_CONNECTED); // true if connected + break; + } + + yield(); // watchdog + } + + DEBUG_WM(DEBUG_NOTIFY,F("config portal exiting")); + return result; +} + +/** + * [process description] + * @access public + * @return {[type]} [description] + */ +boolean WiFiManager::process(){ + if(webPortalActive || (configPortalActive && !_configPortalIsBlocking)){ + uint8_t state = processConfigPortal(); + return state == WL_CONNECTED; + } + return false; +} + +//using esp enums returns for now, should be fine +uint8_t WiFiManager::processConfigPortal(){ + //DNS handler + dnsServer->processNextRequest(); + //HTTP handler + server->handleClient(); + + // Waiting for save... + if(connect) { + connect = false; + DEBUG_WM(DEBUG_VERBOSE,F("process connect")); + if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast. + + // skip wifi if no ssid + if(_ssid == ""){ + DEBUG_WM(DEBUG_VERBOSE,F("No ssid, skipping wifi")); + } + else{ + // attempt sta connection to submitted _ssid, _pass + if (connectWifi(_ssid, _pass) == WL_CONNECTED) { + + DEBUG_WM(F("Connect to new AP [SUCCESS]")); + DEBUG_WM(F("Got IP Address:")); + DEBUG_WM(WiFi.localIP()); + + if ( _savecallback != NULL) { + _savecallback(); + } + stopConfigPortal(); + return WL_CONNECTED; // CONNECT SUCCESS + } + DEBUG_WM(DEBUG_ERROR,F("[ERROR] Connect to new AP Failed")); + } + + if (_shouldBreakAfterConfig) { + // do save callback + // @todo this is more of an exiting callback than a save, clarify when this should actually occur + // confirm or verify data was saved to make this more accurate callback + if ( _savecallback != NULL) { + _savecallback(); + } + stopConfigPortal(); + return WL_CONNECT_FAILED; // CONNECT FAIL + } + else{ + // clear save strings + _ssid = ""; + _pass = ""; + // if connect fails, turn sta off to stabilize AP + WiFi_Disconnect(); + WiFi_enableSTA(false); + DEBUG_WM(DEBUG_VERBOSE,F("Disabling STA")); + } + } + + return WL_IDLE_STATUS; +} + +/** + * [stopConfigPortal description] + * @access public + * @return {[type]} [description] + */ +boolean WiFiManager::stopConfigPortal(){ + if(webPortalActive) return false; + + //DNS handler + dnsServer->processNextRequest(); + //HTTP handler + server->handleClient(); + + // @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 + // @todo bug workaround + // https://github.com/esp8266/Arduino/issues/3793 + // [APdisconnect] set_config failed! *WM: disconnect configportal - softAPdisconnect failed + // still no way to reproduce reliably + DEBUG_WM(DEBUG_VERBOSE,F("disconnect configportal")); + bool ret = false; + ret = WiFi.softAPdisconnect(false); + if(!ret)DEBUG_WM(DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); + 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; +} + +// @todo refactor this up into seperate functions +// one for connecting to flash , one for new client +// clean up, flow is convoluted, and causes bugs +uint8_t WiFiManager::connectWifi(String ssid, String pass) { + DEBUG_WM(DEBUG_VERBOSE,F("Connecting as wifi client...")); + + uint8_t connRes = (uint8_t)WL_NO_SSID_AVAIL; + + setSTAConfig(); + //@todo catch failures in set_config + + // make sure sta is on before `begin` so it does not call enablesta->mode while persistent is ON ( which would save WM AP state to eeprom !) + if(_cleanConnect) WiFi_Disconnect(); // disconnect before begin, in case anything is hung, this causes a 2 seconds delay for connect + // @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 != "") { - WiFi.begin(ssid.c_str(), pass.c_str()); - } else { - if (WiFi.SSID()) { - DEBUG_WM(F("Using last saved values, should be faster")); - //trying to fix connection in progress hanging - ETS_UART_INTR_DISABLE(); - wifi_station_disconnect(); - ETS_UART_INTR_ENABLE(); - - WiFi.begin(); - } else { - DEBUG_WM(F("No saved credentials")); + wifiConnectNew(ssid,pass); + if(_saveTimeout > 0){ + connRes = waitForConnectResult(_saveTimeout); // use default save timeout for saves to prevent bugs in esp->waitforconnectresult loop + } + else { + connRes = waitForConnectResult(0); + } + } + else { + // connect using saved ssid if there is one + if (WiFi_hasAutoConnect()) { + wifiConnectDefault(); + connRes = waitForConnectResult(); + } + else { + DEBUG_WM(F("No saved credentials, skipping wifi")); } } - int connRes = waitForConnectResult(); - DEBUG_WM ("Connection result: "); - DEBUG_WM ( connRes ); - //not connected, WPS enabled, no pass - first attempt - #ifdef NO_EXTRA_4K_HEAP + 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 == "") { startWPS(); - //should be connected at the end of WPS + // should be connected at the end of WPS connRes = waitForConnectResult(); } - #endif +#endif + + if(connRes != WL_SCAN_COMPLETED){ + updateConxResult(connRes); + } + return connRes; } -uint8_t WiFiManager::waitForConnectResult() { - if (_connectTimeout == 0) { - return WiFi.waitForConnectResult(); - } else { - DEBUG_WM (F("Waiting for connection result with time out")); - unsigned long start = millis(); - boolean keepConnecting = true; - uint8_t status; - while (keepConnecting) { - status = WiFi.status(); - if (millis() > start + _connectTimeout) { - keepConnecting = false; - DEBUG_WM (F("Connection timed out")); - } - if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) { - keepConnecting = false; - } - delay(100); - } - return status; - } +/** + * connect to a new wifi ap + * @since $dev + * @param String ssid + * @param String pass + * @return bool success + */ +bool WiFiManager::wifiConnectNew(String ssid, String pass){ + bool ret = false; + DEBUG_WM(F("Connecting to new AP:"),ssid); + WiFi_enableSTA(true,storeSTAmode); // storeSTAmode will also toggle STA on in default opmode (persistent) if true (default) + WiFi.persistent(true); + ret = WiFi.begin(ssid.c_str(), pass.c_str()); + WiFi.persistent(false); + if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed"); + return ret; } +/** + * connect to stored wifi + * @since dev + * @return bool success + */ +bool WiFiManager::wifiConnectDefault(){ + bool ret = false; + DEBUG_WM(F("Connecting to saved AP:"),WiFi_SSID()); + ret = WiFi_enableSTA(true,storeSTAmode); + if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi enableSta failed"); + ret = WiFi.begin(); + if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed"); + return ret; +} + + +/** + * set sta config if set + * @since $dev + * @return bool success + */ +bool WiFiManager::setSTAConfig(){ + bool ret = true; + if (_sta_static_ip) { + if(_sta_static_dns) { + DEBUG_WM(DEBUG_VERBOSE,F("Custom STA IP/GW/Subnet/DNS")); + ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn, _sta_static_dns); + } + else { + DEBUG_WM(DEBUG_VERBOSE,F("Custom STA IP/GW/Subnet")); + ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn); + } + + if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi config failed"); + else DEBUG_WM(F("STA IP set:"),WiFi.localIP()); + } else { + DEBUG_WM(DEBUG_VERBOSE,F("setSTAConfig static ip not set")); + } + return ret; +} + +// @todo change to getLastFailureReason and do not touch conxresult +void WiFiManager::updateConxResult(uint8_t status){ + // hack in wrong password detection + _lastconxresult = status; + #ifdef ESP8266 + if(_lastconxresult == WL_CONNECT_FAILED){ + if(wifi_station_get_connect_status() == STATION_WRONG_PASSWORD){ + _lastconxresult = WL_STATION_WRONG_PASSWORD; + } + } + #elif defined(ESP32) + // if(_lastconxresult == WL_CONNECT_FAILED){ + if(_lastconxresult == WL_CONNECT_FAILED || _lastconxresult == WL_DISCONNECTED){ + DEBUG_WM(DEBUG_DEV,"lastconxresulttmp:",getWLStatusString(_lastconxresulttmp)); + if(_lastconxresulttmp != WL_IDLE_STATUS){ + _lastconxresult = _lastconxresulttmp; + // _lastconxresulttmp = WL_IDLE_STATUS; + } + } + #endif + DEBUG_WM(DEBUG_DEV,"lastconxresult:",getWLStatusString(_lastconxresult)); +} + + +uint8_t WiFiManager::waitForConnectResult() { + if(_connectTimeout > 0) DEBUG_WM(DEBUG_VERBOSE,_connectTimeout,F("ms connectTimeout set")); + return waitForConnectResult(_connectTimeout); +} + +/** + * waitForConnectResult + * @param uint16_t timeout in seconds + * @return uint8_t WL Status + */ +uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) { + if (timeout == 0){ + DEBUG_WM(F("connectTimeout not set, ESP waitForConnectResult...")); + return WiFi.waitForConnectResult(); + } + + unsigned long timeoutmillis = millis() + timeout; + DEBUG_WM(DEBUG_VERBOSE,timeout,F("ms timeout, waiting for connect...")); + uint8_t status = WiFi.status(); + + while(millis() < timeoutmillis) { + status = WiFi.status(); + // @todo detect additional states, connect happens, then dhcp then get ip, there is some delay here, make sure not to timeout if waiting on IP + if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) { + return status; + } + DEBUG_WM (DEBUG_VERBOSE,F(".")); + delay(100); + } + return status; +} + +// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 +#ifdef NO_EXTRA_4K_HEAP void WiFiManager::startWPS() { DEBUG_WM(F("START WPS")); - WiFi.beginWPSConfig(); + #ifdef ESP8266 + WiFi.beginWPSConfig(); + #else + // @todo + #endif DEBUG_WM(F("END WPS")); } -/* - String WiFiManager::getSSID() { - if (_ssid == "") { - DEBUG_WM(F("Reading SSID")); - _ssid = WiFi.SSID(); - DEBUG_WM(F("SSID: ")); - DEBUG_WM(_ssid); - } - return _ssid; - } +#endif - String WiFiManager::getPassword() { - if (_pass == "") { - DEBUG_WM(F("Reading Password")); - _pass = WiFi.psk(); - DEBUG_WM("Password: " + _pass); - //DEBUG_WM(_pass); - } - return _pass; - } -*/ -String WiFiManager::getConfigPortalSSID() { - return _apName; -} - -void WiFiManager::resetSettings() { - DEBUG_WM(F("settings invalidated")); - DEBUG_WM(F("THIS MAY CAUSE AP NOT TO START UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA.")); - WiFi.disconnect(true); - if (_resetcallback != NULL) - _resetcallback(); - //delay(200); -} -void WiFiManager::setTimeout(unsigned long seconds) { - setConfigPortalTimeout(seconds); -} - -void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { - _configPortalTimeout = seconds * 1000; -} - -void WiFiManager::setConnectTimeout(unsigned long seconds) { - _connectTimeout = seconds * 1000; -} - -void WiFiManager::setDebugOutput(boolean debug) { - _debug = debug; -} - -void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { - _ap_static_ip = ip; - _ap_static_gw = gw; - _ap_static_sn = sn; -} - -void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { - _sta_static_ip = ip; - _sta_static_gw = gw; - _sta_static_sn = sn; -} - -void WiFiManager::setMinimumSignalQuality(int quality) { - _minimumQuality = quality; -} - -void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { - _shouldBreakAfterConfig = shouldBreak; -} - -/** Handle root or redirect to captive portal */ -void WiFiManager::handleRoot() { - DEBUG_WM(F("Handle root")); - if (captivePortal()) { // If caprive portal redirect instead of displaying the page. - return; - } - - String page = FPSTR(HTTP_HEAD); - page.replace("{v}", "Options"); +String WiFiManager::getHTTPHead(String title){ + String page; + 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); - page += String(F("

")); - page += _apName; - page += String(F("

")); - page += String(F("

WiFiManager

")); + + 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; +} + +/** + * HTTPD handler for page requests + */ +void WiFiManager::handleRequest() { + _webPortalAccessed = millis(); +} + +/** + * HTTPD CALLBACK root or redirect to captive portal + */ +void WiFiManager::handleRoot() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Root")); + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + handleRequest(); + String page = getHTTPHead(FPSTR(S_options)); // @token options + String str = FPSTR(HTTP_ROOT_MAIN); + str.replace(FPSTR(T_v),configPortalActive ? _apName : WiFi.localIP().toString()); // use ip if ap is not active for heading + page += str; page += FPSTR(HTTP_PORTAL_OPTIONS); + page += getMenuOut(); + reportStatus(page); page += FPSTR(HTTP_END); - server->sendHeader("Content-Length", String(page.length())); - server->send(200, "text/html", page); - + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + // server->close(); // testing reliability fix for content length mismatches during mutiple flood hits WiFi_scanNetworks(); // preload wifiscan + if(_preloadwifiscan) WiFi_scanNetworks((unsigned)20000,true); // preload wifiscan throttled, async + // @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 } -/** Wifi config page handler */ +/** + * HTTPD CALLBACK Wifi config page handler + */ void WiFiManager::handleWifi(boolean scan) { - - String page = FPSTR(HTTP_HEAD); - page.replace("{v}", "Config ESP"); - page += FPSTR(HTTP_SCRIPT); - page += FPSTR(HTTP_STYLE); - page += _customHeadElement; - page += FPSTR(HTTP_HEAD_END); - + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Wifi")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi if (scan) { - int n = WiFi.scanNetworks(); - DEBUG_WM(F("Scan done")); + // 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 = ""; + + pitem = FPSTR(HTTP_FORM_START); + pitem.replace(FPSTR(T_v), F("wifisave")); // set form action + page += pitem; + + pitem = FPSTR(HTTP_FORM_WIFI); + pitem.replace(FPSTR(T_v), WiFi_SSID()); + page += pitem; + + page += getStaticOut(); + page += FPSTR(HTTP_FORM_WIFI_END); + if(_paramsInWifi && _paramsCount>0){ + page += FPSTR(HTTP_FORM_PARAM_HEAD); + page += getParamOut(); + } + page += FPSTR(HTTP_FORM_END); + page += FPSTR(HTTP_SCAN_LINK); + reportStatus(page); + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + // server->close(); // testing reliability fix for content length mismatches during mutiple flood hits + + DEBUG_WM(DEBUG_DEV,F("Sent config page")); +} + +/** + * HTTPD CALLBACK Wifi param page handler + */ +void WiFiManager::handleParam(){ + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Param")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleparam)); // @token titlewifi + + String pitem = ""; + + pitem = FPSTR(HTTP_FORM_START); + pitem.replace(FPSTR(T_v), F("paramsave")); + page += pitem; + + page += getParamOut(); + page += FPSTR(HTTP_FORM_END); + reportStatus(page); + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + + DEBUG_WM(DEBUG_DEV,F("Sent param page")); +} + + +String WiFiManager::getMenuOut(){ + String page; + + for(auto menuId :_menuIds ){ + if(((String)menuId == "param") && (_paramsCount == 0)) continue; // no params set, omit params + page += HTTP_PORTAL_MENU[menuId]; + } + + 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,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,false); +} +bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ + // DEBUG_WM(DEBUG_DEV,"scanNetworks async:",async == true); + // DEBUG_WM(DEBUG_DEV,_numNetworks,(millis()-_lastscan )); + // DEBUG_WM(DEBUG_DEV,"scanNetworks force:",force == true); + if(force || _numNetworks == 0 || (millis()-_lastscan > 60000)){ + int8_t res; + _startscan = millis(); + if(async){ + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); + #ifdef ESP8266 + #ifndef WM_NOASYNC // no async available < 2.4.0 + using namespace std::placeholders; // for `_1` + WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); + #else + res = WiFi.scanNetworks(); + #endif + #else + res = WiFi.scanNetworks(true); + #endif + return false; + } + else{ + res = WiFi.scanNetworks(); + } + if(res == WIFI_SCAN_FAILED) DEBUG_WM(DEBUG_ERROR,"[ERROR] scan failed"); + else if(res == WIFI_SCAN_RUNNING){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] scan waiting"); + while(WiFi.scanComplete() == WIFI_SCAN_RUNNING){ + DEBUG_WM(DEBUG_ERROR,"."); + delay(100); + } + _numNetworks = WiFi.scanComplete(); + } + else if(res >=0 ) _numNetworks = res; + _lastscan = millis(); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); + return true; + } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+" ms ago"); + return false; +} + +String WiFiManager::WiFiManager::getScanItemOut(){ + String page; + + if(!_numNetworks) WiFi_scanNetworks(); // scan in case this gets called before any scans + + int n = _numNetworks; if (n == 0) { DEBUG_WM(F("No networks found")); - page += F("No networks found. Refresh to scan again."); - } else { - + page += FPSTR(S_nonetworks); // @token nonetworks + } + else { + DEBUG_WM(n,F("networks found")); //sort networks int indices[n]; for (int i = 0; i < n; i++) { @@ -465,8 +1075,6 @@ void WiFiManager::handleWifi(boolean scan) { } // RSSI SORT - - // old sort for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) { @@ -475,10 +1083,12 @@ void WiFiManager::handleWifi(boolean scan) { } } - /*std::sort(indices, indices + n, [](const int & a, const int & b) -> bool + /* test std:sort + std::sort(indices, indices + n, [](const int & a, const int & b) -> bool { return WiFi.RSSI(a) > WiFi.RSSI(b); - });*/ + }); + */ // remove duplicates ( must be RSSI sorted ) if (_removeDuplicateAPs) { @@ -488,279 +1098,928 @@ void WiFiManager::handleWifi(boolean scan) { cssid = WiFi.SSID(indices[i]); for (int j = i + 1; j < n; j++) { if (cssid == WiFi.SSID(indices[j])) { - DEBUG_WM("DUP AP: " + WiFi.SSID(indices[j])); + DEBUG_WM(DEBUG_VERBOSE,F("DUP AP:"),WiFi.SSID(indices[j])); indices[j] = -1; // set dup aps to index -1 } } } } + // token precheck, to speed up replacements on large ap lists + String HTTP_ITEM_STR = FPSTR(HTTP_ITEM); + + // toggle icons with percentage + HTTP_ITEM_STR.replace("{qp}", FPSTR(HTTP_ITEM_QP)); + HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "" : "h"); + HTTP_ITEM_STR.replace("{qi}", FPSTR(HTTP_ITEM_QI)); + HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "h" : ""); + + // set token precheck flags + bool tok_r = HTTP_ITEM_STR.indexOf(FPSTR(T_r)) > 0; + bool tok_R = HTTP_ITEM_STR.indexOf(FPSTR(T_R)) > 0; + bool tok_e = HTTP_ITEM_STR.indexOf(FPSTR(T_e)) > 0; + bool tok_q = HTTP_ITEM_STR.indexOf(FPSTR(T_q)) > 0; + bool tok_i = HTTP_ITEM_STR.indexOf(FPSTR(T_i)) > 0; + //display networks in page for (int i = 0; i < n; i++) { if (indices[i] == -1) continue; // skip dups - DEBUG_WM(WiFi.SSID(indices[i])); - DEBUG_WM(WiFi.RSSI(indices[i])); - int quality = getRSSIasQuality(WiFi.RSSI(indices[i])); - if (_minimumQuality == -1 || _minimumQuality < quality) { - String item = FPSTR(HTTP_ITEM); - String rssiQ; - rssiQ += quality; - item.replace("{v}", WiFi.SSID(indices[i])); - item.replace("{r}", rssiQ); - if (WiFi.encryptionType(indices[i]) != ENC_TYPE_NONE) { - item.replace("{i}", "l"); - } else { - item.replace("{i}", ""); + DEBUG_WM(DEBUG_VERBOSE,F("AP: "),(String)WiFi.RSSI(indices[i]) + " " + (String)WiFi.SSID(indices[i])); + + int rssiperc = getRSSIasQuality(WiFi.RSSI(indices[i])); + uint8_t enc_type = WiFi.encryptionType(indices[i]); + + if (_minimumQuality == -1 || _minimumQuality < rssiperc) { + String item = HTTP_ITEM_STR; + item.replace(FPSTR(T_v), htmlEntities(WiFi.SSID(indices[i]))); // ssid no encoding + if(tok_e) item.replace(FPSTR(T_e), encryptionTypeStr(enc_type)); + if(tok_r) item.replace(FPSTR(T_r), (String)rssiperc); // rssi percentage 0-100 + if(tok_R) item.replace(FPSTR(T_R), (String)WiFi.RSSI(indices[i])); // rssi db + if(tok_q) item.replace(FPSTR(T_q), (String)round(map(rssiperc,0,100,1,4))); //quality icon 1-4 + if(tok_i){ + if (enc_type != WM_WIFIOPEN) { + item.replace(FPSTR(T_i), F("l")); + } else { + item.replace(FPSTR(T_i), ""); + } } //DEBUG_WM(item); page += item; delay(0); } else { - DEBUG_WM(F("Skipping due to quality")); + DEBUG_WM(DEBUG_VERBOSE,F("Skipping , does not meet _minimumQuality")); } } - page += "
"; - } - } - - page += FPSTR(HTTP_FORM_START); - char parLength[5]; - // add the extra parameters to the form - for (int i = 0; i < _paramsCount; i++) { - if (_params[i] == NULL) { - break; + page += FPSTR(HTTP_BR); } - String pitem = FPSTR(HTTP_FORM_PARAM); - if (_params[i]->getID() != NULL) { - pitem.replace("{i}", _params[i]->getID()); - pitem.replace("{n}", _params[i]->getID()); - pitem.replace("{p}", _params[i]->getPlaceholder()); - snprintf(parLength, 5, "%d", _params[i]->getValueLength()); - pitem.replace("{l}", parLength); - pitem.replace("{v}", _params[i]->getValue()); - pitem.replace("{c}", _params[i]->getCustomHTML()); - } else { - pitem = _params[i]->getCustomHTML(); - } - - page += pitem; - } - if (_params[0] != NULL) { - page += "
"; - } - - if (_sta_static_ip) { - - String item = FPSTR(HTTP_FORM_PARAM); - item.replace("{i}", "ip"); - item.replace("{n}", "ip"); - item.replace("{p}", "Static IP"); - item.replace("{l}", "15"); - item.replace("{v}", _sta_static_ip.toString()); - - page += item; - - item = FPSTR(HTTP_FORM_PARAM); - item.replace("{i}", "gw"); - item.replace("{n}", "gw"); - item.replace("{p}", "Static Gateway"); - item.replace("{l}", "15"); - item.replace("{v}", _sta_static_gw.toString()); - - page += item; - - item = FPSTR(HTTP_FORM_PARAM); - item.replace("{i}", "sn"); - item.replace("{n}", "sn"); - item.replace("{p}", "Subnet"); - item.replace("{l}", "15"); - item.replace("{v}", _sta_static_sn.toString()); - - page += item; - - page += "
"; - } - - page += FPSTR(HTTP_FORM_END); - page += FPSTR(HTTP_SCAN_LINK); - - page += FPSTR(HTTP_END); - - server->sendHeader("Content-Length", String(page.length())); - server->send(200, "text/html", page); - - - DEBUG_WM(F("Sent config page")); + return page; } -/** Handle the WLAN save form and redirect to WLAN config page again */ +String WiFiManager::getIpForm(String id, String title, String value){ + String item = FPSTR(HTTP_FORM_LABEL); + item += FPSTR(HTTP_FORM_PARAM); + item.replace(FPSTR(T_i), id); + item.replace(FPSTR(T_n), id); + item.replace(FPSTR(T_p), FPSTR(T_t)); + // item.replace(FPSTR(T_p), default); + item.replace(FPSTR(T_t), title); + item.replace(FPSTR(T_l), F("15")); + item.replace(FPSTR(T_v), value); + item.replace(FPSTR(T_c), ""); + return item; +} + +String WiFiManager::getStaticOut(){ + String page; + if ((_staShowStaticFields || _sta_static_ip) && _staShowStaticFields>=0) { + DEBUG_WM(DEBUG_DEV,"_staShowStaticFields"); + page += FPSTR(HTTP_FORM_STATIC_HEAD); + // @todo how can we get these accurate settings from memory , wifi_get_ip_info does not seem to reveal if struct ip_info is static or not + page += getIpForm(FPSTR(S_ip),FPSTR(S_staticip),(_sta_static_ip ? _sta_static_ip.toString() : "")); // @token staticip + // WiFi.localIP().toString(); + page += getIpForm(FPSTR(S_gw),FPSTR(S_staticgw),(_sta_static_gw ? _sta_static_gw.toString() : "")); // @token staticgw + // WiFi.gatewayIP().toString(); + page += getIpForm(FPSTR(S_sn),FPSTR(S_subnet),(_sta_static_sn ? _sta_static_sn.toString() : "")); // @token subnet + // WiFi.subnetMask().toString(); + } + + if((_staShowDns || _sta_static_dns) && _staShowDns>=0){ + page += getIpForm(FPSTR(S_dns),FPSTR(S_staticdns),(_sta_static_dns ? _sta_static_dns.toString() : "")); // @token dns + } + + if(page!="") page += FPSTR(HTTP_BR); // @todo remove these, use css + + return page; +} + +String WiFiManager::getParamOut(){ + String page; + + if(_paramsCount > 0){ + + 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_n = HTTP_PARAM_temp.indexOf(FPSTR(T_n)) > 0; + bool tok_p = HTTP_PARAM_temp.indexOf(FPSTR(T_p)) > 0; + bool tok_t = HTTP_PARAM_temp.indexOf(FPSTR(T_t)) > 0; + bool tok_l = HTTP_PARAM_temp.indexOf(FPSTR(T_l)) > 0; + 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]; + // add the extra parameters to the form + for (int i = 0; i < _paramsCount; i++) { + if (_params[i] == NULL || _params[i]->_length == 0) { + DEBUG_WM(DEBUG_ERROR,"[ERROR] WiFiManagerParameter is out of scope"); + break; + } + + // label before or after, this could probably be done via floats however + String pitem; + switch (_params[i]->getLabelPlacement()) { + case WFM_LABEL_BEFORE: + pitem = FPSTR(HTTP_FORM_LABEL); + pitem += FPSTR(HTTP_FORM_PARAM); + break; + case WFM_LABEL_AFTER: + pitem = FPSTR(HTTP_FORM_PARAM); + pitem += FPSTR(HTTP_FORM_LABEL); + break; + default: + // WFM_NO_LABEL + pitem = FPSTR(HTTP_FORM_PARAM); + break; + } + + // if no ID use customhtml for item, else generate from param string + if (_params[i]->getID() != NULL) { + if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); + if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); + if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); + if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); + if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getPlaceholder()); + snprintf(parLength, 5, "%d", _params[i]->getValueLength()); + if(tok_l)pitem.replace(FPSTR(T_l), parLength); + if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); + if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // meant for additional attributes, not html + } else { + pitem = _params[i]->getCustomHTML(); + } + + page += pitem; + } + } + + return page; +} + +void WiFiManager::handleWiFiStatus(){ + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi status ")); + handleRequest(); + String page; + // String page = "{\"result\":true,\"count\":1}"; + #ifdef JSTEST + page = FPSTR(HTTP_JS); + #endif + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); +} + +/** + * HTTPD CALLBACK save form and redirect to WLAN config page again + */ void WiFiManager::handleWifiSave() { - DEBUG_WM(F("WiFi save")); + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); + DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); + handleRequest(); + + // @todo use new callback for before paramsaves + if ( _presavecallback != NULL) { + _presavecallback(); + } //SAVE/connect here - _ssid = server->arg("s").c_str(); - _pass = server->arg("p").c_str(); + _ssid = server->arg(F("s")).c_str(); + _pass = server->arg(F("p")).c_str(); - //parameters - for (int i = 0; i < _paramsCount; i++) { - if (_params[i] == NULL) { - break; - } - //read parameter - String value = server->arg(_params[i]->getID()).c_str(); - //store it in array - value.toCharArray(_params[i]->_value, _params[i]->_length + 1); - DEBUG_WM(F("Parameter")); - DEBUG_WM(_params[i]->getID()); - DEBUG_WM(value); - } + if(_paramsInWifi) doParamSave(); - if (server->arg("ip") != "") { - DEBUG_WM(F("static ip")); - DEBUG_WM(server->arg("ip")); - //_sta_static_ip.fromString(server->arg("ip")); - String ip = server->arg("ip"); + if (server->arg(FPSTR(S_ip)) != "") { + //_sta_static_ip.fromString(server->arg(FPSTR(S_ip)); + String ip = server->arg(FPSTR(S_ip)); optionalIPFromString(&_sta_static_ip, ip.c_str()); + DEBUG_WM(DEBUG_DEV,F("static ip:"),ip); } - if (server->arg("gw") != "") { - DEBUG_WM(F("static gateway")); - DEBUG_WM(server->arg("gw")); - String gw = server->arg("gw"); + if (server->arg(FPSTR(S_gw)) != "") { + String gw = server->arg(FPSTR(S_gw)); optionalIPFromString(&_sta_static_gw, gw.c_str()); + DEBUG_WM(DEBUG_DEV,F("static gateway:"),gw); } - if (server->arg("sn") != "") { - DEBUG_WM(F("static netmask")); - DEBUG_WM(server->arg("sn")); - String sn = server->arg("sn"); + if (server->arg(FPSTR(S_sn)) != "") { + String sn = server->arg(FPSTR(S_sn)); optionalIPFromString(&_sta_static_sn, sn.c_str()); + DEBUG_WM(DEBUG_DEV,F("static netmask:"),sn); + } + if (server->arg(FPSTR(S_dns)) != "") { + String dns = server->arg(FPSTR(S_dns)); + optionalIPFromString(&_sta_static_dns, dns.c_str()); + DEBUG_WM(DEBUG_DEV,F("static DNS:"),dns); } - String page = FPSTR(HTTP_HEAD); - page.replace("{v}", "Credentials Saved"); - page += FPSTR(HTTP_SCRIPT); - page += FPSTR(HTTP_STYLE); - page += _customHeadElement; - page += FPSTR(HTTP_HEAD_END); + String page = getHTTPHead(FPSTR(S_titlewifisaved)); // @token titlewifisaved page += FPSTR(HTTP_SAVED); page += FPSTR(HTTP_END); - server->sendHeader("Content-Length", String(page.length())); - server->send(200, "text/html", page); + 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(F("Sent wifi save 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 } -/** Handle the info page */ -void WiFiManager::handleInfo() { - DEBUG_WM(F("Info")); +void WiFiManager::handleParamSave() { - String page = FPSTR(HTTP_HEAD); - page.replace("{v}", "Info"); - page += FPSTR(HTTP_SCRIPT); - page += FPSTR(HTTP_STYLE); - page += _customHeadElement; - page += FPSTR(HTTP_HEAD_END); - page += F("
"); - page += F("
Chip ID
"); - page += ESP.getChipId(); - page += F("
"); - page += F("
Flash Chip ID
"); - page += ESP.getFlashChipId(); - page += F("
"); - page += F("
IDE Flash Size
"); - page += ESP.getFlashChipSize(); - page += F(" bytes
"); - page += F("
Real Flash Size
"); - page += ESP.getFlashChipRealSize(); - page += F(" bytes
"); - page += F("
Soft AP IP
"); - page += WiFi.softAPIP().toString(); - page += F("
"); - page += F("
Soft AP MAC
"); - page += WiFi.softAPmacAddress(); - page += F("
"); - page += F("
Station MAC
"); - page += WiFi.macAddress(); - page += F("
"); - page += F("
"); - page += FPSTR(HTTP_END); + 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(); - server->sendHeader("Content-Length", String(page.length())); - server->send(200, "text/html", page); - - DEBUG_WM(F("Sent info page")); -} - -/** Handle the reset page */ -void WiFiManager::handleReset() { - DEBUG_WM(F("Reset")); - - String page = FPSTR(HTTP_HEAD); - page.replace("{v}", "Info"); - page += FPSTR(HTTP_SCRIPT); - page += FPSTR(HTTP_STYLE); - page += _customHeadElement; - page += FPSTR(HTTP_HEAD_END); - page += F("Module will reset in a few seconds."); - page += FPSTR(HTTP_END); - - server->sendHeader("Content-Length", String(page.length())); - server->send(200, "text/html", page); - - DEBUG_WM(F("Sent reset page")); - delay(5000); - ESP.reset(); - delay(2000); -} - -void WiFiManager::handleNotFound() { - if (captivePortal()) { // If captive portal redirect instead of displaying the error page. - return; + // @todo use new callback for before paramsaves + if ( _presavecallback != NULL) { + _presavecallback(); } - String message = "File Not Found\n\n"; - message += "URI: "; + + doParamSave(); + + // @todo use new callback for paramsaves + if ( _savecallback != NULL) { + _savecallback(); + } + + String page = getHTTPHead(FPSTR(S_titleparamsaved)); // @token titleparamsaved + page += FPSTR(HTTP_PARAMSAVED); + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + + DEBUG_WM(DEBUG_DEV,F("Sent param save page")); +} + +void WiFiManager::doParamSave(){ + //parameters + if(_paramsCount > 0){ + DEBUG_WM(DEBUG_VERBOSE,F("Parameters")); + DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + for (int i = 0; i < _paramsCount; i++) { + if (_params[i] == NULL) { + break; + } + //read parameter from server + String name = (String)FPSTR(S_parampre)+(String)i; + String value; + 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 + DEBUG_WM(DEBUG_VERBOSE,(String)_params[i]->getID() + ":",value); + } + DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + } +} + +/** + * HTTPD CALLBACK info page + */ +void WiFiManager::handleInfo() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Info")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo + reportStatus(page); + + uint16_t infos = 0; + + //@todo convert to enum or refactor to strings + #ifdef ESP8266 + infos = 27; + String infoids[] = { + F("esphead"), + F("uptime"), + F("chipid"), + F("fchipid"), + F("idesize"), + F("flashsize"), + F("sdkver"), + F("corever"), + F("bootver"), + F("cpufreq"), + F("freeheap"), + F("memsketch"), + F("memsmeter"), + F("lastreset"), + F("wifihead"), + F("apip"), + F("apmac"), + F("apssid"), + F("apbssid"), + F("staip"), + F("stagw"), + F("stasub"), + F("dnss"), + F("host"), + F("stamac"), + F("conx"), + F("autoconx") + }; + + #elif defined(ESP32) + infos = 22; + String infoids[] = { + F("esphead"), + F("uptime"), + F("chipid"), + F("chiprev"), + F("idesize"), + F("sdkver"), + F("cpufreq"), + F("freeheap"), + F("lastreset"), + // F("temp"), + F("wifihead"), + F("apip"), + F("apmac"), + F("aphost"), + F("apssid"), + F("apbssid"), + F("staip"), + F("stagw"), + F("stasub"), + F("dnss"), + F("host"), + F("stamac"), + F("conx") + }; + #endif + + for(size_t i=0; i"); + if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); + page += FPSTR(HTTP_HELP); + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + + DEBUG_WM(DEBUG_DEV,F("Sent info page")); +} + +String WiFiManager::getInfoData(String id){ + + String p; + // @todo add versioning + if(id==F("esphead"))p = FPSTR(HTTP_INFO_esphead); + else if(id==F("wifihead"))p = FPSTR(HTTP_INFO_wifihead); + else if(id==F("uptime")){ + // subject to rollover! + p = FPSTR(HTTP_INFO_uptime); + p.replace(FPSTR(T_1),(String)(millis() / 1000 / 60)); + p.replace(FPSTR(T_2),(String)((millis() / 1000) % 60)); + } + else if(id==F("chipid")){ + p = FPSTR(HTTP_INFO_chipid); + p.replace(FPSTR(T_1),String(WIFI_getChipId(),HEX)); + } + #ifdef ESP32 + else if(id==F("chiprev")){ + p = FPSTR(HTTP_INFO_chiprev); + String rev = (String)ESP.getChipRevision(); + #ifdef _SOC_EFUSE_REG_H_ + String revb = (String)(REG_READ(EFUSE_BLK0_RDATA3_REG) >> (EFUSE_RD_CHIP_VER_RESERVE_S)&&EFUSE_RD_CHIP_VER_RESERVE_V); + p.replace(FPSTR(T_1),rev+"
"+revb); + #else + p.replace(FPSTR(T_1),rev); + #endif + } + #endif + #ifdef ESP8266 + else if(id==F("fchipid")){ + p = FPSTR(HTTP_INFO_fchipid); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipId()); + } + #endif + else if(id==F("idesize")){ + p = FPSTR(HTTP_INFO_idesize); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipSize()); + } + else if(id==F("flashsize")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_flashsize); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipRealSize()); + #endif + } + else if(id==F("sdkver")){ + p = FPSTR(HTTP_INFO_sdkver); + #ifdef ESP32 + p.replace(FPSTR(T_1),(String)esp_get_idf_version()); + #else + p.replace(FPSTR(T_1),(String)system_get_sdk_version()); + #endif + } + else if(id==F("corever")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_corever); + p.replace(FPSTR(T_1),(String)ESP.getCoreVersion()); + #endif + } + #ifdef ESP8266 + else if(id==F("bootver")){ + p = FPSTR(HTTP_INFO_bootver); + p.replace(FPSTR(T_1),(String)system_get_boot_version()); + } + #endif + else if(id==F("cpufreq")){ + p = FPSTR(HTTP_INFO_cpufreq); + p.replace(FPSTR(T_1),(String)ESP.getCpuFreqMHz()); + } + else if(id==F("freeheap")){ + p = FPSTR(HTTP_INFO_freeheap); + p.replace(FPSTR(T_1),(String)ESP.getFreeHeap()); + } + #ifdef ESP8266 + else if(id==F("memsketch")){ + p = FPSTR(HTTP_INFO_memsketch); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + } + #endif + #ifdef ESP8266 + else if(id==F("memsmeter")){ + p = FPSTR(HTTP_INFO_memsmeter); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + } + #endif + else if(id==F("lastreset")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_lastreset); + p.replace(FPSTR(T_1),(String)ESP.getResetReason()); + #elif defined(ESP32) && defined(_ROM_RTC_H_) + // requires #include + p = FPSTR(HTTP_INFO_lastreset); + for(int i=0;i<2;i++){ + int reason = rtc_get_reset_reason(i); + String tok = (String)T_ss+(String)(i+1)+(String)T_es; + switch (reason) + { + //@todo move to array + case 1 : p.replace(tok,F("Vbat power on reset"));break; + case 3 : p.replace(tok,F("Software reset digital core"));break; + case 4 : p.replace(tok,F("Legacy watch dog reset digital core"));break; + case 5 : p.replace(tok,F("Deep Sleep reset digital core"));break; + case 6 : p.replace(tok,F("Reset by SLC module, reset digital core"));break; + case 7 : p.replace(tok,F("Timer Group0 Watch dog reset digital core"));break; + case 8 : p.replace(tok,F("Timer Group1 Watch dog reset digital core"));break; + case 9 : p.replace(tok,F("RTC Watch dog Reset digital core"));break; + case 10 : p.replace(tok,F("Instrusion tested to reset CPU"));break; + case 11 : p.replace(tok,F("Time Group reset CPU"));break; + case 12 : p.replace(tok,F("Software reset CPU"));break; + case 13 : p.replace(tok,F("RTC Watch dog Reset CPU"));break; + case 14 : p.replace(tok,F("for APP CPU, reseted by PRO CPU"));break; + case 15 : p.replace(tok,F("Reset when the vdd voltage is not stable"));break; + case 16 : p.replace(tok,F("RTC Watch dog reset digital core and rtc module"));break; + default : p.replace(tok,F("NO_MEAN")); + } + } + #endif + } + else if(id==F("apip")){ + p = FPSTR(HTTP_INFO_apip); + p.replace(FPSTR(T_1),WiFi.softAPIP().toString()); + } + else if(id==F("apmac")){ + p = FPSTR(HTTP_INFO_apmac); + p.replace(FPSTR(T_1),(String)WiFi.softAPmacAddress()); + } + #ifdef ESP32 + else if(id==F("aphost")){ + p = FPSTR(HTTP_INFO_aphost); + p.replace(FPSTR(T_1),WiFi.softAPgetHostname()); + } + #endif + else if(id==F("apssid")){ + p = FPSTR(HTTP_INFO_apssid); + p.replace(FPSTR(T_1),htmlEntities((String)WiFi_SSID())); + } + else if(id==F("apbssid")){ + p = FPSTR(HTTP_INFO_apbssid); + p.replace(FPSTR(T_1),(String)WiFi.BSSIDstr()); + } + else if(id==F("staip")){ + p = FPSTR(HTTP_INFO_staip); + p.replace(FPSTR(T_1),WiFi.localIP().toString()); + } + else if(id==F("stagw")){ + p = FPSTR(HTTP_INFO_stagw); + p.replace(FPSTR(T_1),WiFi.gatewayIP().toString()); + } + else if(id==F("stasub")){ + p = FPSTR(HTTP_INFO_stasub); + p.replace(FPSTR(T_1),WiFi.subnetMask().toString()); + } + else if(id==F("dnss")){ + p = FPSTR(HTTP_INFO_dnss); + p.replace(FPSTR(T_1),WiFi.dnsIP().toString()); + } + else if(id==F("host")){ + p = FPSTR(HTTP_INFO_host); + #ifdef ESP32 + p.replace(FPSTR(T_1),WiFi.getHostname()); + #else + p.replace(FPSTR(T_1),WiFi.hostname()); + #endif + } + else if(id==F("stamac")){ + p = FPSTR(HTTP_INFO_stamac); + p.replace(FPSTR(T_1),WiFi.macAddress()); + } + else if(id==F("conx")){ + 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; +} + +/** + * HTTPD CALLBACK root or redirect to captive portal + */ +void WiFiManager::handleExit() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Exit")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleexit)); // @token titleexit + page += FPSTR(S_exiting); // @token exiting + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + abort = true; +} + +/** + * HTTPD CALLBACK reset page + */ +void WiFiManager::handleReset() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Reset")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titlereset)); //@token titlereset + page += FPSTR(S_resetting); //@token resetting + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + + DEBUG_WM(F("RESETTING ESP")); + delay(1000); + reboot(); +} + +/** + * HTTPD CALLBACK erase page + */ + +// void WiFiManager::handleErase() { +// handleErase(false); +// } +void WiFiManager::handleErase(boolean opt) { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Erase")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase + + bool ret = erase(opt); + + if(ret) page += FPSTR(S_resetting); // @token resetting + else { + page += FPSTR(S_error); // @token erroroccur + DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFi EraseConfig failed")); + } + + page += FPSTR(HTTP_END); + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + + if(ret){ + delay(2000); + DEBUG_WM(F("RESETTING ESP")); + reboot(); + } +} + +/** + * HTTPD CALLBACK 404 + */ +void WiFiManager::handleNotFound() { + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + handleRequest(); + String message = FPSTR(S_notfound); // @token notfound + message += FPSTR(S_uri); // @token uri message += server->uri(); - message += "\nMethod: "; - message += ( server->method() == HTTP_GET ) ? "GET" : "POST"; - message += "\nArguments: "; + message += FPSTR(S_method); // @token method + message += ( server->method() == HTTP_GET ) ? FPSTR(S_GET) : FPSTR(S_POST); + message += FPSTR(S_args); // @token args message += server->args(); - message += "\n"; + message += F("\n"); for ( uint8_t i = 0; i < server->args(); i++ ) { message += " " + server->argName ( i ) + ": " + server->arg ( i ) + "\n"; } - server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); - server->sendHeader("Pragma", "no-cache"); - server->sendHeader("Expires", "-1"); - server->sendHeader("Content-Length", String(message.length())); - server->send ( 404, "text/plain", message ); + server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); + server->sendHeader(F("Pragma"), F("no-cache")); + server->sendHeader(F("Expires"), F("-1")); + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(message.length())); + server->send ( 404, FPSTR(HTTP_HEAD_CT2), message ); } - -/** Redirect to captive portal if we got a request for another domain. Return true in that case so the page handler do not try to handle the request again. */ +/** + * HTTPD redirector + * Redirect to captive portal if we got a request for another domain. + * Return true in that case so the page handler do not try to handle the request again. + */ boolean WiFiManager::captivePortal() { - if (!isIp(server->hostHeader()) ) { - DEBUG_WM(F("Request redirected to captive portal")); - server->sendHeader("Location", String("http://") + toStringIp(server->client().localIP()), true); - server->send ( 302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + DEBUG_WM(DEBUG_DEV,"-> " + server->hostHeader()); + + if(!_enableCaptivePortal) return false; // skip redirections + + if (!isIp(server->hostHeader())) { + DEBUG_WM(DEBUG_VERBOSE,F("<- Request redirected to captive portal")); + server->sendHeader(F("Location"), (String)F("http://") + toStringIp(server->client().localIP()), true); + server->send ( 302, FPSTR(HTTP_HEAD_CT2), ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. server->client().stop(); // Stop is needed because we sent no content length return true; } return false; } -//start up config portal callback -void WiFiManager::setAPCallback( void (*func)(WiFiManager* myWiFiManager) ) { - _apcallback = func; +void WiFiManager::stopCaptivePortal(){ + _enableCaptivePortal= false; + // @todo maybe disable configportaltimeout(optional), or just provide callback for user } -//start up save config callback -void WiFiManager::setSaveConfigCallback( void (*func)(void) ) { +void WiFiManager::handleClose(){ + stopCaptivePortal(); + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP close")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleclose)); // @token titleclose + page += FPSTR(S_closing); // @token closing + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); +} + +void WiFiManager::reportStatus(String &page){ + updateConxResult(WiFi.status()); + String str; + if (WiFi_SSID() != ""){ + if (WiFi.status()==WL_CONNECTED){ + str = FPSTR(HTTP_STATUS_ON); + str.replace(FPSTR(T_i),WiFi.localIP().toString()); + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + } + else { + str = FPSTR(HTTP_STATUS_OFF); + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + if(_lastconxresult == WL_STATION_WRONG_PASSWORD){ + // wrong password + str.replace(FPSTR(T_c),"D"); // class + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFPW)); + } + else if(_lastconxresult == WL_NO_SSID_AVAIL){ + // connect failed, or ap not found + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFNOAP)); + } + else if(_lastconxresult == WL_CONNECT_FAILED){ + // connect failed + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFFAIL)); + } + else{ + str.replace(FPSTR(T_c),""); + str.replace(FPSTR(T_r),""); + } + } + } + else { + str = FPSTR(HTTP_STATUS_NONE); + } + page += str; +} + +// PUBLIC + +// METHODS + +/** + * reset wifi settings, clean stored ap password + */ + +/** + * disconnect + * @access public + * @since $dev + * @return bool success + */ +bool WiFiManager::disconnect(){ + if(WiFi.status() != WL_CONNECTED){ + DEBUG_WM(DEBUG_VERBOSE,"Disconnecting: Not connected"); + return false; + } + DEBUG_WM("Disconnecting"); + return WiFi_Disconnect(); +} + +/** + * reboot the device + * @access public + */ +void WiFiManager::reboot(){ + DEBUG_WM("Restarting"); + ESP.restart(); +} + +/** + * reboot the device + * @access public + */ +bool WiFiManager::erase(){ + return erase(false); +} + +bool WiFiManager::erase(bool opt){ + DEBUG_WM("Erasing"); + + #if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) + // if opt true, do nvs erase + if(opt){ + DEBUG_WM("Erasing NVS"); + int err; + esp_err_t err; + err = nvs_flash_init(); + DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_init: ",err!=ESP_OK ? (String)err : "Success"); + err = nvs_flash_erase(); + DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_erase: ", err!=ESP_OK ? (String)err : "Success"); + return err == ESP_OK; + } + #else + (void)opt; + #endif + + return WiFi_eraseConfig(); +} + +/** + * [resetSettings description] + * ERASES STA CREDENTIALS + * @access public + */ +void WiFiManager::resetSettings() { + DEBUG_WM(F("SETTINGS ERASED")); + 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 + +/** + * [setTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setTimeout(unsigned long seconds) { + setConfigPortalTimeout(seconds); +} + +/** + * [setConfigPortalTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { + _configPortalTimeout = seconds * 1000; +} + +/** + * [setConnectTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setConnectTimeout(unsigned long seconds) { + _connectTimeout = seconds * 1000; +} + +/** + * [setConnectTimeout description + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setSaveConnectTimeout(unsigned long seconds) { + _saveTimeout = seconds * 1000; +} + +/** + * [setDebugOutput description] + * @access public + * @param {[type]} boolean debug [description] + */ +void WiFiManager::setDebugOutput(boolean debug) { + _debug = debug; +} + +/** + * [setAPStaticIPConfig description] + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + */ +void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { + _ap_static_ip = ip; + _ap_static_gw = gw; + _ap_static_sn = sn; +} + +/** + * [setSTAStaticIPConfig description] + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + */ +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { + _sta_static_ip = ip; + _sta_static_gw = gw; + _sta_static_sn = sn; +} + +/** + * [setSTAStaticIPConfig description] + * @since $dev + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + * @param {[type]} IPAddress dns [description] + */ +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns) { + setSTAStaticIPConfig(ip,gw,sn); + _sta_static_dns = dns; +} + +/** + * [setMinimumSignalQuality description] + * @access public + * @param {[type]} int quality [description] + */ +void WiFiManager::setMinimumSignalQuality(int quality) { + _minimumQuality = quality; +} + +/** + * [setBreakAfterConfig description] + * @access public + * @param {[type]} boolean shouldBreak [description] + */ +void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { + _shouldBreakAfterConfig = shouldBreak; +} + +/** + * setAPCallback, set a callback when softap is started + * @access public + * @param {[type]} void (*func)(WiFiManager* myWiFiManager) [description] + */ +void WiFiManager::setAPCallback( std::function func ) { + _apcallback = func; +} + +/** + * setSaveConfigCallback, set a save config callback after closing configportal + * @todo only calls if configportal stopped + * @access public + * @param {[type]} void (*func)(void) [description] + */ +void WiFiManager::setSaveConfigCallback( std::function func ) { _savecallback = func; } @@ -770,23 +2029,358 @@ void WiFiManager::setConfigResetCallback(void(*func)(void)) { } //sets a custom element to add to head, like a new style tag +/** + * setPreSaveConfigCallback, set a pre save config callback after closing configportal + * @todo only calls if configportal stopped + * @access public + * @param {[type]} void (*func)(void) [description] + */ +void WiFiManager::setPreSaveConfigCallback( std::function func ) { + _presavecallback = func; +} + +/** + * set custom head html + * custom element will be added to head, eg. new style tag etc. + * @access public + * @param char element + */ void WiFiManager::setCustomHeadElement(const char* element) { _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 + * @access public + * @param boolean removeDuplicates [true] + */ void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) { _removeDuplicateAPs = removeDuplicates; } +/** + * toggle configportal blocking loop + * if enabled, then the configportal will enter a blocking loop and wait for configuration + * if disabled use with process() to manually process webserver + * @since $dev + * @access public + * @param boolean shoudlBlock [false] + */ +void WiFiManager::setConfigPortalBlocking(boolean shoudlBlock) { + _configPortalIsBlocking = shoudlBlock; +} + +/** + * toggle restore persistent, track internally + * sets ESP wifi.persistent so we can remember it and restore user preference on destruct + * there is no getter in esp8266 platform prior to https://github.com/esp8266/Arduino/pull/3857 + * @since $dev + * @access public + * @param boolean persistent [true] + */ +void WiFiManager::setRestorePersistent(boolean persistent) { + _userpersistent = persistent; + if(!persistent) DEBUG_WM(F("persistent is off")); +} + +/** + * toggle showing static ip form fields + * if enabled, then the static ip, gateway, subnet fields will be visible, even if not set in code + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowStaticFields(boolean alwaysShow){ + if(_disableIpFields) _staShowStaticFields = alwaysShow ? 1 : -1; + else _staShowStaticFields = alwaysShow ? 1 : 0; +} + +/** + * toggle showing dns fields + * if enabled, then the dns1 field will be visible, even if not set in code + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowDnsFields(boolean alwaysShow){ + if(_disableIpFields) _staShowDns = alwaysShow ? 1 : -1; + _staShowDns = alwaysShow ? 1 : 0; +} + +/** + * toggle captive portal + * if enabled, then devices that use captive portal checks will be redirected to root + * if not you will automatically have to navigate to ip [192.168.4.1] + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setCaptivePortalEnable(boolean enabled){ + _enableCaptivePortal = enabled; +} + +/** + * toggle wifi autoreconnect policy + * if enabled, then wifi will autoreconnect automatically always + * On esp8266 we force this on when autoconnect is called, see notes + * On esp32 this is handled on SYSTEM_EVENT_STA_DISCONNECTED since it does not exist in core yet + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setWiFiAutoReconnect(boolean enabled){ + _wifiAutoReconnect = enabled; +} + +/** + * toggle configportal timeout wait for station client + * if enabled, then the configportal will start timeout when no stations are connected to softAP + * disabled by default as rogue stations can keep it open if there is no auth + * @since $dev + * @access public + * @param boolean enabled [false] + */ +void WiFiManager::setCaptivePortalClientCheck(boolean enabled){ + _cpClientCheck = enabled; +} + +/** + * toggle configportal timeout wait for web client + * if enabled, then the configportal will restart timeout when client requests come in + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setWebPortalClientCheck(boolean enabled){ + _webClientCheck = enabled; +} + +/** + * toggle wifiscan percentages or quality icons + * @since $dev + * @access public + * @param boolean enabled [false] + */ +void WiFiManager::setScanDispPerc(boolean enabled){ + _scanDispOptions = enabled; +} + +/** + * toggle configportal if autoconnect failed + * if enabled, then the configportal will be activated on autoconnect failure + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setEnableConfigPortal(boolean enable) +{ + _enableConfigPortal = enable; +} +/** + * set the hostname (dhcp client id) + * @since $dev + * @access public + * @param char* hostname 32 character hostname to use for sta+ap in esp32, sta in esp8266 + * @return bool false if hostname is not valid + */ +bool WiFiManager::setHostname(const char * hostname){ + //@todo max length 32 + _hostname = hostname; + return true; +} + +/** + * toggle showing erase wifi config button on info page + * @param boolean enabled + */ +void WiFiManager::setShowInfoErase(boolean enabled){ + _showInfoErase = enabled; +} + +/** + * set menu items and order + * 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++){ + if(menu[i] == _menutokens[j]){ + if((String)menu[i] == "param") _paramsInWifi = false; // param auto flag + _menuIds.push_back(j); + } + } + } + // 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++){ + if(menuitem == _menutokens[j]){ + if((String)menuitem == "param") _paramsInWifi = false; // param auto flag + _menuIds.push_back(j); + } + } + } + // DEBUG_WM(getMenuOut()); +} + + +// GETTERS + +/** + * get config portal AP SSID + * @since 0.0.1 + * @access public + * @return String the configportal ap name + */ +String WiFiManager::getConfigPortalSSID() { + return _apName; +} + +/** + * return the last known connection result + * logged on autoconnect and wifisave, can be used to check why failed + * get as readable string with getWLStatusString(getLastConxResult); + * @since $dev + * @access public + * @return bool return wl_status codes + */ +uint8_t WiFiManager::getLastConxResult(){ + return _lastconxresult; +} + +/** + * check if wifi has a saved ap or not + * @since $dev + * @access public + * @return bool true if a saved ap config exists + */ +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 +// @todo fix DEBUG_WM(0,0); template void WiFiManager::DEBUG_WM(Generic text) { - if (_debug) { - Serial.print("*WM: "); - Serial.println(text); + DEBUG_WM(DEBUG_NOTIFY,text,""); +} + +template +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text) { + if(_debugLevel >= level) DEBUG_WM(level,text,""); +} + +template +void WiFiManager::DEBUG_WM(Generic text,Genericb textb) { + DEBUG_WM(DEBUG_NOTIFY,text,textb); +} + +template +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { + if(!_debug || _debugLevel < level) return; + + 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 + * @return {[type]} [description] + */ +void WiFiManager::debugSoftAPConfig(){ + #ifdef ESP8266 + softap_config config; + wifi_softap_get_config(&config); + #elif defined(ESP32) + wifi_config_t conf_config; + esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK + wifi_ap_config_t config = conf_config.ap; + #endif + + DEBUG_WM(F("SoftAP Configuration")); + DEBUG_WM(FPSTR(D_HR)); + DEBUG_WM(F("ssid: "),(char *) config.ssid); + DEBUG_WM(F("password: "),(char *) config.password); + DEBUG_WM(F("ssid_len: "),config.ssid_len); + DEBUG_WM(F("channel: "),config.channel); + DEBUG_WM(F("authmode: "),config.authmode); + DEBUG_WM(F("ssid_hidden: "),config.ssid_hidden); + DEBUG_WM(F("max_connection: "),config.max_connection); + DEBUG_WM(F("beacon_interval: "),(String)config.beacon_interval + "(ms)"); + DEBUG_WM(FPSTR(D_HR)); +} + +/** + * [debugPlatformInfo description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::debugPlatformInfo(){ + #ifdef ESP8266 + system_print_meminfo(); + DEBUG_WM(F("getCoreVersion(): "),ESP.getCoreVersion()); + DEBUG_WM(F("system_get_sdk_version(): "),system_get_sdk_version()); + DEBUG_WM(F("system_get_boot_version():"),system_get_boot_version()); + DEBUG_WM(F("getFreeHeap(): "),(String)ESP.getFreeHeap()); + #elif defined(ESP32) + size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); + DEBUG_WM("Free heap: ", freeHeap); + DEBUG_WM("ESP-IDF version: ", esp_get_idf_version()); + #endif } int WiFiManager::getRSSIasQuality(int RSSI) { @@ -822,3 +2416,231 @@ String WiFiManager::toStringIp(IPAddress ip) { res += String(((ip >> 8 * 3)) & 0xFF); return res; } + +boolean WiFiManager::validApPassword(){ + // check that ap password is valid, return false + if (_apPassword == NULL) _apPassword = ""; + if (_apPassword != "") { + if (_apPassword.length() < 8 || _apPassword.length() > 63) { + DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); + _apPassword = ""; + return false; // @todo FATAL or fallback to empty ? + } + DEBUG_WM(DEBUG_VERBOSE,F("AccessPoint set password is VALID")); + DEBUG_WM(_apPassword); + } + return true; +} + +/** + * encode htmlentities + * @since $dev + * @param string str string to replace entities + * @return string encoded string + */ +String WiFiManager::htmlEntities(String str) { + str.replace("&","&"); + str.replace("<","<"); + str.replace(">",">"); + // str.replace("'","'"); + // str.replace("\"","""); + // str.replace("/": "/"); + // str.replace("`": "`"); + // str.replace("=": "="); +return str; +} + +/** + * [getWLStatusString description] + * @access public + * @param {[type]} uint8_t status [description] + * @return {[type]} [description] + */ +String WiFiManager::getWLStatusString(uint8_t status){ + if(status <= 7) return WIFI_STA_STATUS[status]; + return FPSTR(S_NA); +} + +String WiFiManager::encryptionTypeStr(uint8_t authmode) { + // DEBUG_WM("enc_tye: ",authmode); + return AUTH_MODE_NAMES[authmode]; +} + +String WiFiManager::getModeString(uint8_t mode){ + if(mode <= 3) return WIFI_MODES[mode]; + 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; + } + ETS_UART_INTR_DISABLE(); + if(persistent) ret = wifi_set_opmode(m); + else ret = wifi_set_opmode_current(m); + ETS_UART_INTR_ENABLE(); + return ret; + #elif defined(ESP32) + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.mode(m); // @todo persistent check persistant mode , NI + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif +} +bool WiFiManager::WiFi_Mode(WiFiMode_t m) { + return WiFi_Mode(m,false); +} + +// sta disconnect without persistent +bool WiFiManager::WiFi_Disconnect() { + #ifdef ESP8266 + if((WiFi.getMode() & WIFI_STA) != 0) { + bool ret; + DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); + ETS_UART_INTR_DISABLE(); // @todo probably not needed + ret = wifi_station_disconnect(); + ETS_UART_INTR_ENABLE(); + return ret; + } + #elif defined(ESP32) + DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); + return WiFi.disconnect(); // not persistent atm + #endif + return false; +} + +// toggle STA without persistent +bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { + DEBUG_WM(DEBUG_DEV,F("WiFi station enable")); + #ifdef ESP8266 + WiFiMode_t newMode; + WiFiMode_t currentMode = WiFi.getMode(); + bool isEnabled = (currentMode & WIFI_STA) != 0; + if(enable) newMode = (WiFiMode_t)(currentMode | WIFI_STA); + else newMode = (WiFiMode_t)(currentMode & (~WIFI_STA)); + + if((isEnabled != enable) || persistent) { + if(enable) { + if(persistent) DEBUG_WM(DEBUG_DEV,F("enableSTA PERSISTENT ON")); + return WiFi_Mode(newMode,persistent); + } else { + return WiFi_Mode(newMode,persistent); + } + } else { + return true; + } + #elif defined(ESP32) + bool ret; + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif +} +bool WiFiManager::WiFi_enableSTA(bool enable) { + return WiFi_enableSTA(enable,false); +} + +bool WiFiManager::WiFi_eraseConfig() { + #ifdef ESP8266 + #ifndef WM_FIXERASECONFIG + return ESP.eraseConfig(); + #else + // erase config BUG replacement + // https://github.com/esp8266/Arduino/pull/3635 + const size_t cfgSize = 0x4000; + size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; + + for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) { + if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) { + return false; + } + } + return true; + #endif + #elif defined(ESP32) + bool ret; + WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! + WiFi.persistent(true); + ret = WiFi.disconnect(true,true); + WiFi.persistent(false); + return ret; + #endif +} + +uint8_t WiFiManager::WiFi_softap_num_stations(){ + #ifdef ESP8266 + return wifi_softap_get_station_num(); + #elif defined(ESP32) + return WiFi.softAPgetStationNum(); + #endif +} + +bool WiFiManager::WiFi_hasAutoConnect(){ + return WiFi_SSID() != ""; +} + +String WiFiManager::WiFi_SSID(){ + #ifdef ESP8266 + return WiFi.SSID(); + #elif defined(ESP32) + //@todo , workaround only when not connected + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.ssid)); + #endif +} + +#ifdef ESP32 +void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ + DEBUG_WM(DEBUG_VERBOSE,"[EVENT]",event); + if(event == SYSTEM_EVENT_STA_DISCONNECTED){ + DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON:",info.disconnected.reason); + if(info.disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.disconnected.reason == WIFI_REASON_AUTH_FAIL){ + _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail + } else _lastconxresulttmp = WiFi.status(); + if(info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON: NO_AP_FOUND"); + #ifdef esp32autoreconnect + DEBUG_WM(DEBUG_VERBOSE,"[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); + WiFi.reconnect(); + #endif + } + else if(event == SYSTEM_EVENT_SCAN_DONE){ + uint16_t scans = WiFi.scanComplete(); + WiFi_scanComplete(scans); + } +} +#endif + +void WiFiManager::WiFi_autoReconnect(){ + #ifdef ESP8266 + WiFi.setAutoReconnect(_wifiAutoReconnect); + #elif defined(ESP32) + // if(_wifiAutoReconnect){ + DEBUG_WM(DEBUG_VERBOSE,"ESP32 event handler enabled"); + using namespace std::placeholders; + WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); + // } + #endif +} diff --git a/WiFiManager.h b/WiFiManager.h index 9b1c1e3..97d3103 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -1,44 +1,103 @@ -/************************************************************** - WiFiManager is a library for the ESP8266/Arduino platform - (https://github.com/esp8266/Arduino) to enable easy - configuration and reconfiguration of WiFi credentials using a Captive Portal - inspired by: - http://www.esp8266.com/viewtopic.php?f=29&t=2520 - https://github.com/chriscook8/esp-arduino-apboot - https://github.com/esp8266/Arduino/tree/master/libraries/DNSServer/examples/CaptivePortalAdvanced - Built by AlexT https://github.com/tzapu - Licensed under MIT license - **************************************************************/ +/** + * WiFiManager.h + * + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ #ifndef WiFiManager_h #define WiFiManager_h -#include -#include +#ifdef ESP8266 +#include +#endif + +#include + +// #define WM_MDNS // also set MDNS with sethostname +// #define WM_FIXERASECONFIG // use erase flash fix +// #define WM_ERASE_NVS // esp32 erase(true) will erase NVS +// #define WM_RTC // esp32 info page will include reset reasons + +#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 +// autoreconnect status WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 + +#define WM_WEBSERVERSHIM // use webserver shim lib + +#ifdef ESP8266 + + extern "C" { + #include "user_interface.h" + } + #include + #include + + #ifdef WM_MDNS + #include + #endif + + #define WIFI_getChipId() ESP.getChipId() + #define WM_WIFIOPEN ENC_TYPE_NONE + +#elif defined(ESP32) + + #include + #include + + #define WIFI_getChipId() (uint32_t)ESP.getEfuseMac() + #define WM_WIFIOPEN WIFI_AUTH_OPEN + + #ifndef WEBSERVER_H + #ifdef WM_WEBSERVERSHIM + #include + #else + #include + // Forthcoming official ? + // https://github.com/esp8266/ESPWebServer + #endif + #endif + + #ifdef WM_ERASE_NVS + #include + #include + #endif + + #ifdef WM_MDNS + #include + #endif + + #ifdef WM_RTC + #include + #endif + + +#else +#endif + #include #include - -extern "C" { - #include "user_interface.h" -} - -const char HTTP_HEAD[] PROGMEM = "{v}"; -const char HTTP_STYLE[] PROGMEM = ""; -const char HTTP_SCRIPT[] PROGMEM = ""; -const char HTTP_HEAD_END[] PROGMEM = "
"; -const char HTTP_PORTAL_OPTIONS[] PROGMEM = "



"; -const char HTTP_ITEM[] PROGMEM = "
{v} {r}%
"; -const char HTTP_FORM_START[] PROGMEM = "


"; -const char HTTP_FORM_PARAM[] PROGMEM = "
"; -const char HTTP_FORM_END[] PROGMEM = "
"; -const char HTTP_SCAN_LINK[] PROGMEM = "
"; -const char HTTP_SAVED[] PROGMEM = "
Credentials Saved
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; -const char HTTP_END[] PROGMEM = "
"; +#include "strings_en.h" #ifndef WIFI_MANAGER_MAX_PARAMS -#define WIFI_MANAGER_MAX_PARAMS 10 + #define WIFI_MANAGER_MAX_PARAMS 5 // params will autoincrement and realloc by this amount when max is reached #endif +#define WFM_LABEL_BEFORE 1 +#define WFM_LABEL_AFTER 2 +#define WFM_NO_LABEL 0 + class WiFiManagerParameter { public: /** @@ -46,24 +105,32 @@ class WiFiManagerParameter { @id is used for HTTP queries and must not contain spaces nor other special characters */ WiFiManagerParameter(const char *custom); + WiFiManagerParameter(const char *id, const char *placeholder); WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length); WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom); + WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement); ~WiFiManagerParameter(); const char *getID(); const char *getValue(); const char *getPlaceholder(); int getValueLength(); + int getLabelPlacement(); const char *getCustomHTML(); + void setValue(const char *defaultValue, int length); + + protected: + void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom); + void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom, int labelPlacement); + private: const char *_id; const char *_placeholder; 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); - friend class WiFiManager; }; @@ -71,134 +138,352 @@ class WiFiManagerParameter { class WiFiManager { public: + WiFiManager(Stream& consolePort); WiFiManager(); ~WiFiManager(); + void WiFiManagerInit(); + // auto connect to saved wifi, or custom, and start config portal on failures boolean autoConnect(); boolean autoConnect(char const *apName, char const *apPassword = NULL); - //if you want to always start the config portal, without trying to connect first - boolean startConfigPortal(); + //manually start the config portal, autoconnect does this automatically on connect failure + boolean startConfigPortal(); // auto generates apname boolean startConfigPortal(char const *apName, char const *apPassword = NULL); + //manually stop the config portal if started manually + boolean stopConfigPortal(); + + //manually start the web portal, autoconnect does this automatically on connect failure + void startWebPortal(); + //manually stop the web portal if started manually + void stopWebPortal(); + // Run webserver processing, if setConfigPortalBlocking(false) + boolean process(); + // get the AP name of the config portal, so it can be used in the callback String getConfigPortalSSID(); + // erase wifi credentials void resetSettings(); + // reboot esp + void reboot(); + // disconnect wifi, without persistent saving or erasing + bool disconnect(); + // erase esp + bool erase(); + bool erase(bool opt); - //sets timeout before webserver loop ends and exits even if there has been no setup. + //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); + void setTimeout(unsigned long seconds); // @deprecated, alias //sets timeout for which to attempt connecting, useful if you get a lot of failed connects void setConnectTimeout(unsigned long seconds); - - + //sets timeout for which to attempt connecting on saves, useful if there are bugs in esp waitforconnectloop + void setSaveConnectTimeout(unsigned long seconds); + // toggle debug output void setDebugOutput(boolean debug); - //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); //sets config for a static IP void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + //sets config for a static IP with DNS + void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns); //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) ); + void setAPCallback( std::function func ); //called when settings reset have been triggered void setConfigResetCallback(void(*func)(void)); + //called when settings have been changed and connection was successful + void setSaveConfigCallback( std::function func ); + //called when settings before have been changed and connection was successful + void setPreSaveConfigCallback( std::function func ); //adds a custom parameter, returns false on failure bool addParameter(WiFiManagerParameter *p); + //returns the list of Parameters + WiFiManagerParameter** getParameters(); + // returns the Parameters Count + int getParametersCount(); //if this is set, it will exit after config, even if connection is unsuccessful. void setBreakAfterConfig(boolean shouldBreak); - //if this is set, try WPS setup when starting (this will delay config portal for up to 2 mins) - //TODO + // if this is set, portal will be blocking and wait until save or exit, + // is false user must manually `process()` to handle config portal, + // setConfigPortalTimeout is ignored in this mode, user is responsible for closing configportal + void setConfigPortalBlocking(boolean shouldBlock); //if this is set, customise style void setCustomHeadElement(const char* element); //if this is true, remove duplicated Access Points - defaut true void setRemoveDuplicateAPs(boolean removeDuplicates); + //setter for ESP wifi.persistent so we can remember it and restore user preference, as WIFi._persistent is protected + void setRestorePersistent(boolean persistent); + //if true, always show static net inputs, IP, subnet, gateway, else only show if set via setSTAStaticIPConfig + void setShowStaticFields(boolean alwaysShow); + //if true, always show static dns, esle only show if set via setSTAStaticIPConfig + void setShowDnsFields(boolean alwaysShow); + //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 true, reset timeout when webclient connects (true), suggest disabling if captiveportal is open + void setWebPortalClientCheck(boolean enabled); + // if true, enable autoreconnecting + void setWiFiAutoReconnect(boolean enabled); + // if true, wifiscan will show percentage instead of quality icons, until we have better templating + void setScanDispPerc(boolean enabled); + // if true (default) then start the config portal from autoConnect if connection failed + void setEnableConfigPortal(boolean enable); + // set a custom hostname, sets sta and ap dhcp client id for esp32, and sta for esp8266 + bool setHostname(const char * hostname); + // show erase wifi onfig button on info page, true + void setShowInfoErase(boolean enabled); + // set custom menu + + // set custom menu items and order + void setMenu(std::vector& menu); + void setMenu(const char* menu[], uint8_t size); + + // get last connection result, includes autoconnect and wifisave + uint8_t getLastConxResult(); + // get a status as string + String getWLStatusString(uint8_t status); + String getModeString(uint8_t mode); + // check if the module has a saved ap to connect to + bool getWiFiIsSaved(); + + // debug output the softap config + void debugSoftAPConfig(); + // 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; - std::unique_ptr server; - //const int WM_DONE = 0; - //const int WM_WAIT = 10; + #if defined(ESP32) && defined(WM_WEBSERVERSHIM) + using WM_WebServer = WebServer; + #else + using WM_WebServer = ESP8266WebServer; + #endif + std::unique_ptr server; - //const String HTTP_HEAD = "{v}"; - - void setupConfigPortal(); - void startWPS(); - - const char* _apName = "no-net"; - const char* _apPassword = NULL; - String _ssid = ""; - String _pass = ""; - unsigned long _configPortalTimeout = 0; - unsigned long _connectTimeout = 0; - unsigned long _configPortalStart = 0; + std::vector _menuIds; + std::vector _menuIdsDefault = {"wifi","info","exit"}; + // ip configs @todo struct ? IPAddress _ap_static_ip; IPAddress _ap_static_gw; IPAddress _ap_static_sn; IPAddress _sta_static_ip; IPAddress _sta_static_gw; IPAddress _sta_static_sn; + IPAddress _sta_static_dns; - int _paramsCount = 0; - int _minimumQuality = -1; - boolean _removeDuplicateAPs = true; - boolean _shouldBreakAfterConfig = false; - boolean _tryWPS = false; + // defaults + const byte DNS_PORT = 53; + const byte HTTP_PORT = 80; + String _apName = "no-net"; + String _apPassword = ""; + String _ssid = ""; + String _pass = ""; + + // options flags + unsigned long _configPortalTimeout = 0; // ms close config portal loop if set (depending on _cp/webClientCheck options) + unsigned long _connectTimeout = 0; // ms stop trying to connect to ap if set + unsigned long _saveTimeout = 0; // ms stop trying to connect to ap on saves, in case bugs in esp waitforconnectresult + unsigned long _configPortalStart = 0; // ms config portal start time (updated for timeouts) + unsigned long _webPortalAccessed = 0; // ms last web access time + WiFiMode_t _usermode = WIFI_OFF; + String _wifissidprefix = FPSTR(S_ssidpre); // auto apname prefix prefix+chipid + uint8_t _lastconxresult = WL_IDLE_STATUS; + int _numNetworks = 0; + 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 - const char* _customHeadElement = ""; + #ifdef ESP32 + static uint8_t _lastconxresulttmp; // tmp var for esp32 callback + #endif - //String getEEPROMString(int start, int len); - //void setEEPROMString(int start, int len, String string); + #ifndef WL_STATION_WRONG_PASSWORD + uint8_t WL_STATION_WRONG_PASSWORD = 7; // @kludge define a WL status for wrong password + #endif + + // parameter options + int _minimumQuality = -1; // filter wifiscan ap by this rssi + int _staShowStaticFields = 0; // ternary always show static ip fields, only if not set in code, never(cannot change ips via web!) + 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 _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 _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 + boolean _showInfoErase = true; // info page erase button + boolean _enableConfigPortal = true; // use config portal if autoconnect failed + 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(); + +#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); + bool setSTAConfig(); + bool wifiConnectDefault(); + bool wifiConnectNew(String ssid, String pass); - int status = WL_IDLE_STATUS; - int connectWifi(String ssid, String pass); uint8_t waitForConnectResult(); + uint8_t waitForConnectResult(uint16_t timeout); + void updateConxResult(uint8_t status); + // webserver handlers void handleRoot(); void handleWifi(boolean scan); void handleWifiSave(); void handleInfo(); void handleReset(); void handleNotFound(); - void handle204(); + void handleExit(); + void handleClose(); + // void handleErase(); + void handleErase(boolean opt); + void handleParam(); + void handleWiFiStatus(); + void handleRequest(); + void handleParamSave(); + void doParamSave(); + boolean captivePortal(); boolean configPortalHasTimeout(); + uint8_t processConfigPortal(); + void stopCaptivePortal(); - // DNS server - const byte DNS_PORT = 53; + // wifi platform abstractions + bool WiFi_Mode(WiFiMode_t m); + bool WiFi_Mode(WiFiMode_t m,bool persistent); + bool WiFi_Disconnect(); + bool WiFi_enableSTA(bool enable); + bool WiFi_enableSTA(bool enable,bool persistent); + bool WiFi_eraseConfig(); + uint8_t WiFi_softap_num_stations(); + bool WiFi_hasAutoConnect(); + void WiFi_autoReconnect(); + String WiFi_SSID(); + bool WiFi_scanNetworks(); + 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 + void WiFiEvent(WiFiEvent_t event, system_event_info_t info); + #endif + + // output helpers + String getParamOut(); + String getIpForm(String id, String title, String value); + String getScanItemOut(); + String getStaticOut(); + String getHTTPHead(String title); + String getMenuOut(); //helpers int getRSSIasQuality(int RSSI); boolean isIp(String str); String toStringIp(IPAddress ip); + boolean validApPassword(); + String encryptionTypeStr(uint8_t authmode); + void reportStatus(String &page); + String getInfoData(String id); + // flags boolean connect; - boolean _debug = true; + boolean abort; + boolean reset = false; + boolean configPortalActive = false; + boolean webPortalActive = false; + boolean portalTimeoutResult = false; + boolean portalAbortResult = false; + boolean storeSTAmode = true; // option store persistent STA mode in connectwifi + int timer = 0; + + // WiFiManagerParameter + int _paramsCount = 0; + int _max_params; + WiFiManagerParameter** _params = NULL; - void (*_apcallback)(WiFiManager*) = NULL; - void (*_savecallback)(void) = NULL; - void (*_resetcallback)(void) = NULL; - - int _max_params; - WiFiManagerParameter** _params; + // debugging + typedef enum { + DEBUG_ERROR = 0, + DEBUG_NOTIFY = 1, // default + DEBUG_VERBOSE = 2, + DEBUG_DEV = 3, + DEBUG_MAX = 4 + } wm_debuglevel_t; + boolean _debug = true; + uint8_t _debugLevel = DEBUG_DEV; + Stream& _debugPort; // debug output stream ref + template - void DEBUG_WM(Generic text); + void DEBUG_WM(Generic text); + + template + void DEBUG_WM(wm_debuglevel_t level,Generic text); + template + void DEBUG_WM(Generic text,Genericb textb); + template + void DEBUG_WM(wm_debuglevel_t level, Generic text,Genericb textb); + + // callbacks + std::function _apcallback; + std::function _savecallback; + std::function _presavecallback; + void (*_resetcallback)(void) = NULL; // @todo change to std func template auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { return obj->fromString(s); } auto optionalIPFromString(...) -> bool { - DEBUG_WM("NO fromString METHOD ON IPAddress, you need ESP8266 core 2.1.0 or newer for Custom IP configuration to work."); + // DEBUG_WM("NO fromString METHOD ON IPAddress, you need ESP8266 core 2.1.0 or newer for Custom IP configuration to work."); return false; } }; diff --git a/examples/Advanced/Advanced.ino b/examples/Advanced/Advanced.ino new file mode 100644 index 0000000..700ab6c --- /dev/null +++ b/examples/Advanced/Advanced.ino @@ -0,0 +1,103 @@ +/** + * WiFiManager advanced demo, contains advanced configurartion options + * Implements TRIGGEN_PIN button press, press for ondemand configportal, hold for 3 seconds for reset settings. + */ +#include // https://github.com/tzapu/WiFiManager + +#define TRIGGER_PIN 0 + +WiFiManager wm; + +void setup() { + Serial.begin(115200); + Serial.setDebugOutput(true); + delay(3000); + Serial.println("\n Starting"); + + pinMode(TRIGGER_PIN, INPUT); + + // wm.resetSettings(); // wipe settings + + // add a custom input field + int customFieldLength = 40; + WiFiManagerParameter custom_field("customfield", "Custom Field", "Default Value", customFieldLength); + wm.addParameter(&custom_field); + + // custom menu via array or vector + // + // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (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(60); // auto close configportal after n seconds + // wifiManager.setCaptivePortalEnable(false); // disable captive portal redirection + + // wifi scan settings + // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) + // wm.setMinimumSignalQuality(20); // set min RSSI (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, not recommended for production code + delay(50); + if( digitalRead(TRIGGER_PIN) == LOW ){ + + // holding button 3000 ms, reset settings + delay(3000); // reset delay hold + if( digitalRead(TRIGGER_PIN) == LOW ){ + Serial.println("Erasing Config"); + wm.resetSettings(); + ESP.restart(); + } + + // start portal w delay + Serial.println("Starting config portal"); + wm.setConfigPortalTimeout(120); + + if (!wm.startConfigPortal("OnDemandAP")) { + Serial.println("failed to connect or hit timeout"); + delay(3000); + // ESP.restart(); + } else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + } + } +} + +void loop() { + checkButton(); + // put your main code here, to run repeatedly: +} diff --git a/examples/AutoConnect/AutoConnect.ino b/examples/AutoConnect/AutoConnect.ino deleted file mode 100644 index 0c44909..0000000 --- a/examples/AutoConnect/AutoConnect.ino +++ /dev/null @@ -1,38 +0,0 @@ -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#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 53% rename from examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino rename to examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index 7e6c373..fea3287 100644 --- a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -1,18 +1,20 @@ -#include //this needs to be first, or it all crashes and burns... +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager +#include // https://github.com/bblanchon/ArduinoJson -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager - -#include //https://github.com/bblanchon/ArduinoJson +#ifdef ESP32 + #include +#endif //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; @@ -23,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..."); @@ -56,74 +53,89 @@ 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"); } - configFile.close(); } } } else { 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", blynk_token, 32); + 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.setTimeout(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 - ESP.reset(); + // 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) { @@ -131,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 60% rename from examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino rename to examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino index 3f391ae..35b32ed 100644 --- a/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino +++ b/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino @@ -1,19 +1,16 @@ -#include //this needs to be first, or it all crashes and burns... +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager +#include // https://github.com/bblanchon/ArduinoJson -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager - -#include //https://github.com/bblanchon/ArduinoJson +#ifdef ESP32 + #include +#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"; @@ -28,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..."); @@ -60,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"); } @@ -87,59 +74,54 @@ 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.setTimeout(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 - ESP.reset(); + // if we still have not connected restart and try all over again + ESP.restart(); delay(5000); } @@ -149,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) { @@ -157,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) { @@ -173,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 70% rename from examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino rename to examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino index 77b264b..4a2c4dd 100644 --- a/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino +++ b/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino @@ -1,19 +1,16 @@ -#include //https://github.com/esp8266/Arduino +// LED will blink when in config mode -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager +#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 @@ -31,27 +28,27 @@ 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.reset(); + ESP.restart(); delay(1000); } @@ -59,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/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..e8be11b --- /dev/null +++ b/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -0,0 +1,198 @@ +/** + * This is a kind of unit test for DEV for now + */ +#include // https://github.com/tzapu/WiFiManager + +#define TRIGGER_PIN 0 +const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; + +WiFiManager wm; + +char ssid[] = "*************"; // your network SSID (name) +char pass[] = "********"; // your network password + +void debugchipid(){ + // WiFi.mode(WIFI_STA); + // WiFi.printDiag(Serial); + // Serial.println(modes[WiFi.getMode()]); + + // ESP.eraseConfig(); + // wm.resetSettings(); + // wm.erase(true); + WiFi.mode(WIFI_AP); + // WiFi.softAP(); + WiFi.enableAP(true); + delay(500); + // esp_wifi_start(); + delay(1000); + WiFi.printDiag(Serial); + delay(60000); + ESP.restart(); + + // AP esp_267751 + // 507726A4AE30 + // ESP32 Chip ID = 507726A4AE30 +} + +void saveCallback(){ + Serial.println("saveCallback fired"); +} + + +//gets called when WiFiManager enters configuration mode +void configModeCallback (WiFiManager *myWiFiManager) { + Serial.println("configModeCallback fired"); + // myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // Serial.println(WiFi.softAPIP()); + //if you used auto generated SSID, print it + // Serial.println(myWiFiManager->getConfigPortalSSID()); +} + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.setDebugOutput(true); + // delay(3000); + Serial.println("\n Starting"); + // WiFi.setSleepMode(WIFI_NONE_SLEEP); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + // WiFiManager wm; + + 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"); + wm.setAPCallback(configModeCallback); + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep + //in seconds + // wm.setConfigPortalTimeout(600); + // wm.setConnectTimeout(5); + // wm.setShowStaticFields(true); + + // uint8_t menu[] = {wm.MENU_WIFI,wm.MENU_INFO,wm.MENU_PARAM,wm.MENU_CLOSE}; + // wm.setMenu(menu); + + // std::vector menu = {wm.MENU_WIFI,wm.MENU_INFO,wm.MENU_PARAM,wm.MENU_CLOSE,wm.MENU_SEP,wm.MENU_ERASE,wm.MENU_EXIT}; + // wm.setMenu(menu); + +// std::vector menu = {wm.MENU_WIFI,wm.MENU_INFO,wm.MENU_PARAM,wm.MENU_CLOSE,wm.MENU_SEP,wm.MENU_ERASE,wm.MENU_EXIT}; + // wm.setMenu(menu); + + + WiFiManagerParameter custom_html("

This Is Custom HTML

"); + WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); + 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}'"); + + // callbacks + wm.setSaveConfigCallback(saveCallback); + + //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); + + // MENU_WIFI = 0, + // MENU_WIFINOSCAN = 1, + // MENU_INFO = 2, + // MENU_PARAM = 3, + // MENU_CLOSE = 4, + // MENU_RESTART = 5, + // MENU_EXIT = 6, + // MENU_ERASE = 7, + // MENU_SEP = 8 + + // const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; + // wm.setMenu(menu,9); + + std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; + wm.setMenu(menu); + + // 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 { + // start configportal always + // wm.setConfigPortalTimeout(60); + // wm.startConfigPortal(); + } + + pinMode(TRIGGER_PIN, INPUT); +} + +void loop() { + // is configuration portal requested? + if ( digitalRead(TRIGGER_PIN) == LOW ) { + Serial.println("BUTTON PRESSED"); + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + //reset settings - for testing + //wm.resetSettings(); + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep, in seconds + wm.setConfigPortalTimeout(120); + + //it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + + //WITHOUT THIS THE AP DOES NOT SEEM TO WORK PROPERLY WITH SDK 1.5 , update to at least 1.5.1 + //WiFi.mode(WIFI_STA); + + // disable captive portal redirection + // wm.setCaptivePortalEnable(false); + + 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 :)"); + } + } + + // put your main code here, to run repeatedly: + delay(5000); +} 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/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 83% rename from examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino rename to examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino index 9491760..d3c4ed8 100644 --- a/examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino +++ b/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino @@ -1,9 +1,4 @@ -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include "WiFiManager.h" //https://github.com/tzapu/WiFiManager +#include // https://github.com/tzapu/WiFiManager void configModeCallback (WiFiManager *myWiFiManager) { Serial.println("Entered config mode"); @@ -32,7 +27,7 @@ void setup() { if(!wifiManager.autoConnect()) { Serial.println("failed to connect and hit timeout"); //reset and try again, or maybe put it to deep sleep - ESP.reset(); + ESP.restart(); delay(1000); } diff --git a/examples/AutoConnectWithReset/AutoConnectWithReset.ino b/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino similarity index 75% rename from examples/AutoConnectWithReset/AutoConnectWithReset.ino rename to examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino index 5af3b1f..53a0d13 100644 --- a/examples/AutoConnectWithReset/AutoConnectWithReset.ino +++ b/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino @@ -1,11 +1,5 @@ -#include //this needs to be first, or it all crashes and burns... - -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager void setup() { // put your setup code here, to run once: @@ -30,7 +24,7 @@ void setup() { if (!wifiManager.autoConnect("AutoConnectAP", "password")) { Serial.println("failed to connect, we should reset as see if it connects"); delay(3000); - ESP.reset(); + ESP.restart(); delay(5000); } diff --git a/examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino b/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino similarity index 86% rename from examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino rename to examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino index 86556d3..9f88e47 100644 --- a/examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino +++ b/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino @@ -1,12 +1,5 @@ -#include //this needs to be first, or it all crashes and burns... - -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager - +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager /************************************************************************************** * this example shows how to set a static IP configuration for the ESP @@ -15,9 +8,7 @@ * if you want the ability to configure and persist the new IP configuration * look at the FS examples, which save the config to file *************************************************************************************/ - - - + //default custom static IP //char static_ip[16] = "10.0.1.59"; //char static_gw[16] = "10.0.1.1"; @@ -61,7 +52,7 @@ void setup() { if (!wifiManager.autoConnect("AutoConnectAP", "password")) { Serial.println("failed to connect, we should reset as see if it connects"); delay(3000); - ESP.reset(); + ESP.restart(); delay(5000); } diff --git a/examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino b/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino similarity index 78% rename from examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino rename to examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino index c90cf10..9df428d 100644 --- a/examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino +++ b/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino @@ -1,11 +1,4 @@ -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager - - +#include // https://github.com/tzapu/WiFiManager void setup() { // put your setup code here, to run once: @@ -20,7 +13,7 @@ void setup() { //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds - wifiManager.setTimeout(180); + wifiManager.setConfigPortalTimeout(180); //fetches ssid and pass and tries to connect //if it does not connect it starts an access point with the specified name @@ -30,7 +23,7 @@ void setup() { Serial.println("failed to connect and hit timeout"); delay(3000); //reset and try again, or maybe put it to deep sleep - ESP.reset(); + ESP.restart(); delay(5000); } 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 2f2d0cc..0000000 --- a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ /dev/null @@ -1,60 +0,0 @@ -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#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 - - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println("\n Starting"); - - 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 - WiFiManager wifiManager; - - //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.setTimeout(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); - - if (!wifiManager.startConfigPortal("OnDemandAP")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - //reset and try again, or maybe put it to deep sleep - ESP.reset(); - 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/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 e15593b..9a0b082 100644 --- a/extras/WiFiManager.template.html +++ b/extras/WiFiManager.template.html @@ -6,15 +6,158 @@ {v} - + + + + + + + + + + + + diff --git a/library.json b/library.json index 8f0830a..0ceb4c8 100644 --- a/library.json +++ b/library.json @@ -1,13 +1,29 @@ { "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" }, "frameworks": "arduino", - "platforms": "espressif8266", - "version": "0.14" + "platforms": + [ + "espressif8266", + "espressif32" + ], + "version": "1.0.0" } diff --git a/library.properties b/library.properties index e0420ad..5ee6e46 100644 --- a/library.properties +++ b/library.properties @@ -1,9 +1,9 @@ name=WiFiManager -version=0.14 -author=tzapu -maintainer=tzapu -sentence=ESP8266 WiFi Connection manager with fallback web configuration portal -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 +architectures=esp8266,esp32 diff --git a/strings_en.h b/strings_en.h new file mode 100644 index 0000000..db8e6bc --- /dev/null +++ b/strings_en.h @@ -0,0 +1,327 @@ +/** + * strings_en.h + * engligh strings for + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ + +#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! + +const char HTTP_HEAD_START[] PROGMEM = "{v}"; +const char HTTP_SCRIPT[] PROGMEM = ""; +const char HTTP_HEAD_END[] PROGMEM = "
"; + +const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

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

\n", // MENU_WIFI +"

\n", // MENU_WIFINOSCAN +"

\n", // MENU_INFO +"

\n",//MENU_PARAM +"

\n", // MENU_CLOSE +"

\n",// MENU_RESTART +"

\n", // MENU_EXIT +"

\n", // MENU_ERASE +"

" // MENU_SEP +}; + +// const char HTTP_PORTAL_OPTIONS[] PROGMEM = strcat(HTTP_PORTAL_MENU[0] , HTTP_PORTAL_MENU[3] , HTTP_PORTAL_MENU[7]); +const char HTTP_PORTAL_OPTIONS[] PROGMEM = ""; +const char HTTP_ITEM_QI[] PROGMEM = ""; // rssi icons +const char HTTP_ITEM_QP[] PROGMEM = "
{r}%
"; // rssi percentage +const char HTTP_ITEM[] PROGMEM = "
{v}{qi}{qp}
"; // {q} = HTTP_ITEM_QI, {r} = HTTP_ITEM_QP +// const char HTTP_ITEM[] PROGMEM = "
{v} {R} {r}% {q} {e}
"; // test all tokens + +const char HTTP_FORM_START[] PROGMEM = "
"; +const char HTTP_FORM_WIFI[] PROGMEM = "
"; +const char HTTP_FORM_WIFI_END[] PROGMEM = ""; +const char HTTP_FORM_STATIC_HEAD[] PROGMEM = "

"; +const char HTTP_FORM_END[] PROGMEM = "

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

"; +const char HTTP_FORM_PARAM[] PROGMEM = "
"; + +const char HTTP_SCAN_LINK[] PROGMEM = "
"; +const char HTTP_SAVED[] PROGMEM = "
Saving Credentials
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; +const char HTTP_PARAMSAVED[] PROGMEM = "
Saved
"; +const char HTTP_END[] PROGMEM = "
"; +const char HTTP_ERASEBTN[] PROGMEM = "
"; + +const char HTTP_STATUS_ON[] PROGMEM = "
Connected to {v}
with IP {i}
"; +const char HTTP_STATUS_OFF[] PROGMEM = "
Not Connected to {v}{r}
"; +const char HTTP_STATUS_OFFPW[] PROGMEM = "
Authentication Failure"; // STATION_WRONG_PASSWORD, no eps32 +const char HTTP_STATUS_OFFNOAP[] PROGMEM = "
AP not found"; // WL_NO_SSID_AVAIL +const char HTTP_STATUS_OFFFAIL[] PROGMEM = "
Could not Connect"; // WL_CONNECT_FAILED +const char HTTP_STATUS_NONE[] PROGMEM = "
No AP set
"; +const char HTTP_BR[] PROGMEM = "
"; + +const char HTTP_STYLE[] PROGMEM = ""; + +const char HTTP_HELP[] PROGMEM = + "

Available Pages


" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "
PageFunction
/Menu page.
/wifiShow WiFi scan results and enter WiFi configuration.(/0wifi noscan)
/wifisaveSave WiFi configuration information and configure device. Needs variables supplied.
/paramParameter page
/infoInformation page
/closeClose the captiveportal popup,configportal will remain active
/exitExit Config Portal, configportal will close
/restartReboot the device
/eraseErase WiFi configuration and reboot Device. Device will not reconnect to a network until new WiFi configuration data is entered.
" + "

More information about WiFiManager at https://github.com/tzapu/WiFiManager."; + +#ifdef JSTEST +const char HTTP_JS[] PROGMEM = +""; +#endif + +// Info html +#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_aphost[] PROGMEM = "
Acccess Point Hostname
{1}
"; +#else + const char HTTP_INFO_esphead[] PROGMEM = "

esp8266


"; + const char HTTP_INFO_flashsize[] PROGMEM = "
Real Flash Size
{1} bytes
"; + const char HTTP_INFO_fchipid[] PROGMEM = "
Flash Chip ID
{1}
"; + const char HTTP_INFO_corever[] PROGMEM = "
Core Version
{1}
"; + const char HTTP_INFO_bootver[] PROGMEM = "
Boot Version
{1}
"; + const char HTTP_INFO_memsketch[] PROGMEM = "
Memory - Sketch Size
Used / Total bytes
{1} / {2}"; + const char HTTP_INFO_memsmeter[] PROGMEM = "
"; + const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
{1}
"; +#endif + +const char HTTP_INFO_freeheap[] PROGMEM = "
Memory - Free Heap
{1} bytes available
"; +const char HTTP_INFO_wifihead[] PROGMEM = "

WiFi


"; +const char HTTP_INFO_uptime[] PROGMEM = "
Uptime
{1} Mins {2} Secs
"; +const char HTTP_INFO_chipid[] PROGMEM = "
Chip ID
{1}
"; +const char HTTP_INFO_idesize[] PROGMEM = "
Flash Size
{1} bytes
"; +const char HTTP_INFO_sdkver[] PROGMEM = "
SDK Version
{1}
"; +const char HTTP_INFO_cpufreq[] PROGMEM = "
CPU Frequency
{1}MHz
"; +const char HTTP_INFO_apip[] PROGMEM = "
Access Point IP
{1}
"; +const char HTTP_INFO_apmac[] PROGMEM = "
Access Point MAC
{1}
"; +const char HTTP_INFO_apssid[] PROGMEM = "
SSID
{1}
"; +const char HTTP_INFO_apbssid[] PROGMEM = "
BSSID
{1}
"; +const char HTTP_INFO_staip[] PROGMEM = "
Station IP
{1}
"; +const char HTTP_INFO_stagw[] PROGMEM = "
Station Gateway
{1}
"; +const char HTTP_INFO_stasub[] PROGMEM = "
Station Subnet
{1}
"; +const char HTTP_INFO_dnss[] PROGMEM = "
DNS Server
{1}
"; +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"; +const char S_n[] PROGMEM = "No"; +const char S_enable[] PROGMEM = "Enabled"; +const char S_disable[] PROGMEM = "Disabled"; +const char S_GET[] PROGMEM = "GET"; +const char S_POST[] PROGMEM = "POST"; +const char S_NA[] PROGMEM = "Unknown"; + +const char S_titlewifisaved[] PROGMEM = "Credentials Saved"; +const char S_titlewifi[] PROGMEM = "Config ESP"; +const char S_titleinfo[] PROGMEM = "Info"; +const char S_titleparam[] PROGMEM = "Setup"; +const char S_titleparamsaved[] PROGMEM = "Setup Saved"; +const char S_titleexit[] PROGMEM = "Exit"; +const char S_titlereset[] PROGMEM = "Reset"; +const char S_titleerase[] PROGMEM = "Erase"; +const char S_titleclose[] PROGMEM = "Close"; +const char S_options[] PROGMEM = "options"; +const char S_nonetworks[] PROGMEM = "No networks found. Refresh to scan again."; +const char S_staticip[] PROGMEM = "Static IP"; +const char S_staticgw[] PROGMEM = "Static Gateway"; +const char S_staticdns[] PROGMEM = "Static DNS"; +const char S_subnet[] PROGMEM = "Subnet"; +const char S_exiting[] PROGMEM = "Exiting"; +const char S_resetting[] PROGMEM = "Module will reset in a few seconds."; +const char S_closing[] PROGMEM = "You can close the page, portal will continue to run"; +const char S_error[] PROGMEM = "An Error Occured"; +const char S_notfound[] PROGMEM = "File Not Found\n\n"; +const char S_uri[] PROGMEM = "URI: "; +const char S_method[] PROGMEM = "\nMethod: "; +const char S_args[] PROGMEM = "\nArguments: "; +const char S_parampre[] PROGMEM = "param_"; + +// debug strings +const char D_HR[] PROGMEM = "--------------------"; + +// END WIFI_MANAGER_OVERRIDE_STRINGS +#endif + +// ----------------------------------------------------------------------------------------------- +// DO NOT EDIT BELOW THIS LINE + +const uint8_t _nummenutokens = 9; +const char * const _menutokens[9] PROGMEM = { + "wifi", + "wifinoscan", + "info", + "param", + "close", + "restart", + "exit", + "erase", + "sep" +}; + +const char R_root[] PROGMEM = "/"; +const char R_wifi[] PROGMEM = "/wifi"; +const char R_wifinoscan[] PROGMEM = "/0wifi"; +const char R_wifisave[] PROGMEM = "/wifisave"; +const char R_info[] PROGMEM = "/info"; +const char R_param[] PROGMEM = "/param"; +const char R_paramsave[] PROGMEM = "/paramsave"; +const char R_restart[] PROGMEM = "/restart"; +const char R_exit[] PROGMEM = "/exit"; +const char R_close[] PROGMEM = "/close"; +const char R_erase[] PROGMEM = "/erase"; +const char R_status[] PROGMEM = "/status"; + + +//Strings +const char S_ip[] PROGMEM = "ip"; +const char S_gw[] PROGMEM = "gw"; +const char S_sn[] PROGMEM = "sn"; +const char S_dns[] PROGMEM = "dns"; + +// softap ssid default prefix +#ifdef ESP8266 + const char S_ssidpre[] PROGMEM = "ESP"; +#elif defined(ESP32) + const char S_ssidpre[] PROGMEM = "ESP32"; +#else + const char S_ssidpre[] PROGMEM = "WM"; +#endif + +//Tokens +//@todo consolidate and reduce +const char T_ss[] PROGMEM = "{"; // token start sentinel +const char T_es[] PROGMEM = "}"; // token end sentinel +const char T_1[] PROGMEM = "{1}"; // @token 1 +const char T_2[] PROGMEM = "{2}"; // @token 2 +const char T_v[] PROGMEM = "{v}"; // @token v +const char T_I[] PROGMEM = "{I}"; // @token I +const char T_i[] PROGMEM = "{i}"; // @token i +const char T_n[] PROGMEM = "{n}"; // @token n +const char T_p[] PROGMEM = "{p}"; // @token p +const char T_t[] PROGMEM = "{t}"; // @token t +const char T_l[] PROGMEM = "{l}"; // @token l +const char T_c[] PROGMEM = "{c}"; // @token c +const char T_e[] PROGMEM = "{e}"; // @token e +const char T_q[] PROGMEM = "{q}"; // @token q +const char T_r[] PROGMEM = "{r}"; // @token r +const char T_R[] PROGMEM = "{R}"; // @token R +const char T_h[] PROGMEM = "{h}"; // @token h + +// http +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 +{ + "WL_IDLE_STATUS", // 0 STATION_IDLE + "WL_NO_SSID_AVAIL", // 1 STATION_NO_AP_FOUND + "WL_SCAN_COMPLETED", // 2 + "WL_CONNECTED", // 3 STATION_GOT_IP + "WL_CONNECT_FAILED", // 4 STATION_CONNECT_FAIL, STATION_WRONG_PASSWORD(NI) + "WL_CONNECTION_LOST", // 5 + "WL_DISCONNECTED", // 6 + "WL_STATION_WRONG_PASSWORD" // 7 KLUDGE +}; + +#ifdef ESP32 +const char * const AUTH_MODE_NAMES[] PROGMEM +{ + "OPEN", + "WEP", + "WPA_PSK", + "WPA2_PSK", + "WPA_WPA2_PSK", + "WPA2_ENTERPRISE", + "MAX" +}; +#elif defined(ESP8266) +const char * const AUTH_MODE_NAMES[] PROGMEM +{ + "", + "", + "WPA_PSK", // 2 ENC_TYPE_TKIP + "", + "WPA2_PSK", // 4 ENC_TYPE_CCMP + "WEP", // 5 ENC_TYPE_WEP + "", + "OPEN", //7 ENC_TYPE_NONE + "WPA_WPA2_PSK", // 8 ENC_TYPE_AUTO +}; +#endif + +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 diff --git a/travis/common.sh b/travis/common.sh index d115085..4b3e655 100644 --- a/travis/common.sh +++ b/travis/common.sh @@ -2,6 +2,7 @@ function build_examples() { + excludes=("$@") # track the exit code for this platform local exit_code=0 # loop through results and add them to the array @@ -19,6 +20,14 @@ function build_examples() # store the filename for the example without the path local example_file=$(basename $example) + # skip files listed as excludes + for exclude in "${excludes[@]}"; do + if [ "${example_file}" == "${exclude}" ] ; then + echo ">>>>>>>>>>>>>>>>>>>>>>>> Skipping ${example_file} <<<<<<<<<<<<<<<<<<<<<<<<<<" + continue 2 + fi + done + echo "$example_file: " local sketch="$example_dir/$example_file" echo "$sketch"