From ffdc117a6eea9ff155f8d2ff98ec31ff643239c2 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Sun, 27 Dec 2015 11:17:29 +0200 Subject: [PATCH 01/61] added AP quality added padlock for secured networks moved more stuff to PROGMEM --- WiFiManager.cpp | 22 +++++++++++++++++++++- WiFiManager.h | 9 ++++++--- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 2d29133..61e31d6 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -333,8 +333,17 @@ void WiFiManager::handleWifi(bool scan) { { DEBUG_PRINT(WiFi.SSID(i)); DEBUG_PRINT(WiFi.RSSI(i)); - String item = HTTP_ITEM; + String item = FPSTR(HTTP_ITEM); + String rssiQ; + rssiQ += getRSSIasQuality(WiFi.RSSI(i)); item.replace("{v}", WiFi.SSID(i)); + item.replace("{r}", rssiQ); + if(WiFi.encryptionType(i) != ENC_TYPE_NONE) { + item.replace("{i}", FPSTR(HTTP_ITEM_PADLOCK)); + } else { + item.replace("{i}", ""); + } + //DEBUG_PRINT(item); server->sendContent(item); delay(0); } @@ -436,7 +445,18 @@ void WiFiManager::DEBUG_PRINT(Generic text) { } +int WiFiManager::getRSSIasQuality(int RSSI) { + int quality = 0; + if(RSSI <= -100){ + quality = 0; + }else if(RSSI >= -50){ + quality = 100; + } else { + quality = 2 * (RSSI + 100); + } + return quality; +} /** Is this an IP? */ boolean WiFiManager::isIp(String str) { diff --git a/WiFiManager.h b/WiFiManager.h index 77ca589..84cf7a5 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -26,7 +26,8 @@ const char HTTP_200[] PROGMEM = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\ const char HTTP_STYLE[] PROGMEM = ""; const char HTTP_SCRIPT[] PROGMEM = ""; const char HTTP_HEAD_END[] PROGMEM = ""; -//const char HTTP_ITEM[] PROGMEM = "
{v}
"; +const char HTTP_ITEM[] PROGMEM = "
{v} {r}% {i}
"; +const char HTTP_ITEM_PADLOCK[] PROGMEM = ""; const char HTTP_FORM[] 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 = ""; @@ -71,7 +72,7 @@ private: //const String HTTP_STYLE = ""; //const String HTTP_SCRIPT = ""; //const String HTTP_HEAD_END = ""; - const String HTTP_ITEM = "
{v}
"; + //const String HTTP_ITEM = "
{v}
"; //const String HTTP_FORM = "

"; //const String HTTP_SAVED = "
Credentials Saved
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; //const String HTTP_END = ""; @@ -110,7 +111,9 @@ private: // DNS server const byte DNS_PORT = 53; - + + //helpers + int getRSSIasQuality(int RSSI); boolean isIp(String str); String toStringIp(IPAddress ip); From ec1a55bffcb1f5b22657ad996d27823120e9cd5c Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 28 Dec 2015 14:32:36 +0200 Subject: [PATCH 02/61] new padlock icon --- WiFiManager.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.h b/WiFiManager.h index 84cf7a5..cbcba5c 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -27,7 +27,7 @@ const char HTTP_STYLE[] PROGMEM = ""; +const char HTTP_STYLE[] PROGMEM = ""; const char HTTP_SCRIPT[] PROGMEM = ""; -const char HTTP_HEAD_END[] PROGMEM = ""; +const char HTTP_HEAD_END[] PROGMEM = "
"; +const char HTTP_PORTAL_OPTIONS[] PROGMEM = "

"; const char HTTP_ITEM[] PROGMEM = "
{v} {r}% {i}
"; -const char HTTP_ITEM_PADLOCK[] PROGMEM = ""; -const char HTTP_FORM[] PROGMEM = "

"; +const char HTTP_ITEM_PADLOCK[] PROGMEM = ""; +const char HTTP_FORM[] 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 = ""; +const char HTTP_END[] PROGMEM = "
"; class WiFiManager @@ -84,16 +85,16 @@ private: void begin(char const *apName); void begin(char const *apName, char const *apPasswd); - int _eepromStart; + int _eepromStart; const char* _apName = "no-net"; const char* _apPasswd = NULL; - String _ssid = ""; - String _pass = ""; + String _ssid = ""; + String _pass = ""; unsigned long timeout = 0; unsigned long start = 0; - IPAddress _ip; - IPAddress _gw; - IPAddress _sn; + IPAddress _ip; + IPAddress _gw; + IPAddress _sn; String getEEPROMString(int start, int len); void setEEPROMString(int start, int len, String string); From a69c5e2b93abf3dcf1d6d707847c4bca8a9f2311 Mon Sep 17 00:00:00 2001 From: Maximiliano Duarte Date: Wed, 30 Dec 2015 12:12:57 -0300 Subject: [PATCH 04/61] add keywords.txt to standardize the library and appear in Library Manager --- keywords.txt | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 keywords.txt diff --git a/keywords.txt b/keywords.txt new file mode 100644 index 0000000..f7f8495 --- /dev/null +++ b/keywords.txt @@ -0,0 +1,29 @@ +####################################### +# Syntax Coloring Map For WifiManager +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +WiFiManager KEYWORD1 + + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +autoConnect KEYWORD2 +getSSID KEYWORD2 +getPassword KEYWORD2 +resetSettings KEYWORD2 +urldecode KEYWORD2 +setTimeout KEYWORD2 +setDebugOutput KEYWORD2 +setAPConfig KEYWORD2 +setAPCallback KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + +# LITERAL1 From 9350856d334a1664df19dceac6e462981159a268 Mon Sep 17 00:00:00 2001 From: Maximiliano Duarte Date: Wed, 30 Dec 2015 12:14:22 -0300 Subject: [PATCH 05/61] add library.json to standardize the library and appear in Library Manager --- library.json | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 library.json diff --git a/library.json b/library.json new file mode 100644 index 0000000..d82285b --- /dev/null +++ b/library.json @@ -0,0 +1,19 @@ +{ + "name": "WifiManager", + "keywords": "wifi, wi-fi, ESP8266", + "description": "ESP8266 WiFi Connection manager with fallback web configuration portal", + "repository": + { + "type": "git", + "url": "https://github.com/tzapu/WiFiManager.git" + }, + "authors": + { + "name": "tzapu", + "url": "http://tzapu.com" + }, + "frameworks": "arduino", + "platforms": "esp8266" + "version": "0.4", + "architecture": "esp8266", +} From 30f5a220cef7f35d5bb9ac4d1d002f9d5bec10f1 Mon Sep 17 00:00:00 2001 From: Maximiliano Duarte Date: Wed, 30 Dec 2015 12:16:42 -0300 Subject: [PATCH 06/61] add library.properties to standardize the library and appear in Library Manager --- library.properties | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 library.properties diff --git a/library.properties b/library.properties new file mode 100644 index 0000000..9f732a7 --- /dev/null +++ b/library.properties @@ -0,0 +1,9 @@ +name=WiFiManager +version=0.4 +author=tzapu +maintainer=tzapu +sentence=ESP8266 WiFi Connection manager with fallback web configuration portal +paragraph=Like this project? Please star it on GitHub! +category=Storage/Memory +url=https://github.com/tzapu/WiFiManager.git +architectures=esp8266 From 94eef239ebfce5dc7e6ca3d719dfb0818c8871fd Mon Sep 17 00:00:00 2001 From: Maximiliano Duarte Date: Wed, 30 Dec 2015 12:49:53 -0300 Subject: [PATCH 07/61] change space for tabs --- keywords.txt | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/keywords.txt b/keywords.txt index f7f8495..5a47c9c 100644 --- a/keywords.txt +++ b/keywords.txt @@ -12,15 +12,15 @@ WiFiManager KEYWORD1 ####################################### # Methods and Functions (KEYWORD2) ####################################### -autoConnect KEYWORD2 -getSSID KEYWORD2 -getPassword KEYWORD2 -resetSettings KEYWORD2 -urldecode KEYWORD2 -setTimeout KEYWORD2 -setDebugOutput KEYWORD2 -setAPConfig KEYWORD2 -setAPCallback KEYWORD2 +autoConnect KEYWORD2 +getSSI KEYWORD2 +getPasswor KEYWORD2 +resetSettings KEYWORD2 +urldecode KEYWORD2 +setTimeout KEYWORD2 +setDebugOutput KEYWORD2 +setAPConfig KEYWORD2 +setAPCallback KEYWORD2 ####################################### # Constants (LITERAL1) From ab23ca7b1835f4b81a97e9cc5033b90dc1b43457 Mon Sep 17 00:00:00 2001 From: Maximiliano Duarte Date: Thu, 31 Dec 2015 09:53:35 -0300 Subject: [PATCH 08/61] change category --- library.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library.properties b/library.properties index 9f732a7..8639fbb 100644 --- a/library.properties +++ b/library.properties @@ -4,6 +4,6 @@ author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal paragraph=Like this project? Please star it on GitHub! -category=Storage/Memory +category=Data Storage url=https://github.com/tzapu/WiFiManager.git architectures=esp8266 From 1a58897ab452cd7ede433e8a60387e46b23ecde1 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Sat, 2 Jan 2016 09:49:47 +0200 Subject: [PATCH 09/61] added some more thanks --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d95fe99..180eda1 100644 --- a/README.md +++ b/README.md @@ -121,14 +121,18 @@ This will set your captive portal to a specific IP should you need/want such a f wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); ``` ### Contributions and thanks +The support and help I got from the community has been nothing short of fenomenal. I can't thank you guys enough. This is my first real attept in developing open source stuff and I must say, now I understand why people are so dedicated to it, it is because of all the wonderful people involved. + +__THANK YOU__ + +[Maximiliano Duarte](https://github.com/domonetic) + [alltheblinkythings](https://github.com/alltheblinkythings) [Niklas Wall](https://github.com/niklaswall) [Jakub Piasecki](https://github.com/zaporylie) -[Maximiliano Duarte](https://github.com/domonetic) - [Peter Allan](https://github.com/alwynallan) [John Little](https://github.com/j0hnlittle) From 9fd11f13b66fae812c98c4916fc353124bec129e Mon Sep 17 00:00:00 2001 From: Alberto Ricci Bitti Date: Mon, 4 Jan 2016 10:44:56 +0100 Subject: [PATCH 10/61] connectWifi() now returns connection status, making its use more straightforward --- WiFiManager.cpp | 18 +++++------------- WiFiManager.h | 2 +- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index fc79a72..5567d7f 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -96,9 +96,7 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { //String pass = WiFi.psk(); WiFi.mode(WIFI_STA); - connectWifi(ssid, pass); - int s = WiFi.status(); - if (s == WL_CONNECTED) { + if(connectWifi(ssid, pass) == WL_CONNECTED) { DEBUG_PRINT(F("IP Address:")); DEBUG_PRINT(WiFi.localIP()); //connected @@ -127,16 +125,9 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { delay(2000); DEBUG_PRINT(F("Connecting to new AP")); connect = false; - //ssid = getSSID(); - //pass = getPassword(); - connectWifi(_ssid, _pass); - int s = WiFi.status(); - if (s != WL_CONNECTED) { + // using user-provided _ssid, _pass in place of system-stored ssid amd pass + if (connectWifi(_ssid, _pass) != WL_CONNECTED) { DEBUG_PRINT(F("Failed to connect.")); - //not connected, should retry everything - //ESP.reset(); - //delay(1000); - //return false; } else { //connected WiFi.mode(WIFI_STA); @@ -153,13 +144,14 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { } -void WiFiManager::connectWifi(String ssid, String pass) { +int WiFiManager::connectWifi(String ssid, String pass) { DEBUG_PRINT(F("Connecting as wifi client...")); //WiFi.disconnect(); WiFi.begin(ssid.c_str(), pass.c_str()); int connRes = WiFi.waitForConnectResult(); DEBUG_PRINT ("Connection result: "); DEBUG_PRINT ( connRes ); + return connRes; } diff --git a/WiFiManager.h b/WiFiManager.h index 27deed9..88211fc 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -101,7 +101,7 @@ private: bool keepLooping = true; int status = WL_IDLE_STATUS; - void connectWifi(String ssid, String pass); + int connectWifi(String ssid, String pass); void handleRoot(); void handleWifi(bool scan); From ead84aea361d46c6b0395bbd3650a3f353c3eae4 Mon Sep 17 00:00:00 2001 From: Alberto Ricci Bitti Date: Mon, 4 Jan 2016 10:57:43 +0100 Subject: [PATCH 11/61] Removed unused/commented code --- WiFiManager.cpp | 43 ------------------------------------------- WiFiManager.h | 3 --- 2 files changed, 46 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 5567d7f..5d566c0 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -16,14 +16,6 @@ WiFiManager::WiFiManager() { } -void WiFiManager::begin() { - begin("NoNetESP"); -} - -void WiFiManager::begin(char const *apName) { - begin(apName,NULL); -} - void WiFiManager::begin(char const *apName, char const *apPasswd) { dnsServer.reset(new DNSServer()); server.reset(new ESP8266WebServer(80)); @@ -113,7 +105,6 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { connect = false; begin(apName,apPasswd); - bool looping = true; while(timeout == 0 || millis() < start + timeout) { //DNS dnsServer->processNextRequest(); @@ -175,40 +166,6 @@ String WiFiManager::getPassword() { return _pass; } -/* -String WiFiManager::getEEPROMString(int start, int len) { - EEPROM.begin(512); - delay(10); - String string = ""; - for (int i = _eepromStart + start; i < _eepromStart + start + len; i++) { - //DEBUG_PRINT(i); - string += char(EEPROM.read(i)); - } - EEPROM.end(); - return string; -} -*/ -/* -void WiFiManager::setEEPROMString(int start, int len, String string) { - EEPROM.begin(512); - delay(10); - int si = 0; - for (int i = _eepromStart + start; i < _eepromStart + start + len; i++) { - char c; - if (si < string.length()) { - c = string[si]; - //DEBUG_PRINT(F("Wrote: "); - //DEBUG_PRINT(c); - } else { - c = 0; - } - EEPROM.write(i, c); - si++; - } - EEPROM.end(); - DEBUG_PRINT(F("Wrote " + string); -}*/ - String WiFiManager::urldecode(const char *src) { String decoded = ""; diff --git a/WiFiManager.h b/WiFiManager.h index 88211fc..35fa359 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -13,9 +13,6 @@ #define WiFiManager_h #include - -//#include -//#include #include #include #include From 807933270b6c05650d98dab550284decdeba1464 Mon Sep 17 00:00:00 2001 From: Alberto Ricci Bitti Date: Mon, 4 Jan 2016 13:17:06 +0100 Subject: [PATCH 12/61] Added "forceAP" parameter to autoconnect (defaulted to false, which leaves previous behaviour unchanged). If true, starts the configuration portal anyway (in my case I have a physical button to enter configuration) --- WiFiManager.cpp | 24 ++++++++++++------------ WiFiManager.h | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 5d566c0..5292d89 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -76,25 +76,25 @@ boolean WiFiManager::autoConnect(char const *apName) { return autoConnect(apName,NULL); } -boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { +boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd, bool forceAP) { DEBUG_PRINT(F("")); DEBUG_PRINT(F("AutoConnect")); // read eeprom for ssid and pass String ssid = getSSID(); String pass = getPassword(); - //use SDK functions to get SSID and pass - //String ssid = WiFi.SSID(); - //String pass = WiFi.psk(); - - WiFi.mode(WIFI_STA); - if(connectWifi(ssid, pass) == WL_CONNECTED) { - DEBUG_PRINT(F("IP Address:")); - DEBUG_PRINT(WiFi.localIP()); - //connected - return true; + + if ( ! forceAP ) { + // attempt to connect; should it fail, fall back to AP + WiFi.mode(WIFI_STA); + if(connectWifi(ssid, pass) == WL_CONNECTED) { + DEBUG_PRINT(F("IP Address:")); + DEBUG_PRINT(WiFi.localIP()); + //connected + return true; + } } - + //not connected //setup AP WiFi.mode(WIFI_AP); diff --git a/WiFiManager.h b/WiFiManager.h index 35fa359..4b9168c 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -38,7 +38,7 @@ public: boolean autoConnect(); boolean autoConnect(char const *apName); - boolean autoConnect(char const *apName, char const *apPasswd); + boolean autoConnect(char const *apName, char const *apPasswd, bool forceAP = false); String getSSID(); String getPassword(); From d8683d9f503ccb8ba2f924e5978ad5352330ea2a Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 4 Jan 2016 16:32:32 +0200 Subject: [PATCH 13/61] updated to 0.5 --- library.json | 4 ++-- library.properties | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/library.json b/library.json index d82285b..badf097 100644 --- a/library.json +++ b/library.json @@ -14,6 +14,6 @@ }, "frameworks": "arduino", "platforms": "esp8266" - "version": "0.4", - "architecture": "esp8266", + "version": "0.5", + "architecture": "esp8266", } diff --git a/library.properties b/library.properties index 8639fbb..c739029 100644 --- a/library.properties +++ b/library.properties @@ -1,9 +1,9 @@ name=WiFiManager -version=0.4 +version=0.5 author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal -paragraph=Like this project? Please star it on GitHub! +paragraph=Library for configuring ESP8266 modules WiFi credentials at runtime. category=Data Storage url=https://github.com/tzapu/WiFiManager.git architectures=esp8266 From caa808c265749f4c90b151fd60af0a03a960c7c9 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 4 Jan 2016 16:42:35 +0200 Subject: [PATCH 14/61] changed category --- library.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library.properties b/library.properties index c739029..55f390a 100644 --- a/library.properties +++ b/library.properties @@ -4,6 +4,6 @@ author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal paragraph=Library for configuring ESP8266 modules WiFi credentials at runtime. -category=Data Storage +category=Communication url=https://github.com/tzapu/WiFiManager.git architectures=esp8266 From 2ad6d0897c509cdebf056fa9868306e656d46872 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 4 Jan 2016 16:42:35 +0200 Subject: [PATCH 15/61] changed category fixed keywords --- keywords.txt | 6 +++--- library.properties | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/keywords.txt b/keywords.txt index 5a47c9c..79774cf 100644 --- a/keywords.txt +++ b/keywords.txt @@ -13,15 +13,15 @@ WiFiManager KEYWORD1 # Methods and Functions (KEYWORD2) ####################################### autoConnect KEYWORD2 -getSSI KEYWORD2 -getPasswor KEYWORD2 +getSSID KEYWORD2 +getPassword KEYWORD2 resetSettings KEYWORD2 urldecode KEYWORD2 setTimeout KEYWORD2 setDebugOutput KEYWORD2 setAPConfig KEYWORD2 setAPCallback KEYWORD2 - + ####################################### # Constants (LITERAL1) ####################################### diff --git a/library.properties b/library.properties index c739029..55f390a 100644 --- a/library.properties +++ b/library.properties @@ -4,6 +4,6 @@ author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal paragraph=Library for configuring ESP8266 modules WiFi credentials at runtime. -category=Data Storage +category=Communication url=https://github.com/tzapu/WiFiManager.git architectures=esp8266 From 311c80d4756ca27cf9c29fe32222acaa6286b1a3 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Tue, 5 Jan 2016 08:28:02 +0200 Subject: [PATCH 16/61] added Boards Manager instructions --- README.md | 71 +++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 48 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 180eda1..2431963 100644 --- a/README.md +++ b/README.md @@ -15,37 +15,37 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - 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. -## Still left to do +## Wishlist - ~~remove dependency on EEPROM library~~ -- move HTML Strings to PROGMEM +- ~~move HTML Strings to PROGMEM~~ - cleanup and streamline code - if timeout is set, extend it when a page is fetched in AP mode - add ability to configure more parameters than ssid/password - maybe allow setting ip of ESP after reboot - -## Releases -#### v0.4 - user contributed changes - Thank you - - added ability to password protect the configuration Access Point - - callback for enter configuration mode - - memory allocation improvements - -##### v0.3 - - removed the need for EEPROM and works with the 2.0.0 and above stable release of the ESP8266 for Arduino IDE package - - removed restart on save of credentials - - updated examples - -##### v0.2 -needs the latest staging version (or at least a recent release of the staging version) to work - -##### v0.1 -works with the staging release ver. 1.6.5-1044-g170995a, built on Aug 10, 2015 of the ESP8266 Arduino library. - +- ~~add to Arduino Boards Manager~~ +- add to PlatformIO +- add multiple sets of network credentials +- allow users to customize CSS ## Quick Start -- Make sure you have a recent package of the ESP8266 for Arduino IDE +You can either install through the Arduino Boards Manager or checkout the latest changes or a release from github + +#### Install through Boards Manager +__Currently version 0.5 works with release 2.0.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) + + - search for WiFiManager + ![WiFiManager package](http://i.imgur.com/18yIai8.png) + + - click Install and start using it + +#### Checkout from github +__Github version works with release 2.0.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 @@ -53,7 +53,7 @@ works with the staging release ver. 1.6.5-1044-g170995a, built on Aug 10, 2015 o #include ``` -- Initialise library, in your setup function add +- Initialize library, in your setup function add ```cpp WiFiManager wifiManager; ``` @@ -120,8 +120,33 @@ This will set your captive portal to a specific IP should you need/want such a f //set custom ip for portal wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); ``` + +## Releases +#### 0.5 + - Added to Arduino Boards Manager - Thanks Max + - moved most stuff to PROGMEM + - added signal quality and a nice little padlock to show which networks are encrypted + +##### v0.4 - user contributed changes - Thank you + - added ability to password protect the configuration Access Point + - callback for enter configuration mode + - memory allocation improvements + +##### v0.3 + - removed the need for EEPROM and works with the 2.0.0 and above stable release of the ESP8266 for Arduino IDE package + - removed restart on save of credentials + - updated examples + +##### v0.2 +needs the latest staging version (or at least a recent release of the staging version) to work + +##### v0.1 +works with the staging release ver. 1.6.5-1044-g170995a, built on Aug 10, 2015 of the ESP8266 Arduino library. + + + ### Contributions and thanks -The support and help I got from the community has been nothing short of fenomenal. I can't thank you guys enough. This is my first real attept in developing open source stuff and I must say, now I understand why people are so dedicated to it, it is because of all the wonderful people involved. +The support and help I got from the community has been nothing short of phenomenal. I can't thank you guys enough. This is my first real attept in developing open source stuff and I must say, now I understand why people are so dedicated to it, it is because of all the wonderful people involved. __THANK YOU__ From c1d8249b10aaff1c2546a0e1f345f14e361ed91b Mon Sep 17 00:00:00 2001 From: Rafael de Pelegrini Soares Date: Tue, 5 Jan 2016 23:28:56 -0200 Subject: [PATCH 17/61] Added support for additional parameters --- .../AutoConnectParametersWithTimeout.ino | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino diff --git a/examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino b/examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino new file mode 100644 index 0000000..fc02fd8 --- /dev/null +++ b/examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino @@ -0,0 +1,62 @@ +#include //https://github.com/esp8266/Arduino + +//needed for library +#include +#include +#include //https://github.com/tzapu/WiFiManager + + +// The extra parameters to be configured (can be either global or just in the setup) +WiFiManagerParameter mqtt_server("server", "mqtt server", NULL, 40); +WiFiManagerParameter mqtt_port("port", "mqtt port", "8080", 8); + +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; + + //add all your parameters here + wifiManager.addParameter(&mqtt_server); + wifiManager.addParameter(&mqtt_port); + + //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(180); + + //fetches ssid and pass and tries to connect + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + if(!wifiManager.autoConnect("AutoConnectAP")) { + Serial.println("failed to connect and hit timeout"); + 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 :)"); + + // use your parameter values as needed + Serial.print(mqtt_server.getPlaceholder()); + Serial.print(": "); + Serial.println(mqtt_server.getValue()); + + Serial.print(mqtt_port.getPlaceholder()); + Serial.print(": "); + Serial.println(mqtt_port.getValue()); +} + +void loop() { + // put your main code here, to run repeatedly: + + +} From f29d63018cb3818493756dd91c042cf7c3d6a155 Mon Sep 17 00:00:00 2001 From: Rafael de Pelegrini Soares Date: Tue, 5 Jan 2016 23:31:10 -0200 Subject: [PATCH 18/61] Added support for additional parameters --- WiFiManager.cpp | 124 +++++++++++++++++++++++++++++++++++++++++++++++- WiFiManager.h | 33 ++++++++++++- 2 files changed, 154 insertions(+), 3 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index fc79a72..fa970c5 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -13,7 +13,95 @@ #include "WiFiManager.h" +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length){ + _id = id; + _placeholder = placeholder; + _length = length; + _value = new char[length]; + for(int i=0; igetValueLength(); + } + DEBUG_PRINT(F("EEPROM initialized with length ")); + DEBUG_PRINT(_eepromLength); + + EEPROM.begin(_eepromLength); + } + + int pos = 0; + for(int i=0; igetValueLength(); + for(int j=0; j_value[j] = EEPROM.read(pos++); + _params[i]->_value[l-1] = 0; + DEBUG_PRINT(F("Parameter loaded")); + DEBUG_PRINT(_params[i]->getID()); + DEBUG_PRINT(_params[i]->getValue()); + } +} + +void WiFiManager::saveParameters(){ + if(_eepromLength==0){ + // if not initialized + for(int i=0; igetValueLength(); + } + DEBUG_PRINT(F("EEPROM initialized with length ")); + DEBUG_PRINT(_eepromLength); + + EEPROM.begin(_eepromLength); + } + int pos = 0; + for(int i=0; igetValueLength(); + for(int j=0; j_value[j]); + } + EEPROM.commit(); } void WiFiManager::begin() { @@ -258,6 +346,9 @@ void WiFiManager::resetSettings() { DEBUG_PRINT(F("THIS MAY CAUSE AP NOT TO STRT UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA.")); WiFi.disconnect(true); //delay(200); + + //overwrite the current parameter values (with defaults) + saveParameters(); } void WiFiManager::setTimeout(unsigned long seconds) { @@ -353,7 +444,26 @@ void WiFiManager::handleWifi(bool scan) { } } - server->sendContent_P(HTTP_FORM); + server->sendContent_P(HTTP_FORM_START); + char parLength[2]; + // add the extra parameters to the form + for(int i=0; igetID()); + pitem.replace("{n}", _params[i]->getID()); + pitem.replace("{p}", _params[i]->getPlaceholder()); + snprintf(parLength, 2, "%d", _params[i]->getValueLength()); + pitem.replace("{l}", parLength); + pitem.replace("{v}", _params[i]->getValue()); + + server->sendContent(pitem); + } + if(_params[0]!=NULL) + server->sendContent_P("
"); + + server->sendContent_P(HTTP_FORM_END); server->sendContent_P(HTTP_END); server->client().stop(); @@ -368,6 +478,18 @@ void WiFiManager::handleWifiSave() { _ssid = urldecode(server->arg("s").c_str()); _pass = urldecode(server->arg("p").c_str()); + //parameter + for(int i=0; iarg(_params[i]->getID()).c_str()); + value.toCharArray(_params[i]->_value, _params[i]->_length); + DEBUG_PRINT(F("Parameter")); + DEBUG_PRINT(_params[i]->getID()); + DEBUG_PRINT(value); + } + saveParameters(); + server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server->sendHeader("Pragma", "no-cache"); server->sendHeader("Expires", "-1"); diff --git a/WiFiManager.h b/WiFiManager.h index 27deed9..7192d24 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -14,7 +14,7 @@ #include -//#include +#include //#include #include #include @@ -29,10 +29,32 @@ const char HTTP_HEAD_END[] PROGMEM = "
{v} {r}% {i}
"; const char HTTP_ITEM_PADLOCK[] PROGMEM = ""; -const char HTTP_FORM[] PROGMEM = "



"; +const char HTTP_FORM_START[] PROGMEM = "


"; +const char HTTP_FORM_PARAM[] PROGMEM = "
"; +const char HTTP_FORM_END[] 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 = ""; +#define WIFI_MANAGER_MAX_PARAMS 6 + +class WiFiManagerParameter { +public: + WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length); + + const char* getID(); + const char* getValue(); + const char* getPlaceholder(); + int getValueLength(); +private: + const char* _id; + const char* _placeholder; + char* _value; + int _length; + +friend class WiFiManager; +}; + class WiFiManager { @@ -60,6 +82,10 @@ public: void setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn); void setAPCallback( void (*func)(void) ); + void addParameter(WiFiManagerParameter *p); + + void loadParameters(); + void saveParameters(); private: std::unique_ptr dnsServer; std::unique_ptr server; @@ -123,6 +149,9 @@ private: void (*_apcallback)(void) = NULL; + WiFiManagerParameter* _params[WIFI_MANAGER_MAX_PARAMS]; + int _eepromLength; + template void DEBUG_PRINT(Generic text); }; From 2bd9e7dd99dea7f6e1ff824a39dbf5b063f0342a Mon Sep 17 00:00:00 2001 From: Rafael de Pelegrini Soares Date: Tue, 5 Jan 2016 23:38:12 -0200 Subject: [PATCH 19/61] missing load parameters --- .../AutoConnectParametersWithTimeout.ino | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino b/examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino index fc02fd8..e933bdf 100644 --- a/examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino +++ b/examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino @@ -25,6 +25,9 @@ void setup() { //reset settings - for testing wifiManager.resetSettings(); + //load previously saved parameters + wifiManager.loadParameters(); + //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds From e0548dc4b4a08fbe71dcd13c316bf5c4bdcc2443 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Thu, 7 Jan 2016 17:52:29 +0200 Subject: [PATCH 20/61] modified custom parameters feature so user can provide their own storage mechanism added FS json storage of parameters example --- WiFiManager.cpp | 242 ++++++++++-------- WiFiManager.h | 12 +- .../AutoConnectParametersWithTimeout.ino | 65 ----- .../AutoConnectWithFSParameters.ino | 128 +++++++++ 4 files changed, 266 insertions(+), 181 deletions(-) delete mode 100644 examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino create mode 100644 examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino diff --git a/WiFiManager.cpp b/WiFiManager.cpp index fa970c5..861c3c6 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1,58 +1,69 @@ /************************************************************** - * WiFiManager is a library for the ESP8266/Arduino platform - * (https://github.com/esp8266/Arduino) to enable easy - * configuration and reconfiguration of WiFi credentials and - * store them in EEPROM. - * 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/esp8266/hardware/esp8266com/esp8266/libraries/DNSServer/examples/CaptivePortalAdvanced - * Built by AlexT https://github.com/tzapu - * Licensed under MIT license + WiFiManager is a library for the ESP8266/Arduino platform + (https://github.com/esp8266/Arduino) to enable easy + configuration and reconfiguration of WiFi credentials and + store them in EEPROM. + 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/esp8266/hardware/esp8266com/esp8266/libraries/DNSServer/examples/CaptivePortalAdvanced + Built by AlexT https://github.com/tzapu + Licensed under MIT license **************************************************************/ #include "WiFiManager.h" -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length){ - _id = id; - _placeholder = placeholder; - _length = length; - _value = new char[length]; - for(int i=0; igetID()); + //} + } -void WiFiManager::loadParameters(){ +/* + void WiFiManager::loadParameters() { + DEBUG_PRINT("Load parameters - not needed"); if(_eepromLength==0){ // if not initialized for(int i=0; igetID()); DEBUG_PRINT(_params[i]->getValue()); } -} + } +*/ +void WiFiManager::saveParameters() { + DEBUG_PRINT("save params callback"); + /* + if(_eepromLength==0){ + // if not initialized + for(int i=0; igetValueLength(); + } + DEBUG_PRINT(F("EEPROM initialized with length ")); + DEBUG_PRINT(_eepromLength); -void WiFiManager::saveParameters(){ - if(_eepromLength==0){ - // if not initialized - for(int i=0; igetValueLength(); - } - DEBUG_PRINT(F("EEPROM initialized with length ")); - DEBUG_PRINT(_eepromLength); - - EEPROM.begin(_eepromLength); - } - int pos = 0; - for(int i=0; igetValueLength(); - for(int j=0; j_value[j]); - } - EEPROM.commit(); + EEPROM.begin(_eepromLength); + } + int pos = 0; + for(int i=0; igetValueLength(); + for(int j=0; j_value[j]); + } + EEPROM.commit(); + */ } void WiFiManager::begin() { @@ -109,13 +123,13 @@ void WiFiManager::begin() { } void WiFiManager::begin(char const *apName) { - begin(apName,NULL); + begin(apName, NULL); } void WiFiManager::begin(char const *apName, char const *apPasswd) { dnsServer.reset(new DNSServer()); server.reset(new ESP8266WebServer(80)); - + DEBUG_PRINT(F("")); _apName = apName; _apPasswd = apPasswd; @@ -124,9 +138,9 @@ void WiFiManager::begin(char const *apName, char const *apPasswd) { DEBUG_PRINT(F("Configuring access point... ")); DEBUG_PRINT(_apName); if (_apPasswd != NULL) { - if(strlen(_apPasswd) < 8 || strlen(_apPasswd) > 63) { - // fail passphrase to short or long! - DEBUG_PRINT(F("Invalid AccessPoint password")); + if (strlen(_apPasswd) < 8 || strlen(_apPasswd) > 63) { + // fail passphrase to short or long! + DEBUG_PRINT(F("Invalid AccessPoint password")); } DEBUG_PRINT(_apPasswd); } @@ -147,7 +161,7 @@ void WiFiManager::begin(char const *apName, char const *apPasswd) { DEBUG_PRINT(F("AP IP address: ")); DEBUG_PRINT(WiFi.softAPIP()); - /* Setup the DNS server redirecting all the domains to the apIP */ + /* Setup the DNS server redirecting all the domains to the apIP */ dnsServer->setErrorReplyCode(DNSReplyCode::NoError); dnsServer->start(DNS_PORT, "*", WiFi.softAPIP()); @@ -165,24 +179,24 @@ void WiFiManager::begin(char const *apName, char const *apPasswd) { boolean WiFiManager::autoConnect() { String ssid = "ESP" + String(ESP.getChipId()); - return autoConnect(ssid.c_str(),NULL); + return autoConnect(ssid.c_str(), NULL); } boolean WiFiManager::autoConnect(char const *apName) { - return autoConnect(apName,NULL); + return autoConnect(apName, NULL); } boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { DEBUG_PRINT(F("")); DEBUG_PRINT(F("AutoConnect")); - + // read eeprom for ssid and pass String ssid = getSSID(); String pass = getPassword(); //use SDK functions to get SSID and pass //String ssid = WiFi.SSID(); //String pass = WiFi.psk(); - + WiFi.mode(WIFI_STA); connectWifi(ssid, pass); int s = WiFi.status(); @@ -192,26 +206,26 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { //connected return true; } - + //not connected //setup AP WiFi.mode(WIFI_AP); //notify we entered AP mode - if( _apcallback != NULL) { + if ( _apcallback != NULL) { _apcallback(); } connect = false; - begin(apName,apPasswd); + begin(apName, apPasswd); bool looping = true; - while(timeout == 0 || millis() < start + timeout) { + while (timeout == 0 || millis() < start + timeout) { //DNS dnsServer->processNextRequest(); //HTTP server->handleClient(); - - if(connect) { + + if (connect) { delay(2000); DEBUG_PRINT(F("Connecting to new AP")); connect = false; @@ -226,13 +240,13 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { //delay(1000); //return false; } else { - //connected + //connected WiFi.mode(WIFI_STA); break; } - + } - yield(); + yield(); } server.reset(); @@ -272,7 +286,7 @@ String WiFiManager::getPassword() { } /* -String WiFiManager::getEEPROMString(int start, int len) { + String WiFiManager::getEEPROMString(int start, int len) { EEPROM.begin(512); delay(10); String string = ""; @@ -282,10 +296,10 @@ String WiFiManager::getEEPROMString(int start, int len) { } EEPROM.end(); return string; -} + } */ /* -void WiFiManager::setEEPROMString(int start, int len, String string) { + void WiFiManager::setEEPROMString(int start, int len, String string) { EEPROM.begin(512); delay(10); int si = 0; @@ -303,7 +317,7 @@ void WiFiManager::setEEPROMString(int start, int len, String string) { } EEPROM.end(); DEBUG_PRINT(F("Wrote " + string); -}*/ + }*/ String WiFiManager::urldecode(const char *src) { @@ -348,7 +362,7 @@ void WiFiManager::resetSettings() { //delay(200); //overwrite the current parameter values (with defaults) - saveParameters(); + //saveParameters(); } void WiFiManager::setTimeout(unsigned long seconds) { @@ -392,7 +406,7 @@ void WiFiManager::handleRoot() { server->sendContent(title); server->sendContent(F("

WiFiManager

")); - + server->sendContent_P(HTTP_PORTAL_OPTIONS); server->sendContent_P(HTTP_END); @@ -431,7 +445,7 @@ void WiFiManager::handleWifi(bool scan) { rssiQ += getRSSIasQuality(WiFi.RSSI(i)); item.replace("{v}", WiFi.SSID(i)); item.replace("{r}", rssiQ); - if(WiFi.encryptionType(i) != ENC_TYPE_NONE) { + if (WiFi.encryptionType(i) != ENC_TYPE_NONE) { item.replace("{i}", FPSTR(HTTP_ITEM_PADLOCK)); } else { item.replace("{i}", ""); @@ -443,13 +457,15 @@ void WiFiManager::handleWifi(bool scan) { server->sendContent("
"); } } - + server->sendContent_P(HTTP_FORM_START); char parLength[2]; // add the extra parameters to the form - for(int i=0; igetID()); pitem.replace("{n}", _params[i]->getID()); @@ -460,14 +476,15 @@ void WiFiManager::handleWifi(bool scan) { server->sendContent(pitem); } - if(_params[0]!=NULL) + if (_params[0] != NULL) { server->sendContent_P("
"); + } server->sendContent_P(HTTP_FORM_END); server->sendContent_P(HTTP_END); server->client().stop(); - - DEBUG_PRINT(F("Sent config page")); + + DEBUG_PRINT(F("Sent config page")); } /** Handle the WLAN save form and redirect to WLAN config page again */ @@ -478,15 +495,18 @@ void WiFiManager::handleWifiSave() { _ssid = urldecode(server->arg("s").c_str()); _pass = urldecode(server->arg("p").c_str()); - //parameter - for(int i=0; iarg(_params[i]->getID()).c_str()); + //store it in array value.toCharArray(_params[i]->_value, _params[i]->_length); - DEBUG_PRINT(F("Parameter")); - DEBUG_PRINT(_params[i]->getID()); - DEBUG_PRINT(value); + DEBUG_PRINT(F("Parameter")); + DEBUG_PRINT(_params[i]->getID()); + DEBUG_PRINT(value); } saveParameters(); @@ -501,19 +521,19 @@ void WiFiManager::handleWifiSave() { server->sendContent_P(HTTP_SCRIPT); server->sendContent_P(HTTP_STYLE); server->sendContent_P(HTTP_HEAD_END); - + server->sendContent_P(HTTP_SAVED); server->sendContent_P(HTTP_END); server->client().stop(); - - DEBUG_PRINT(F("Sent wifi save page")); - + + DEBUG_PRINT(F("Sent wifi save page")); + connect = true; //signal ready to connect/reset } void WiFiManager::handle204() { - DEBUG_PRINT(F("204 No Response")); + DEBUG_PRINT(F("204 No Response")); server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server->sendHeader("Pragma", "no-cache"); server->sendHeader("Expires", "-1"); @@ -563,9 +583,9 @@ void WiFiManager::setAPCallback( void (*func)(void) ) { template void WiFiManager::DEBUG_PRINT(Generic text) { - if(_debug) { + if (_debug) { Serial.print("*WM: "); - Serial.println(text); + Serial.println(text); } } @@ -573,12 +593,12 @@ void WiFiManager::DEBUG_PRINT(Generic text) { int WiFiManager::getRSSIasQuality(int RSSI) { int quality = 0; - if(RSSI <= -100){ - quality = 0; - }else if(RSSI >= -50){ - quality = 100; + if (RSSI <= -100) { + quality = 0; + } else if (RSSI >= -50) { + quality = 100; } else { - quality = 2 * (RSSI + 100); + quality = 2 * (RSSI + 100); } return quality; } diff --git a/WiFiManager.h b/WiFiManager.h index 7192d24..9515356 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -36,7 +36,7 @@ const char HTTP_FORM_END[] PROGMEM = "
Credentials Saved
Trying to connect ESP to network.
If it fails reconnect to AP to try again"; const char HTTP_END[] PROGMEM = ""; -#define WIFI_MANAGER_MAX_PARAMS 6 +#define WIFI_MANAGER_MAX_PARAMS 10 class WiFiManagerParameter { public: @@ -81,10 +81,11 @@ public: //sets a custom ip /gateway /subnet configuration void setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn); void setAPCallback( void (*func)(void) ); - - void addParameter(WiFiManagerParameter *p); - void loadParameters(); + //adds a custom parameter + void addParameter(WiFiManagerParameter *p); + + //void loadParameters(); void saveParameters(); private: std::unique_ptr dnsServer; @@ -121,6 +122,7 @@ private: IPAddress _ip; IPAddress _gw; IPAddress _sn; + int _paramsCount = 0; String getEEPROMString(int start, int len); void setEEPROMString(int start, int len, String string); @@ -150,7 +152,7 @@ private: void (*_apcallback)(void) = NULL; WiFiManagerParameter* _params[WIFI_MANAGER_MAX_PARAMS]; - int _eepromLength; + //int _eepromLength; template void DEBUG_PRINT(Generic text); diff --git a/examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino b/examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino deleted file mode 100644 index e933bdf..0000000 --- a/examples/AutoConnectParametersWithTimeout/AutoConnectParametersWithTimeout.ino +++ /dev/null @@ -1,65 +0,0 @@ -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager - - -// The extra parameters to be configured (can be either global or just in the setup) -WiFiManagerParameter mqtt_server("server", "mqtt server", NULL, 40); -WiFiManagerParameter mqtt_port("port", "mqtt port", "8080", 8); - -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; - - //add all your parameters here - wifiManager.addParameter(&mqtt_server); - wifiManager.addParameter(&mqtt_port); - - //reset settings - for testing - wifiManager.resetSettings(); - - //load previously saved parameters - wifiManager.loadParameters(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - wifiManager.setTimeout(180); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - if(!wifiManager.autoConnect("AutoConnectAP")) { - Serial.println("failed to connect and hit timeout"); - 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 :)"); - - // use your parameter values as needed - Serial.print(mqtt_server.getPlaceholder()); - Serial.print(": "); - Serial.println(mqtt_server.getValue()); - - Serial.print(mqtt_port.getPlaceholder()); - Serial.print(": "); - Serial.println(mqtt_port.getValue()); -} - -void loop() { - // put your main code here, to run repeatedly: - - -} diff --git a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino new file mode 100644 index 0000000..e736fcb --- /dev/null +++ b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -0,0 +1,128 @@ +#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 //https://github.com/bblanchon/ArduinoJson + +//define your default values here, if there are different values in config.json, they are overwritten. +const char *mqtt_server = NULL; +const char *mqtt_port = "8080"; +const char *blynk_token = "YOUR_BLYNK_TOKEN"; + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + + //read configuration from FS json + //SPIFFS.format(); + + Serial.println("Mounting FS..."); + + if (!SPIFFS.begin()) { + Serial.println("Failed to mount file system"); + //abort + return; + } + + if (SPIFFS.exists("/config.json")) { + //file exists, reading and loading + Serial.println("Reading config file"); + File configFile = SPIFFS.open("/config.json", "r"); + if (configFile) { + Serial.println("Opened config file"); + size_t size = configFile.size(); + // Allocate a buffer to store contents of the file. + std::unique_ptr buf(new char[size]); + + configFile.readBytes(buf.get(), size); + StaticJsonBuffer<200> jsonBuffer; + JsonObject& json = jsonBuffer.parseObject(buf.get()); + json.printTo(Serial); + if (json.success()) { + Serial.println("\nParsed json"); + + mqtt_server = json["mqtt_server"]; + mqtt_port = json["mqtt_port"]; + blynk_token = json["blynk_token"]; + } else { + Serial.println("Failed to load json config"); + } + } + } + //end read + + // 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, 8); + WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_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 + wifiManager.addParameter(&custom_mqtt_server); + wifiManager.addParameter(&custom_mqtt_port); + wifiManager.addParameter(&custom_blynk_token); + + //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); + + //fetches ssid and pass and tries to connect + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + if (!wifiManager.autoConnect("AutoConnectAP")) { + Serial.println("failed to connect and hit timeout"); + 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 :)"); + + //read updated parameters + mqtt_server = custom_mqtt_server.getValue(); + mqtt_port = custom_mqtt_port.getValue(); + blynk_token = custom_blynk_token.getValue(); + + //save the custom parameters to FS + StaticJsonBuffer<200> jsonBuffer; + JsonObject& json = jsonBuffer.createObject(); + json["mqtt_server"] = mqtt_server; + json["mqtt_port"] = mqtt_port; + json["blynk_token"] = blynk_token; + + File configFile = SPIFFS.open("/config.json", "w"); + if (!configFile) { + Serial.println("Failed to open config file for writing"); + return; + } + + json.printTo(Serial); + json.printTo(configFile); + configFile.close(); + //end save +} + +void loop() { + // put your main code here, to run repeatedly: + + +} From 5dfb2e9ad6fa62ebd59002b1df3064b33d8ca88c Mon Sep 17 00:00:00 2001 From: SebiPanther Date: Thu, 7 Jan 2016 22:18:28 +0100 Subject: [PATCH 21/61] Fixed incompatibilities with DHT Library from https://github.com/adafruit/DHT-sensor-library --- WiFiManager.cpp | 84 ++++++++++++++++++++++++------------------------- WiFiManager.h | 2 +- 2 files changed, 43 insertions(+), 43 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index fc79a72..fb6ce82 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -28,24 +28,24 @@ void WiFiManager::begin(char const *apName, char const *apPasswd) { dnsServer.reset(new DNSServer()); server.reset(new ESP8266WebServer(80)); - DEBUG_PRINT(F("")); + WIFIMGR_DEBUG_PRINT(F("")); _apName = apName; _apPasswd = apPasswd; start = millis(); - DEBUG_PRINT(F("Configuring access point... ")); - DEBUG_PRINT(_apName); + WIFIMGR_DEBUG_PRINT(F("Configuring access point... ")); + WIFIMGR_DEBUG_PRINT(_apName); if (_apPasswd != NULL) { if(strlen(_apPasswd) < 8 || strlen(_apPasswd) > 63) { // fail passphrase to short or long! - DEBUG_PRINT(F("Invalid AccessPoint password")); + WIFIMGR_DEBUG_PRINT(F("Invalid AccessPoint password")); } - DEBUG_PRINT(_apPasswd); + WIFIMGR_DEBUG_PRINT(_apPasswd); } //optional soft ip config if (_ip) { - DEBUG_PRINT(F("Custom IP/GW/Subnet")); + WIFIMGR_DEBUG_PRINT(F("Custom IP/GW/Subnet")); WiFi.softAPConfig(_ip, _gw, _sn); } @@ -56,8 +56,8 @@ void WiFiManager::begin(char const *apName, char const *apPasswd) { } delay(500); // Without delay I've seen the IP address blank - DEBUG_PRINT(F("AP IP address: ")); - DEBUG_PRINT(WiFi.softAPIP()); + WIFIMGR_DEBUG_PRINT(F("AP IP address: ")); + WIFIMGR_DEBUG_PRINT(WiFi.softAPIP()); /* Setup the DNS server redirecting all the domains to the apIP */ dnsServer->setErrorReplyCode(DNSReplyCode::NoError); @@ -72,7 +72,7 @@ void WiFiManager::begin(char const *apName, char const *apPasswd) { server->on("/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_PRINT(F("HTTP server started")); + WIFIMGR_DEBUG_PRINT(F("HTTP server started")); } boolean WiFiManager::autoConnect() { @@ -85,8 +85,8 @@ boolean WiFiManager::autoConnect(char const *apName) { } boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { - DEBUG_PRINT(F("")); - DEBUG_PRINT(F("AutoConnect")); + WIFIMGR_DEBUG_PRINT(F("")); + WIFIMGR_DEBUG_PRINT(F("AutoConnect")); // read eeprom for ssid and pass String ssid = getSSID(); @@ -99,8 +99,8 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { connectWifi(ssid, pass); int s = WiFi.status(); if (s == WL_CONNECTED) { - DEBUG_PRINT(F("IP Address:")); - DEBUG_PRINT(WiFi.localIP()); + WIFIMGR_DEBUG_PRINT(F("IP Address:")); + WIFIMGR_DEBUG_PRINT(WiFi.localIP()); //connected return true; } @@ -125,14 +125,14 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { if(connect) { delay(2000); - DEBUG_PRINT(F("Connecting to new AP")); + WIFIMGR_DEBUG_PRINT(F("Connecting to new AP")); connect = false; //ssid = getSSID(); //pass = getPassword(); connectWifi(_ssid, _pass); int s = WiFi.status(); if (s != WL_CONNECTED) { - DEBUG_PRINT(F("Failed to connect.")); + WIFIMGR_DEBUG_PRINT(F("Failed to connect.")); //not connected, should retry everything //ESP.reset(); //delay(1000); @@ -154,31 +154,31 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { void WiFiManager::connectWifi(String ssid, String pass) { - DEBUG_PRINT(F("Connecting as wifi client...")); + WIFIMGR_DEBUG_PRINT(F("Connecting as wifi client...")); //WiFi.disconnect(); WiFi.begin(ssid.c_str(), pass.c_str()); int connRes = WiFi.waitForConnectResult(); - DEBUG_PRINT ("Connection result: "); - DEBUG_PRINT ( connRes ); + WIFIMGR_DEBUG_PRINT("Connection result: "); + WIFIMGR_DEBUG_PRINT( connRes ); } String WiFiManager::getSSID() { if (_ssid == "") { - DEBUG_PRINT(F("Reading SSID")); + WIFIMGR_DEBUG_PRINT(F("Reading SSID")); _ssid = WiFi.SSID();//getEEPROMString(0, 32); - DEBUG_PRINT(F("SSID: ")); - DEBUG_PRINT(_ssid); + WIFIMGR_DEBUG_PRINT(F("SSID: ")); + WIFIMGR_DEBUG_PRINT(_ssid); } return _ssid; } String WiFiManager::getPassword() { if (_pass == "") { - DEBUG_PRINT(F("Reading Password")); + WIFIMGR_DEBUG_PRINT(F("Reading Password")); _pass = WiFi.psk();//getEEPROMString(32, 64); - DEBUG_PRINT("Password: " + _pass); - //DEBUG_PRINT(_pass); + WIFIMGR_DEBUG_PRINT("Password: " + _pass); + //WIFIMGR_DEBUG_PRINT(_pass); } return _pass; } @@ -189,7 +189,7 @@ String WiFiManager::getEEPROMString(int start, int len) { delay(10); String string = ""; for (int i = _eepromStart + start; i < _eepromStart + start + len; i++) { - //DEBUG_PRINT(i); + //WIFIMGR_DEBUG_PRINT(i); string += char(EEPROM.read(i)); } EEPROM.end(); @@ -205,8 +205,8 @@ void WiFiManager::setEEPROMString(int start, int len, String string) { char c; if (si < string.length()) { c = string[si]; - //DEBUG_PRINT(F("Wrote: "); - //DEBUG_PRINT(c); + //WIFIMGR_DEBUG_PRINT(F("Wrote: "); + //WIFIMGR_DEBUG_PRINT(c); } else { c = 0; } @@ -214,7 +214,7 @@ void WiFiManager::setEEPROMString(int start, int len, String string) { si++; } EEPROM.end(); - DEBUG_PRINT(F("Wrote " + string); + WIFIMGR_DEBUG_PRINT(F("Wrote " + string); }*/ String WiFiManager::urldecode(const char *src) @@ -254,8 +254,8 @@ String WiFiManager::urldecode(const char *src) } void WiFiManager::resetSettings() { - DEBUG_PRINT(F("settings invalidated")); - DEBUG_PRINT(F("THIS MAY CAUSE AP NOT TO STRT UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA.")); + WIFIMGR_DEBUG_PRINT(F("settings invalidated")); + WIFIMGR_DEBUG_PRINT(F("THIS MAY CAUSE AP NOT TO STRT UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA.")); WiFi.disconnect(true); //delay(200); } @@ -277,7 +277,7 @@ void WiFiManager::setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { /** Handle root or redirect to captive portal */ void WiFiManager::handleRoot() { - DEBUG_PRINT(F("Handle root")); + WIFIMGR_DEBUG_PRINT(F("Handle root")); if (captivePortal()) { // If caprive portal redirect instead of displaying the page. return; } @@ -325,16 +325,16 @@ void WiFiManager::handleWifi(bool scan) { if (scan) { int n = WiFi.scanNetworks(); - DEBUG_PRINT(F("Scan done")); + WIFIMGR_DEBUG_PRINT(F("Scan done")); if (n == 0) { - DEBUG_PRINT(F("No networks found")); + WIFIMGR_DEBUG_PRINT(F("No networks found")); server->sendContent("No networks found. Refresh to scan again."); } else { for (int i = 0; i < n; ++i) { - DEBUG_PRINT(WiFi.SSID(i)); - DEBUG_PRINT(WiFi.RSSI(i)); + WIFIMGR_DEBUG_PRINT(WiFi.SSID(i)); + WIFIMGR_DEBUG_PRINT(WiFi.RSSI(i)); String item = FPSTR(HTTP_ITEM); String rssiQ; rssiQ += getRSSIasQuality(WiFi.RSSI(i)); @@ -345,7 +345,7 @@ void WiFiManager::handleWifi(bool scan) { } else { item.replace("{i}", ""); } - //DEBUG_PRINT(item); + //WIFIMGR_DEBUG_PRINT(item); server->sendContent(item); delay(0); } @@ -357,12 +357,12 @@ void WiFiManager::handleWifi(bool scan) { server->sendContent_P(HTTP_END); server->client().stop(); - DEBUG_PRINT(F("Sent config page")); + WIFIMGR_DEBUG_PRINT(F("Sent config page")); } /** Handle the WLAN save form and redirect to WLAN config page again */ void WiFiManager::handleWifiSave() { - DEBUG_PRINT(F("WiFi save")); + WIFIMGR_DEBUG_PRINT(F("WiFi save")); //SAVE/connect here _ssid = urldecode(server->arg("s").c_str()); @@ -385,13 +385,13 @@ void WiFiManager::handleWifiSave() { server->sendContent_P(HTTP_END); server->client().stop(); - DEBUG_PRINT(F("Sent wifi save page")); + WIFIMGR_DEBUG_PRINT(F("Sent wifi save page")); connect = true; //signal ready to connect/reset } void WiFiManager::handle204() { - DEBUG_PRINT(F("204 No Response")); + WIFIMGR_DEBUG_PRINT(F("204 No Response")); server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server->sendHeader("Pragma", "no-cache"); server->sendHeader("Expires", "-1"); @@ -424,7 +424,7 @@ void WiFiManager::handleNotFound() { /** 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_PRINT(F("Request redirected to captive portal")); + WIFIMGR_DEBUG_PRINT(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. server->client().stop(); // Stop is needed because we sent no content length @@ -440,7 +440,7 @@ void WiFiManager::setAPCallback( void (*func)(void) ) { template -void WiFiManager::DEBUG_PRINT(Generic text) { +void WiFiManager::WIFIMGR_DEBUG_PRINT(Generic text) { if(_debug) { Serial.print("*WM: "); Serial.println(text); diff --git a/WiFiManager.h b/WiFiManager.h index 27deed9..9f6a723 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -124,7 +124,7 @@ private: void (*_apcallback)(void) = NULL; template - void DEBUG_PRINT(Generic text); + void WIFIMGR_DEBUG_PRINT(Generic text); }; From ab5902e27342d4718f337e9c2b2b8ac241417680 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Fri, 8 Jan 2016 11:44:50 +0200 Subject: [PATCH 22/61] added html template to repo --- extras/WiFiManager.template.html | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 extras/WiFiManager.template.html diff --git a/extras/WiFiManager.template.html b/extras/WiFiManager.template.html new file mode 100644 index 0000000..4d005b2 --- /dev/null +++ b/extras/WiFiManager.template.html @@ -0,0 +1,17 @@ +{v} + + +
+
{v} {r}% {i}
+
{v} 100%
+
Vila17 95%
+ +
Marcelica 100%
+
PMica 110%
+
+


+
+

+
+
+ \ No newline at end of file From 83177e9c55aec7a9e27d344019cd25bff74b6db4 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Fri, 8 Jan 2016 12:51:10 +0200 Subject: [PATCH 23/61] a bit of cleanup removed write on every connect of parameters, now it only writes parameters to FS if config portal is started and connection is successful --- WiFiManager.cpp | 83 ++------------ WiFiManager.h | 6 +- .../AutoConnectWithFSParameters.ino | 106 ++++++++++-------- 3 files changed, 76 insertions(+), 119 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 861c3c6..a8edd42 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -40,83 +40,15 @@ int WiFiManagerParameter::getValueLength() { } WiFiManager::WiFiManager() { - //for(int i=0; igetID()); - //} - } -/* - void WiFiManager::loadParameters() { - DEBUG_PRINT("Load parameters - not needed"); - if(_eepromLength==0){ - // if not initialized - for(int i=0; igetValueLength(); - } - DEBUG_PRINT(F("EEPROM initialized with length ")); - DEBUG_PRINT(_eepromLength); - - EEPROM.begin(_eepromLength); - } - - int pos = 0; - for(int i=0; igetValueLength(); - for(int j=0; j_value[j] = EEPROM.read(pos++); - _params[i]->_value[l-1] = 0; - DEBUG_PRINT(F("Parameter loaded")); - DEBUG_PRINT(_params[i]->getID()); - DEBUG_PRINT(_params[i]->getValue()); - } - } -*/ -void WiFiManager::saveParameters() { - DEBUG_PRINT("save params callback"); - /* - if(_eepromLength==0){ - // if not initialized - for(int i=0; igetValueLength(); - } - DEBUG_PRINT(F("EEPROM initialized with length ")); - DEBUG_PRINT(_eepromLength); - - EEPROM.begin(_eepromLength); - } - int pos = 0; - for(int i=0; igetValueLength(); - for(int j=0; j_value[j]); - } - EEPROM.commit(); - */ -} void WiFiManager::begin() { begin("NoNetESP"); @@ -242,6 +174,11 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPasswd) { } 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; } @@ -360,9 +297,6 @@ void WiFiManager::resetSettings() { DEBUG_PRINT(F("THIS MAY CAUSE AP NOT TO STRT UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA.")); WiFi.disconnect(true); //delay(200); - - //overwrite the current parameter values (with defaults) - //saveParameters(); } void WiFiManager::setTimeout(unsigned long seconds) { @@ -508,7 +442,6 @@ void WiFiManager::handleWifiSave() { DEBUG_PRINT(_params[i]->getID()); DEBUG_PRINT(value); } - saveParameters(); server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server->sendHeader("Pragma", "no-cache"); @@ -580,6 +513,12 @@ void WiFiManager::setAPCallback( void (*func)(void) ) { _apcallback = func; } +//start up save config callback +void WiFiManager::setSaveConfigCallback( void (*func)(void) ) { + _savecallback = func; +} + + template void WiFiManager::DEBUG_PRINT(Generic text) { diff --git a/WiFiManager.h b/WiFiManager.h index 9515356..b209215 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -80,13 +80,14 @@ public: //sets a custom ip /gateway /subnet configuration void setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + //called when AP mode and config portal is started void setAPCallback( void (*func)(void) ); + //called when settings have been changed and connection was successful + void setSaveConfigCallback( void (*func)(void) ); //adds a custom parameter void addParameter(WiFiManagerParameter *p); - //void loadParameters(); - void saveParameters(); private: std::unique_ptr dnsServer; std::unique_ptr server; @@ -150,6 +151,7 @@ private: boolean _debug = true; void (*_apcallback)(void) = NULL; + void (*_savecallback)(void) = NULL; WiFiManagerParameter* _params[WIFI_MANAGER_MAX_PARAMS]; //int _eepromLength; diff --git a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index e736fcb..5e69973 100644 --- a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -14,49 +14,61 @@ const char *mqtt_server = NULL; const char *mqtt_port = "8080"; const char *blynk_token = "YOUR_BLYNK_TOKEN"; + //flag for saving data + bool shouldSaveConfig = false; + +//callback notifying us of the need to save config +void saveConfigCallback () { + Serial.println("Should save config"); + shouldSaveConfig = true; +} + + void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.println(); - //read configuration from FS json + //clean FS, for testing //SPIFFS.format(); - Serial.println("Mounting FS..."); + //read configuration from FS json + Serial.println("mounting FS..."); - if (!SPIFFS.begin()) { - Serial.println("Failed to mount file system"); - //abort - return; - } + if (SPIFFS.begin()) { + Serial.println("mounted file system"); + if (SPIFFS.exists("/config.json")) { + //file exists, reading and loading + Serial.println("reading config file"); + File configFile = SPIFFS.open("/config.json", "r"); + if (configFile) { + Serial.println("opened config file"); + size_t size = configFile.size(); + // Allocate a buffer to store contents of the file. + std::unique_ptr buf(new char[size]); - if (SPIFFS.exists("/config.json")) { - //file exists, reading and loading - Serial.println("Reading config file"); - File configFile = SPIFFS.open("/config.json", "r"); - if (configFile) { - Serial.println("Opened config file"); - size_t size = configFile.size(); - // Allocate a buffer to store contents of the file. - std::unique_ptr buf(new char[size]); + configFile.readBytes(buf.get(), size); + StaticJsonBuffer<200> jsonBuffer; + JsonObject& json = jsonBuffer.parseObject(buf.get()); + json.printTo(Serial); + if (json.success()) { + Serial.println("\nparsed json"); - configFile.readBytes(buf.get(), size); - StaticJsonBuffer<200> jsonBuffer; - JsonObject& json = jsonBuffer.parseObject(buf.get()); - json.printTo(Serial); - if (json.success()) { - Serial.println("\nParsed json"); - - mqtt_server = json["mqtt_server"]; - mqtt_port = json["mqtt_port"]; - blynk_token = json["blynk_token"]; - } else { - Serial.println("Failed to load json config"); + mqtt_server = json["mqtt_server"]; + mqtt_port = json["mqtt_port"]; + blynk_token = json["blynk_token"]; + } else { + Serial.println("failed to load json config"); + } } } + } else { + Serial.println("failed to mount FS"); } //end read + + // 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 @@ -64,11 +76,13 @@ void setup() { WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 8); WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_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); + //add all your parameters here wifiManager.addParameter(&custom_mqtt_server); wifiManager.addParameter(&custom_mqtt_port); @@ -101,24 +115,26 @@ void setup() { mqtt_server = custom_mqtt_server.getValue(); mqtt_port = custom_mqtt_port.getValue(); blynk_token = custom_blynk_token.getValue(); - + //save the custom parameters to FS - StaticJsonBuffer<200> jsonBuffer; - JsonObject& json = jsonBuffer.createObject(); - json["mqtt_server"] = mqtt_server; - json["mqtt_port"] = mqtt_port; - json["blynk_token"] = blynk_token; + if (shouldSaveConfig) { + Serial.println("saving config"); + StaticJsonBuffer<200> jsonBuffer; + JsonObject& json = jsonBuffer.createObject(); + json["mqtt_server"] = mqtt_server; + json["mqtt_port"] = mqtt_port; + json["blynk_token"] = blynk_token; - File configFile = SPIFFS.open("/config.json", "w"); - if (!configFile) { - Serial.println("Failed to open config file for writing"); - return; + File configFile = SPIFFS.open("/config.json", "w"); + if (!configFile) { + Serial.println("failed to open config file for writing"); + } + + json.printTo(Serial); + json.printTo(configFile); + configFile.close(); + //end save } - - json.printTo(Serial); - json.printTo(configFile); - configFile.close(); - //end save } void loop() { From b05dff34b7a7385d78b9d36ba392703d4191ecb5 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Fri, 8 Jan 2016 21:04:37 +0200 Subject: [PATCH 24/61] added example for on demand config portal cleanup --- WiFiManager.cpp | 21 +++--- WiFiManager.h | 6 +- .../OnDemandConfigPortal.ino | 67 +++++++++++++++++++ 3 files changed, 81 insertions(+), 13 deletions(-) create mode 100644 examples/OnDemandConfigPortal/OnDemandConfigPortal.ino diff --git a/WiFiManager.cpp b/WiFiManager.cpp index f9747dd..dca01eb 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -49,23 +49,24 @@ void WiFiManager::addParameter(WiFiManagerParameter *p) { DEBUG_WM(p->getID()); } -void WiFiManager::setupConfigPortal(char const *apName, char const *apPasswd) { +void WiFiManager::setupConfigPortal(char const *apName, char const *apPassword) { dnsServer.reset(new DNSServer()); server.reset(new ESP8266WebServer(80)); DEBUG_WM(F("")); _apName = apName; - _apPasswd = apPasswd; + _apPassword = apPassword; start = millis(); DEBUG_WM(F("Configuring access point... ")); DEBUG_WM(_apName); - if (_apPasswd != NULL) { - if (strlen(_apPasswd) < 8 || strlen(_apPasswd) > 63) { + if (_apPassword != NULL) { + if (strlen(_apPassword) < 8 || strlen(_apPassword) > 63) { // fail passphrase to short or long! - DEBUG_WM(F("Invalid AccessPoint password")); + DEBUG_WM(F("Invalid AccessPoint password. Ignoring")); + _apPassword = NULL; } - DEBUG_WM(_apPasswd); + DEBUG_WM(_apPassword); } //optional soft ip config @@ -74,8 +75,8 @@ void WiFiManager::setupConfigPortal(char const *apName, char const *apPasswd) { WiFi.softAPConfig(_ip, _gw, _sn); } - if (_apPasswd != NULL) { - WiFi.softAP(_apName, _apPasswd);//password option + if (_apPassword != NULL) { + WiFi.softAP(_apName, _apPassword);//password option } else { WiFi.softAP(_apName); } @@ -136,7 +137,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo connect = false; setupConfigPortal(apName, apPassword); - + DEBUG_WM("start loop"); while (timeout == 0 || millis() < start + timeout) { //DNS dnsServer->processNextRequest(); @@ -168,7 +169,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo server.reset(); dnsServer.reset(); - + DEBUG_WM("end loop"); return WiFi.status() == WL_CONNECTED; } diff --git a/WiFiManager.h b/WiFiManager.h index 42ee500..7460082 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -59,7 +59,7 @@ class WiFiManager WiFiManager(); boolean autoConnect(); - boolean autoConnect(char const *apName, char const *apPasswd = NULL); + 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(char const *apName, char const *apPassword = NULL); @@ -96,11 +96,11 @@ class WiFiManager const String HTTP_HEAD = "{v}"; - void setupConfigPortal(char const *apName, char const *apPasswd); + void setupConfigPortal(char const *apName, char const *apPassword); int _eepromStart; const char* _apName = "no-net"; - const char* _apPasswd = NULL; + const char* _apPassword = NULL; String _ssid = ""; String _pass = ""; unsigned long timeout = 0; diff --git a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino new file mode 100644 index 0000000..06b7677 --- /dev/null +++ b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -0,0 +1,67 @@ +#include //https://github.com/esp8266/Arduino + +//needed for library +#include +#include +#include //https://github.com/tzapu/WiFiManager + + +//callback notifying us of the need to save config +void saveConfigCallback () { + Serial.println("Should save config"); +} + + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println("\n Starting"); + + //read gpio 4 state on startup + pinMode(4, INPUT); + int pinState = digitalRead(4); + + //if gpio 4 is high startup config mode + if (pinState == LOW) { + //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); + + //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 + 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 :)"); + } + + +} + +void loop() { + // put your main code here, to run repeatedly: + + +} From 1db01f08e6c3cd627ea5decab31c687dee10c6e6 Mon Sep 17 00:00:00 2001 From: Franklin van Velthuizen Date: Sat, 9 Jan 2016 01:17:16 +0100 Subject: [PATCH 25/61] Added method getConfigurationSSID(), so the config portal SSID that is created by the ESP8266 can be used in the callback (e.g. for output to a screen) --- WiFiManager.cpp | 14 +++++++++----- WiFiManager.h | 5 ++++- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index dca01eb..95a113d 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -49,13 +49,11 @@ void WiFiManager::addParameter(WiFiManagerParameter *p) { DEBUG_WM(p->getID()); } -void WiFiManager::setupConfigPortal(char const *apName, char const *apPassword) { +void WiFiManager::setupConfigPortal() { dnsServer.reset(new DNSServer()); server.reset(new ESP8266WebServer(80)); DEBUG_WM(F("")); - _apName = apName; - _apPassword = apPassword; start = millis(); DEBUG_WM(F("Configuring access point... ")); @@ -130,13 +128,16 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo //setup AP WiFi.mode(WIFI_AP); + _apName = apName; + _apPassword = apPassword; + //notify we entered AP mode if ( _apcallback != NULL) { _apcallback(); } connect = false; - setupConfigPortal(apName, apPassword); + setupConfigPortal(); DEBUG_WM("start loop"); while (timeout == 0 || millis() < start + timeout) { //DNS @@ -205,6 +206,10 @@ String WiFiManager::getPassword() { return _pass; } +String WiFiManager::getConfigurationSSID() { + return _apName; +} + String WiFiManager::urldecode(const char *src) { String decoded = ""; @@ -477,7 +482,6 @@ void WiFiManager::DEBUG_WM(Generic text) { } } - int WiFiManager::getRSSIasQuality(int RSSI) { int quality = 0; diff --git a/WiFiManager.h b/WiFiManager.h index 7460082..faf3b42 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -67,6 +67,9 @@ class WiFiManager String getSSID(); String getPassword(); + // get the AP name of the config portal, so it can be used in the callback + String getConfigurationSSID(); + void resetSettings(); //for convenience String urldecode(const char*); @@ -96,7 +99,7 @@ class WiFiManager const String HTTP_HEAD = "{v}"; - void setupConfigPortal(char const *apName, char const *apPassword); + void setupConfigPortal(); int _eepromStart; const char* _apName = "no-net"; From 0780115c7bd861cb8565d40ef1d1e254fe934f28 Mon Sep 17 00:00:00 2001 From: Franklin van Velthuizen Date: Sat, 9 Jan 2016 01:24:48 +0100 Subject: [PATCH 26/61] Renamed getConfigurationSSID() to getConfigPortalSSID() --- WiFiManager.cpp | 2 +- WiFiManager.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 95a113d..6243869 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -206,7 +206,7 @@ String WiFiManager::getPassword() { return _pass; } -String WiFiManager::getConfigurationSSID() { +String WiFiManager::getConfigPortalSSID() { return _apName; } diff --git a/WiFiManager.h b/WiFiManager.h index faf3b42..af67424 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -68,7 +68,7 @@ class WiFiManager String getPassword(); // get the AP name of the config portal, so it can be used in the callback - String getConfigurationSSID(); + String getConfigPortalSSID(); void resetSettings(); //for convenience From 90bac5d5803dec56b53dbb396acf0fb94cfac591 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Sat, 9 Jan 2016 18:28:23 +0200 Subject: [PATCH 27/61] on demand example fixed --- WiFiManager.cpp | 4 ++-- examples/OnDemandConfigPortal/OnDemandConfigPortal.ino | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index dca01eb..ae2a525 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -137,7 +137,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo connect = false; setupConfigPortal(apName, apPassword); - DEBUG_WM("start loop"); + while (timeout == 0 || millis() < start + timeout) { //DNS dnsServer->processNextRequest(); @@ -169,7 +169,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo server.reset(); dnsServer.reset(); - DEBUG_WM("end loop"); + return WiFi.status() == WL_CONNECTED; } diff --git a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino index 06b7677..3bf8823 100644 --- a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -22,7 +22,7 @@ void setup() { int pinState = digitalRead(4); //if gpio 4 is high startup config mode - if (pinState == LOW) { + if (pinState == HIGH) { //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around WiFiManager wifiManager; @@ -42,8 +42,8 @@ void setup() { //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration - //WITHOUT THIS THE AP DOES NOT SEEM TO WORK PROPERLY - WiFi.mode(WIFI_STA); + //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"); From 7137082e74a2f697f36b09031df1d97b7b2ce461 Mon Sep 17 00:00:00 2001 From: Alberto Ricci Bitti Date: Sat, 9 Jan 2016 17:50:09 +0100 Subject: [PATCH 28/61] Removed redundant #include --- examples/OnDemandConfigPortal/OnDemandConfigPortal.ino | 2 -- 1 file changed, 2 deletions(-) diff --git a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino index 06b7677..8c32b14 100644 --- a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -1,8 +1,6 @@ #include //https://github.com/esp8266/Arduino //needed for library -#include -#include #include //https://github.com/tzapu/WiFiManager From 687dc20f3ebb1cef69f9b5ed8ebceb13b055dfd8 Mon Sep 17 00:00:00 2001 From: Alberto Ricci Bitti Date: Sat, 9 Jan 2016 18:52:42 +0100 Subject: [PATCH 29/61] Changed to make it work on ESP-01 boards (on ESP-01 pin cannot be checked at setup as its only available pins, gpio0 and gpio2, are shared with the bootloader) - moved triggering of configuration portal into Arduino's loop() function - changed pin from 4 to 0 (and made it #define-able) --- .../OnDemandConfigPortal.ino | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino index 8c32b14..5a801f6 100644 --- a/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ b/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -3,6 +3,10 @@ //needed for library #include //https://github.com/tzapu/WiFiManager +// select wich pin will trigger the configuraton 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 //callback notifying us of the need to save config void saveConfigCallback () { @@ -15,12 +19,13 @@ void setup() { Serial.begin(115200); Serial.println("\n Starting"); - //read gpio 4 state on startup - pinMode(4, INPUT); - int pinState = digitalRead(4); + pinMode(TRIGGER_PIN, INPUT); +} - //if gpio 4 is high startup config mode - if (pinState == LOW) { + +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; @@ -56,10 +61,6 @@ void setup() { } -} - -void loop() { // put your main code here, to run repeatedly: - } From 5587532f01a8fe1ea2ee699a0e77a7d2c7198233 Mon Sep 17 00:00:00 2001 From: Alberto Ricci Bitti Date: Sat, 9 Jan 2016 20:11:04 +0100 Subject: [PATCH 30/61] Manually reverted to current tzapu/master after messing with git commits --- WiFiManager.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index ae2a525..6243869 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -49,13 +49,11 @@ void WiFiManager::addParameter(WiFiManagerParameter *p) { DEBUG_WM(p->getID()); } -void WiFiManager::setupConfigPortal(char const *apName, char const *apPassword) { +void WiFiManager::setupConfigPortal() { dnsServer.reset(new DNSServer()); server.reset(new ESP8266WebServer(80)); DEBUG_WM(F("")); - _apName = apName; - _apPassword = apPassword; start = millis(); DEBUG_WM(F("Configuring access point... ")); @@ -130,14 +128,17 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo //setup AP WiFi.mode(WIFI_AP); + _apName = apName; + _apPassword = apPassword; + //notify we entered AP mode if ( _apcallback != NULL) { _apcallback(); } connect = false; - setupConfigPortal(apName, apPassword); - + setupConfigPortal(); + DEBUG_WM("start loop"); while (timeout == 0 || millis() < start + timeout) { //DNS dnsServer->processNextRequest(); @@ -169,7 +170,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo server.reset(); dnsServer.reset(); - + DEBUG_WM("end loop"); return WiFi.status() == WL_CONNECTED; } @@ -205,6 +206,10 @@ String WiFiManager::getPassword() { return _pass; } +String WiFiManager::getConfigPortalSSID() { + return _apName; +} + String WiFiManager::urldecode(const char *src) { String decoded = ""; @@ -477,7 +482,6 @@ void WiFiManager::DEBUG_WM(Generic text) { } } - int WiFiManager::getRSSIasQuality(int RSSI) { int quality = 0; From 93a7d280f104d8296c9ab0c682b1aee4b65e77af Mon Sep 17 00:00:00 2001 From: joe-average Date: Sat, 9 Jan 2016 23:17:58 +0100 Subject: [PATCH 31/61] Do not show clear text password in form input field --- WiFiManager.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WiFiManager.h b/WiFiManager.h index af67424..7b84cc6 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -26,7 +26,7 @@ const char HTTP_HEAD_END[] PROGMEM = "
{v} {r}% {i}
"; const char HTTP_ITEM_PADLOCK[] PROGMEM = ""; -const char HTTP_FORM_START[] PROGMEM = "


"; +const char HTTP_FORM_START[] PROGMEM = "

"; const char HTTP_FORM_PARAM[] PROGMEM = "
"; const char HTTP_FORM_END[] PROGMEM = "
"; From c77e9cbcc9e2ac35889efe339fc1caba11e286b2 Mon Sep 17 00:00:00 2001 From: Franklin van Velthuizen Date: Sun, 10 Jan 2016 00:28:39 +0100 Subject: [PATCH 32/61] To show the config portal SSID in the callback, a global reference to the WiFiManager object was needed. To solve this, a pointer to the WiFiManager object is now passed to the callback. The feedback example is edited accordingly. --- WiFiManager.cpp | 4 ++-- WiFiManager.h | 4 ++-- .../AutoConnectWithFeedback.ino | 10 +++------- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 6243869..6e4b027 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -133,7 +133,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo //notify we entered AP mode if ( _apcallback != NULL) { - _apcallback(); + _apcallback(this); } connect = false; @@ -463,7 +463,7 @@ boolean WiFiManager::captivePortal() { } //start up config portal callback -void WiFiManager::setAPCallback( void (*func)(void) ) { +void WiFiManager::setAPCallback( void (*func)(WiFiManager* myWiFiManager) ) { _apcallback = func; } diff --git a/WiFiManager.h b/WiFiManager.h index af67424..7505d87 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -83,7 +83,7 @@ class WiFiManager //sets a custom ip /gateway /subnet configuration void setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn); //called when AP mode and config portal is started - void setAPCallback( void (*func)(void) ); + void setAPCallback( void (*func)(WiFiManager*) ); //called when settings have been changed and connection was successful void setSaveConfigCallback( void (*func)(void) ); @@ -138,7 +138,7 @@ class WiFiManager boolean connect; boolean _debug = true; - void (*_apcallback)(void) = NULL; + void (*_apcallback)(WiFiManager*) = NULL; void (*_savecallback)(void) = NULL; WiFiManagerParameter* _params[WIFI_MANAGER_MAX_PARAMS]; diff --git a/examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino b/examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino index e2b0751..9491760 100644 --- a/examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino +++ b/examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino @@ -5,15 +5,11 @@ #include #include "WiFiManager.h" //https://github.com/tzapu/WiFiManager -//WiFiManger -//global intialization: this wastes memory, only used here to have access to wifiManager.getConfigPortalSSID() -WiFiManager wifiManager; - -void configModeCallback () { +void configModeCallback (WiFiManager *myWiFiManager) { Serial.println("Entered config mode"); Serial.println(WiFi.softAPIP()); //if you used auto generated SSID, print it - Serial.println(wifiManager.getConfigPortalSSID()); + Serial.println(myWiFiManager->getConfigPortalSSID()); } void setup() { @@ -22,7 +18,7 @@ void setup() { //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around - //WiFiManager wifiManager; + WiFiManager wifiManager; //reset settings - for testing //wifiManager.resetSettings(); From 1351245d09e6e6e73c04d6309b988228a073a736 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 11 Jan 2016 13:06:12 +0200 Subject: [PATCH 33/61] added signal quality filter --- WiFiManager.cpp | 40 ++++++++++++------- WiFiManager.h | 15 ++++--- .../AutoConnectWithFSParameters.ino | 16 +++++--- 3 files changed, 44 insertions(+), 27 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 6e4b027..c7f91ad 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -1,8 +1,7 @@ /************************************************************** WiFiManager is a library for the ESP8266/Arduino platform (https://github.com/esp8266/Arduino) to enable easy - configuration and reconfiguration of WiFi credentials and - store them in EEPROM. + 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 @@ -127,7 +126,7 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { //setup AP WiFi.mode(WIFI_AP); - + _apName = apName; _apPassword = apPassword; @@ -135,7 +134,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo if ( _apcallback != NULL) { _apcallback(this); } - + connect = false; setupConfigPortal(); DEBUG_WM("start loop"); @@ -267,6 +266,10 @@ void WiFiManager::setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { _sn = sn; } +void WiFiManager::setMinimumSignalQuality(int quality) { + _minimumQuality = quality; +} + /** Handle root or redirect to captive portal */ void WiFiManager::handleRoot() { @@ -328,19 +331,26 @@ void WiFiManager::handleWifi(boolean scan) { { DEBUG_WM(WiFi.SSID(i)); DEBUG_WM(WiFi.RSSI(i)); - String item = FPSTR(HTTP_ITEM); - String rssiQ; - rssiQ += getRSSIasQuality(WiFi.RSSI(i)); - item.replace("{v}", WiFi.SSID(i)); - item.replace("{r}", rssiQ); - if (WiFi.encryptionType(i) != ENC_TYPE_NONE) { - item.replace("{i}", FPSTR(HTTP_ITEM_PADLOCK)); + int quality = getRSSIasQuality(WiFi.RSSI(i)); + + if (_minimumQuality == -1 || _minimumQuality < quality) { + String item = FPSTR(HTTP_ITEM); + String rssiQ; + rssiQ += quality; + item.replace("{v}", WiFi.SSID(i)); + item.replace("{r}", rssiQ); + if (WiFi.encryptionType(i) != ENC_TYPE_NONE) { + item.replace("{i}", FPSTR(HTTP_ITEM_PADLOCK)); + } else { + item.replace("{i}", ""); + } + //DEBUG_WM(item); + server->sendContent(item); + delay(0); } else { - item.replace("{i}", ""); + DEBUG_WM(F("Skipping due to quality")); } - //DEBUG_WM(item); - server->sendContent(item); - delay(0); + } server->sendContent("
"); } diff --git a/WiFiManager.h b/WiFiManager.h index 556badc..3f26362 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -1,10 +1,11 @@ /************************************************************** WiFiManager is a library for the ESP8266/Arduino platform (https://github.com/esp8266/Arduino) to enable easy - configuration and reconfiguration of WiFi credentials and - store them in EEPROM. - inspired by http://www.esp8266.com/viewtopic.php?f=29&t=2520 + 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/esp8266/hardware/esp8266com/esp8266/libraries/DNSServer/examples/CaptivePortalAdvanced Built by AlexT https://github.com/tzapu Licensed under MIT license **************************************************************/ @@ -79,6 +80,8 @@ class WiFiManager //in seconds void setTimeout(unsigned long seconds); void setDebugOutput(boolean debug); + //defaults to not showing anything under 8% signal quality if called + void setMinimumSignalQuality(int quality = 8); //sets a custom ip /gateway /subnet configuration void setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn); @@ -112,11 +115,11 @@ class WiFiManager IPAddress _gw; IPAddress _sn; int _paramsCount = 0; + int _minimumQuality = -1; - String getEEPROMString(int start, int len); - void setEEPROMString(int start, int len, String string); + //String getEEPROMString(int start, int len); + //void setEEPROMString(int start, int len, String string); -// boolean keepLooping = true; int status = WL_IDLE_STATUS; int connectWifi(String ssid, String pass); diff --git a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index 5e69973..e5c9d9f 100644 --- a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -14,8 +14,8 @@ const char *mqtt_server = NULL; const char *mqtt_port = "8080"; const char *blynk_token = "YOUR_BLYNK_TOKEN"; - //flag for saving data - bool shouldSaveConfig = false; +//flag for saving data +bool shouldSaveConfig = false; //callback notifying us of the need to save config void saveConfigCallback () { @@ -79,18 +79,22 @@ void setup() { //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); - + //add all your parameters here wifiManager.addParameter(&custom_mqtt_server); wifiManager.addParameter(&custom_mqtt_port); wifiManager.addParameter(&custom_blynk_token); //reset settings - for testing - //wifiManager.resetSettings(); + 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 @@ -100,7 +104,7 @@ void setup() { //if it does not connect it starts an access point with the specified name //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect("AutoConnectAP")) { + if (!wifiManager.autoConnect("AutoConnectAP", "password")) { Serial.println("failed to connect and hit timeout"); delay(3000); //reset and try again, or maybe put it to deep sleep From f84d97323632bf773ddc5a555439ca13cbe39d41 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Tue, 12 Jan 2016 23:12:04 +0200 Subject: [PATCH 34/61] change icon and fonts thanks @markaswift --- WiFiManager.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/WiFiManager.h b/WiFiManager.h index 3f26362..6c82e74 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -21,12 +21,12 @@ const char HTTP_200[] PROGMEM = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"; //const char HTTP_HEAD[] PROGMEM = "{v}"; -const char HTTP_STYLE[] PROGMEM = ""; +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}% {i}
"; -const char HTTP_ITEM_PADLOCK[] PROGMEM = ""; +const char HTTP_ITEM_PADLOCK[] PROGMEM = ""; const char HTTP_FORM_START[] PROGMEM = "


"; const char HTTP_FORM_PARAM[] PROGMEM = "
"; const char HTTP_FORM_END[] PROGMEM = "
"; From 217faa43a3aa53390930a79e1d5788affeed7da1 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Wed, 13 Jan 2016 11:48:52 +0200 Subject: [PATCH 35/61] 0.6 release updated readme --- README.md | 145 ++++++++++++++++++++++++++++++++++++++------- WiFiManager.cpp | 4 +- library.json | 2 +- library.properties | 2 +- 4 files changed, 127 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 2431963..986b49b 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,28 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are #### This works with the ESP8266 Arduino platform with a recent stable release(2.0.0 or newer) https://github.com/esp8266/Arduino -## How It works +## Contents + - [How it works](#how-it-works) + - [Wishlist](#wishlist) + - [Quick start](#quick-start) + - Installing + - [Through Boards Manager](#install-through-boards-manager) + - [From Github](#checkout-from-github) + - [Using](#using) + - [Documentation](#documentation) + - [Access Point Password](#password-protect-the-configuration-access-point) + - [Callbacks](#callbacks) + - [Timeout](#timeout) + - [On Demand Configuration](#on-demand-configuration-portal) + - [Custom Parameters](#custom-parameters) + - [Custom IP Configuration](#custom-ip-configuration) + - [Filter Low Quality Networks](#filter-networks) + - [Debug Output](#debug) + - [Releases](#releases) + - [Contributors](#contributions-and-thanks) + + +## 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 - 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 @@ -15,12 +36,15 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - 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. +## 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) + ## Wishlist - ~~remove dependency on EEPROM library~~ - ~~move HTML Strings to PROGMEM~~ -- cleanup and streamline code +- ~~cleanup and streamline code~~ (although this is ongoing) - if timeout is set, extend it when a page is fetched in AP mode -- add ability to configure more parameters than ssid/password +- ~~add ability to configure more parameters than ssid/password~~ - maybe allow setting ip of ESP after reboot - ~~add to Arduino Boards Manager~~ - add to PlatformIO @@ -29,23 +53,24 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are ## Quick Start +### Installing You can either install through the Arduino Boards Manager or checkout the latest changes or a release from github #### Install through Boards Manager -__Currently version 0.5 works with release 2.0.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ +__Currently version 0.6 works with release 2.0.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) - search for WiFiManager ![WiFiManager package](http://i.imgur.com/18yIai8.png) - - click Install and start using it + - 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)__ - Checkout library to your Arduino libraries folder -#### Using +### Using - Include in your sketch ```cpp #include @@ -75,9 +100,11 @@ wifiManager.autoConnect(); After you write your sketch and start the ESP, it will try to connect to WiFi. If it fails it starts in Access Point mode. While in AP mode, connect to it then open a browser to the gateway IP, default 192.168.4.1, configure wifi, save and it should reboot and connect. -Also see examples. +Also see [examples](https://github.com/tzapu/WiFiManager/tree/master/examples). -### Password protect the configuration Access Point +## Documentation + +#### Password protect the configuration Access Point You can and should password protect the configuration access point. Simply add the password as a second parameter to `autoConnect`. A short password seems to have unpredictable results so use one that's around 8 characters or more in length. The guidelines are that a wifi password must consist of 8 to 63 ASCII-encoded characters in the range of 32 to 126 (decimal) @@ -85,7 +112,7 @@ The guidelines are that a wifi password must consist of 8 to 63 ASCII-encoded ch wifiManager.autoConnect("AutoConnectAP", "password") ``` -### Callbacks +#### Callbacks ##### Enter Config mode Use this if you need to do something when your device enters configuration mode on failed WiFi connection attempt. Before `autoConnect()` @@ -94,13 +121,32 @@ wifiManager.setAPCallback(configModeCallback); ``` `configModeCallback` declaration and example ```cpp -void configModeCallback () { +void configModeCallback (WiFiManager *myWiFiManager) { Serial.println("Entered config mode"); Serial.println(WiFi.softAPIP()); + + Serial.println(myWiFiManager->getConfigPortalSSID()); } ``` -### Timeout +##### Save settings +This gets called when custom parameters have been set **AND** a connection has been established. Use it to set a flag, so when all the configuration finishes, you can save the extra parameters somewhere. See [AutoConnectWithFSParameters Example](https://github.com/tzapu/WiFiManager/tree/master/examples/AutoConnectWithFSParameters). +```cpp +wifiManager.setSaveConfigCallback(saveConfigCallback); +``` +`saveConfigCallback` declaration and example +```cpp +//flag for saving data +bool shouldSaveConfig = false; + +//callback notifying us of the need to save config +void saveConfigCallback () { + Serial.println("Should save config"); + shouldSaveConfig = true; +} +``` + +#### Timeout If you need to set a timeout so the ESP doesn't hang waiting to be configured, for instance after a power failure, you can add ```cpp wifiManager.setTimeout(180); @@ -108,11 +154,46 @@ wifiManager.setTimeout(180); which will wait 3 minutes (180 seconds). When the time passes, the autoConnect function will return, no matter the outcome. Check for connection and if it's still not established do whatever is needed (on some modules I restart them to retry, on others I enter deep sleep) -### Debug -Debug is enabled by default on Serial. To disable add before autoConnect +#### On Demand Configuration Portal +If you would rather start the configuration portal on demand rather than automatically on a failed connection attempt, then this is for you. + +Instead of calling `autoConnect()` which does all the connecting and failover configuration portal setup for you, you need to use `startConfigPortal()` +Example usage ```cpp -wifiManager.setDebugOutput(false); +void loop() { + // is configuration portal requested? + if ( digitalRead(TRIGGER_PIN) == LOW ) { + WiFiManager wifiManager; + wifiManager.startConfigPortal("OnDemandAP"); + Serial.println("connected...yeey :)"); + } +} ``` +See example for a more complex version. [OnDemandConfigPortal](https://github.com/tzapu/WiFiManager/tree/master/examples/OnDemandConfigPortal) + +### 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. +**You are responsible for saving and loading these custom values.** The library just collects and displays the data for you as a convenience. +Usage scenario would be: +- load values from somewhere (EEPROM/FS) or generate some defaults +- add the custom parameters to WiFiManager using + ```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 + 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 +- Save and load custom parameters to file system in json form [AutoConnectWithFSParameters](https://github.com/tzapu/WiFiManager/tree/master/examples/AutoConnectWithFSParameters) +- *Save and load custom parameters to EEPROM* (not done yet) + ### Custom IP Configuration This will set your captive portal to a specific IP should you need/want such a feature. Add the following snippet before `autoConnect()` @@ -120,14 +201,32 @@ This will set your captive portal to a specific IP should you need/want such a f //set custom ip for portal wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); ``` +#### Filter Networks +If you would like to filter low signal quality networks you can tell WiFiManager to not show networks below an arbitrary quality %; +``` +wifiManager.setMinimumSignalQuality(10); +``` +will not show networks under 10% signal quality. If you omit the parameter it defaults to 8%; + +#### Debug +Debug is enabled by default on Serial. To disable add before autoConnect +```cpp +wifiManager.setDebugOutput(false); +``` ## Releases -#### 0.5 +#### 0.6 + - custom parameters + - prettier + - on demand config portal + - commit #100 :D + +##### 0.5 - Added to Arduino Boards Manager - Thanks Max - moved most stuff to PROGMEM - added signal quality and a nice little padlock to show which networks are encrypted -##### v0.4 - user contributed changes - Thank you +##### v0.4 - all of it user contributed changes - Thank you - added ability to password protect the configuration Access Point - callback for enter configuration mode - memory allocation improvements @@ -139,28 +238,30 @@ wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255, ##### v0.2 needs the latest staging version (or at least a recent release of the staging version) to work +This is jsut random textTo show the lagginess. +[the editor is completly](behing the typing) ##### v0.1 works with the staging release ver. 1.6.5-1044-g170995a, built on Aug 10, 2015 of the ESP8266 Arduino library. - ### Contributions and thanks The support and help I got from the community has been nothing short of phenomenal. I can't thank you guys enough. This is my first real attept in developing open source stuff and I must say, now I understand why people are so dedicated to it, it is because of all the wonderful people involved. __THANK YOU__ [Maximiliano Duarte](https://github.com/domonetic) - [alltheblinkythings](https://github.com/alltheblinkythings) - [Niklas Wall](https://github.com/niklaswall) - [Jakub Piasecki](https://github.com/zaporylie) - [Peter Allan](https://github.com/alwynallan) - [John Little](https://github.com/j0hnlittle) +[markaswift](https://github.com/markaswift) +[franklinvv](https://github.com/franklinvv) +[Alberto Ricci Bitti](https://github.com/riccibitti) +[SebiPanther](https://github.com/SebiPanther) + +Sorry if i have missed anyone. #### Inspiration - http://www.esp8266.com/viewtopic.php?f=29&t=2520 diff --git a/WiFiManager.cpp b/WiFiManager.cpp index c7f91ad..f118517 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -137,7 +137,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo connect = false; setupConfigPortal(); - DEBUG_WM("start loop"); + while (timeout == 0 || millis() < start + timeout) { //DNS dnsServer->processNextRequest(); @@ -169,7 +169,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo server.reset(); dnsServer.reset(); - DEBUG_WM("end loop"); + return WiFi.status() == WL_CONNECTED; } diff --git a/library.json b/library.json index badf097..e6e5435 100644 --- a/library.json +++ b/library.json @@ -14,6 +14,6 @@ }, "frameworks": "arduino", "platforms": "esp8266" - "version": "0.5", + "version": "0.6", "architecture": "esp8266", } diff --git a/library.properties b/library.properties index 55f390a..c43b894 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=WiFiManager -version=0.5 +version=0.6 author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal From b4e688a5432dd9a962fb23959695b3f00c1c0586 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Thu, 14 Jan 2016 20:29:58 +0200 Subject: [PATCH 36/61] changed template fix for web server returning empty pages in latest github --- README.md | 9 +++++++++ WiFiManager.cpp | 5 ++++- WiFiManager.h | 2 +- extras/WiFiManager.template.html | 6 +++--- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 986b49b..283f44a 100644 --- a/README.md +++ b/README.md @@ -251,14 +251,23 @@ The support and help I got from the community has been nothing short of phenomen __THANK YOU__ [Maximiliano Duarte](https://github.com/domonetic) + [alltheblinkythings](https://github.com/alltheblinkythings) + [Niklas Wall](https://github.com/niklaswall) + [Jakub Piasecki](https://github.com/zaporylie) + [Peter Allan](https://github.com/alwynallan) + [John Little](https://github.com/j0hnlittle) + [markaswift](https://github.com/markaswift) + [franklinvv](https://github.com/franklinvv) + [Alberto Ricci Bitti](https://github.com/riccibitti) + [SebiPanther](https://github.com/SebiPanther) Sorry if i have missed anyone. diff --git a/WiFiManager.cpp b/WiFiManager.cpp index f118517..6926ce5 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -281,6 +281,7 @@ void WiFiManager::handleRoot() { server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server->sendHeader("Pragma", "no-cache"); server->sendHeader("Expires", "-1"); + server->setContentLength(CONTENT_LENGTH_UNKNOWN); server->send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. String head = HTTP_HEAD; @@ -309,8 +310,9 @@ void WiFiManager::handleWifi(boolean scan) { server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server->sendHeader("Pragma", "no-cache"); server->sendHeader("Expires", "-1"); + server->setContentLength(CONTENT_LENGTH_UNKNOWN); server->send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. - + server->setContentLength(CONTENT_LENGTH_UNKNOWN); String head = HTTP_HEAD; head.replace("{v}", "Config ESP"); @@ -410,6 +412,7 @@ void WiFiManager::handleWifiSave() { server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server->sendHeader("Pragma", "no-cache"); server->sendHeader("Expires", "-1"); + server->setContentLength(CONTENT_LENGTH_UNKNOWN); server->send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. String head = HTTP_HEAD; diff --git a/WiFiManager.h b/WiFiManager.h index 6c82e74..03626ca 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -20,7 +20,7 @@ const char HTTP_200[] PROGMEM = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"; -//const char HTTP_HEAD[] PROGMEM = "{v}"; +//const char HTTP_HEAD[] PROGMEM = "{v}"; const char HTTP_STYLE[] PROGMEM = ""; const char HTTP_SCRIPT[] PROGMEM = ""; const char HTTP_HEAD_END[] PROGMEM = "
"; diff --git a/extras/WiFiManager.template.html b/extras/WiFiManager.template.html index 4d005b2..5ef5924 100644 --- a/extras/WiFiManager.template.html +++ b/extras/WiFiManager.template.html @@ -1,5 +1,5 @@ -{v} - +{v} +
{v} {r}% {i}
@@ -7,7 +7,7 @@
Vila17 95%
Marcelica 100%
-
PMica 110%
+
PMica 110%




From 598baf445169fb662283e9757555c262464f7501 Mon Sep 17 00:00:00 2001 From: Jonathan Endersby Date: Sun, 17 Jan 2016 07:40:26 +0200 Subject: [PATCH 37/61] Adding Static IP Support --- README.md | 7 +++++++ WiFiManager.cpp | 12 ++++++++++++ WiFiManager.h | 7 +++++-- 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 283f44a..11150f6 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,13 @@ This will set your captive portal to a specific IP should you need/want such a f //set custom ip for portal wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); ``` + +### Custom Static IP Configuration +This will make use the specified IP configuration instead of using DHCP. +``` +wifiManager.setStaticIPConfig(IPAddress(192,168,0,99), IPAddress(192,168,0,1), IPAddress(255,255,255,0)); +``` + #### Filter Networks If you would like to filter low signal quality networks you can tell WiFiManager to not show networks below an arbitrary quality %; ``` diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 6926ce5..4acf038 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -113,6 +113,12 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { // attempt to connect; should it fail, fall back to AP WiFi.mode(WIFI_STA); + + // check if we've got static_ip settings, if we do, use those. + if (_static_ip){ + WiFi.config(_static_ip, _static_gw, _static_sn); + } + if (connectWifi(ssid, pass) == WL_CONNECTED) { DEBUG_WM(F("IP Address:")); DEBUG_WM(WiFi.localIP()); @@ -266,6 +272,12 @@ void WiFiManager::setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { _sn = sn; } +void WiFiManager::setStaticIPConfig(IPAddress static_ip, IPAddress static_gw, IPAddress static_sn) { + _static_ip = static_ip; + _static_gw = static_gw; + _static_sn = static_sn; +} + void WiFiManager::setMinimumSignalQuality(int quality) { _minimumQuality = quality; } diff --git a/WiFiManager.h b/WiFiManager.h index 03626ca..5708644 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -82,14 +82,14 @@ class WiFiManager void setDebugOutput(boolean debug); //defaults to not showing anything under 8% signal quality if called void setMinimumSignalQuality(int quality = 8); - //sets a custom ip /gateway /subnet configuration void setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + //sets config for a static IP + void setStaticIPConfig(IPAddress static_ip, IPAddress static_gw, IPAddress static_sn); //called when AP mode and config portal is started void setAPCallback( void (*func)(WiFiManager*) ); //called when settings have been changed and connection was successful void setSaveConfigCallback( void (*func)(void) ); - //adds a custom parameter void addParameter(WiFiManagerParameter *p); @@ -114,6 +114,9 @@ class WiFiManager IPAddress _ip; IPAddress _gw; IPAddress _sn; + IPAddress _static_ip; + IPAddress _static_gw; + IPAddress _static_sn; int _paramsCount = 0; int _minimumQuality = -1; From e2bbd527d1767c6983a4db9a9e91fb1e48b76ec3 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Sun, 17 Jan 2016 13:27:24 +0200 Subject: [PATCH 38/61] added static mode thanks @jonathanendersby renamed private variables for more clarity readme update --- README.md | 18 +++++++++++------- WiFiManager.cpp | 30 ++++++++++++++++-------------- WiFiManager.h | 16 ++++++++-------- 3 files changed, 35 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 11150f6..5c34ebc 100644 --- a/README.md +++ b/README.md @@ -195,22 +195,22 @@ This feature is a lot more involved than all the others, so here are some exampl - *Save and load custom parameters to EEPROM* (not done yet) -### Custom IP Configuration +### Custom Access Point IP Configuration This will set your captive portal to a specific IP should you need/want such a feature. Add the following snippet before `autoConnect()` ```cpp //set custom ip for portal -wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); +wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); ``` -### Custom Static IP Configuration -This will make use the specified IP configuration instead of using DHCP. -``` -wifiManager.setStaticIPConfig(IPAddress(192,168,0,99), IPAddress(192,168,0,1), IPAddress(255,255,255,0)); +### Custom Station Static IP Configuration +This will make use the specified IP configuration instead of using DHCP in station mode. +```cpp +wifiManager.setSTAStaticIPConfig(IPAddress(192,168,0,99), IPAddress(192,168,0,1), IPAddress(255,255,255,0)); ``` #### Filter Networks If you would like to filter low signal quality networks you can tell WiFiManager to not show networks below an arbitrary quality %; -``` +```cpp wifiManager.setMinimumSignalQuality(10); ``` will not show networks under 10% signal quality. If you omit the parameter it defaults to 8%; @@ -277,6 +277,10 @@ __THANK YOU__ [SebiPanther](https://github.com/SebiPanther) +[jonathanendersby](https://github.com/jonathanendersby) + +[walthercarsten](https://github.com/walthercarsten) + Sorry if i have missed anyone. #### Inspiration diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 4acf038..b43efff 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -67,9 +67,9 @@ void WiFiManager::setupConfigPortal() { } //optional soft ip config - if (_ip) { - DEBUG_WM(F("Custom IP/GW/Subnet")); - WiFi.softAPConfig(_ip, _gw, _sn); + 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) { @@ -115,8 +115,10 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { WiFi.mode(WIFI_STA); // check if we've got static_ip settings, if we do, use those. - if (_static_ip){ - WiFi.config(_static_ip, _static_gw, _static_sn); + 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()); } if (connectWifi(ssid, pass) == WL_CONNECTED) { @@ -266,16 +268,16 @@ void WiFiManager::setDebugOutput(boolean debug) { _debug = debug; } -void WiFiManager::setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { - _ip = ip; - _gw = gw; - _sn = sn; +void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { + _ap_static_ip = ip; + _ap_static_gw = gw; + _ap_static_sn = sn; } -void WiFiManager::setStaticIPConfig(IPAddress static_ip, IPAddress static_gw, IPAddress static_sn) { - _static_ip = static_ip; - _static_gw = static_gw; - _static_sn = static_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) { @@ -346,7 +348,7 @@ void WiFiManager::handleWifi(boolean scan) { DEBUG_WM(WiFi.SSID(i)); DEBUG_WM(WiFi.RSSI(i)); int quality = getRSSIasQuality(WiFi.RSSI(i)); - + if (_minimumQuality == -1 || _minimumQuality < quality) { String item = FPSTR(HTTP_ITEM); String rssiQ; diff --git a/WiFiManager.h b/WiFiManager.h index 5708644..1dc2e1e 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -83,9 +83,9 @@ class WiFiManager //defaults to not showing anything under 8% signal quality if called void setMinimumSignalQuality(int quality = 8); //sets a custom ip /gateway /subnet configuration - void setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); //sets config for a static IP - void setStaticIPConfig(IPAddress static_ip, IPAddress static_gw, IPAddress static_sn); + void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); //called when AP mode and config portal is started void setAPCallback( void (*func)(WiFiManager*) ); //called when settings have been changed and connection was successful @@ -111,12 +111,12 @@ class WiFiManager String _pass = ""; unsigned long timeout = 0; unsigned long start = 0; - IPAddress _ip; - IPAddress _gw; - IPAddress _sn; - IPAddress _static_ip; - IPAddress _static_gw; - IPAddress _static_sn; + IPAddress _ap_static_ip; + IPAddress _ap_static_gw; + IPAddress _ap_static_sn; + IPAddress _sta_static_ip; + IPAddress _sta_static_gw; + IPAddress _sta_static_sn; int _paramsCount = 0; int _minimumQuality = -1; From 13fa4ffa3a326e7bf0936533ff50197c734d69d1 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 18 Jan 2016 11:20:15 +0200 Subject: [PATCH 39/61] added example on how to save static ip to FS config.json added static ip to config portal, if set --- README.md | 11 +- WiFiManager.cpp | 67 +++++- WiFiManager.h | 16 +- ...AutoConnectWithFSParametersAndCustomIP.ino | 193 ++++++++++++++++++ 4 files changed, 265 insertions(+), 22 deletions(-) create mode 100644 examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino diff --git a/README.md b/README.md index 5c34ebc..fca79af 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - ~~cleanup and streamline code~~ (although this is ongoing) - if timeout is set, extend it when a page is fetched in AP mode - ~~add ability to configure more parameters than ssid/password~~ -- maybe allow setting ip of ESP after reboot +- ~~maybe allow setting ip of ESP after reboot~~ - ~~add to Arduino Boards Manager~~ - add to PlatformIO - add multiple sets of network credentials @@ -130,7 +130,9 @@ void configModeCallback (WiFiManager *myWiFiManager) { ``` ##### Save settings -This gets called when custom parameters have been set **AND** a connection has been established. Use it to set a flag, so when all the configuration finishes, you can save the extra parameters somewhere. See [AutoConnectWithFSParameters Example](https://github.com/tzapu/WiFiManager/tree/master/examples/AutoConnectWithFSParameters). +This gets called when custom parameters have been set **AND** a connection has been established. Use it to set a flag, so when all the configuration finishes, you can save the extra parameters somewhere. + +See [AutoConnectWithFSParameters Example](https://github.com/tzapu/WiFiManager/tree/master/examples/AutoConnectWithFSParameters). ```cpp wifiManager.setSaveConfigCallback(saveConfigCallback); ``` @@ -157,7 +159,8 @@ Check for connection and if it's still not established do whatever is needed (on #### On Demand Configuration Portal If you would rather start the configuration portal on demand rather than automatically on a failed connection attempt, then this is for you. -Instead of calling `autoConnect()` which does all the connecting and failover configuration portal setup for you, you need to use `startConfigPortal()` +Instead of calling `autoConnect()` which does all the connecting and failover configuration portal setup for you, you need to use `startConfigPortal()`. __Do not use BOTH.__ + Example usage ```cpp void loop() { @@ -245,8 +248,6 @@ wifiManager.setDebugOutput(false); ##### v0.2 needs the latest staging version (or at least a recent release of the staging version) to work -This is jsut random textTo show the lagginess. -[the editor is completly](behing the typing) ##### v0.1 works with the staging release ver. 1.6.5-1044-g170995a, built on Aug 10, 2015 of the ESP8266 Arduino library. diff --git a/WiFiManager.cpp b/WiFiManager.cpp index b43efff..a553a88 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -114,13 +114,6 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { // attempt to connect; should it fail, fall back to AP WiFi.mode(WIFI_STA); - // 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()); - } - if (connectWifi(ssid, pass) == WL_CONNECTED) { DEBUG_WM(F("IP Address:")); DEBUG_WM(WiFi.localIP()); @@ -154,9 +147,9 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo if (connect) { + connect = false; delay(2000); DEBUG_WM(F("Connecting to new AP")); - connect = false; // using user-provided _ssid, _pass in place of system-stored ssid amd pass if (connectWifi(_ssid, _pass) != WL_CONNECTED) { DEBUG_WM(F("Failed to connect.")); @@ -184,7 +177,15 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo int WiFiManager::connectWifi(String ssid, String pass) { DEBUG_WM(F("Connecting as wifi client...")); - //WiFi.disconnect(); + + // 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()); + } + + WiFi.begin(ssid.c_str(), pass.c_str()); int connRes = WiFi.waitForConnectResult(); DEBUG_WM ("Connection result: "); @@ -394,6 +395,38 @@ void WiFiManager::handleWifi(boolean scan) { server->sendContent_P("
"); } + 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()); + + server->sendContent(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()); + + server->sendContent(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()); + + server->sendContent(item); + + server->sendContent_P("
"); + } + server->sendContent_P(HTTP_FORM_END); server->sendContent_P(HTTP_END); server->client().stop(); @@ -423,6 +456,22 @@ void WiFiManager::handleWifiSave() { DEBUG_WM(value); } + if(server->arg("ip") != "") { + DEBUG_WM(F("static ip")); + DEBUG_WM(server->arg("ip")); + _sta_static_ip.fromString(server->arg("ip")); + } + if(server->arg("gw")) { + DEBUG_WM(F("static gateway")); + DEBUG_WM(server->arg("gw")); + _sta_static_gw.fromString(server->arg("gw")); + } + if(server->arg("sn")) { + DEBUG_WM(F("static netmask")); + DEBUG_WM(server->arg("sn")); + _sta_static_sn.fromString(server->arg("sn")); + } + server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server->sendHeader("Pragma", "no-cache"); server->sendHeader("Expires", "-1"); diff --git a/WiFiManager.h b/WiFiManager.h index 1dc2e1e..35919e8 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -40,15 +40,15 @@ class WiFiManagerParameter { public: WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length); - const char* getID(); - const char* getValue(); - const char* getPlaceholder(); - int getValueLength(); + const char *getID(); + const char *getValue(); + const char *getPlaceholder(); + int getValueLength(); private: - const char* _id; - const char* _placeholder; - char* _value; - int _length; + const char *_id; + const char *_placeholder; + char *_value; + int _length; friend class WiFiManager; }; diff --git a/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino b/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino new file mode 100644 index 0000000..bd44cbe --- /dev/null +++ b/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino @@ -0,0 +1,193 @@ +#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 //https://github.com/bblanchon/ArduinoJson + +//define your default values here, if there are different values in config.json, they are overwritten. +char mqtt_server[40]; +char mqtt_port[5] = "8080"; +char blynk_token[64] = "YOUR_BLYNK_TOKEN"; +//default custom static IP +char static_ip[18] = "10.0.1.56"; +char static_gw[18] = "10.0.1.1"; +char static_sn[18] = "255.255.255.0"; + +//flag for saving data +bool shouldSaveConfig = false; + +//callback notifying us of the need to save config +void saveConfigCallback () { + Serial.println("Should save config"); + shouldSaveConfig = true; +} + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + + //clean FS, for testing + //SPIFFS.format(); + + //read configuration from FS json + Serial.println("mounting FS..."); + + if (SPIFFS.begin()) { + Serial.println("mounted file system"); + if (SPIFFS.exists("/config.json")) { + //file exists, reading and loading + Serial.println("reading config file"); + File configFile = SPIFFS.open("/config.json", "r"); + if (configFile) { + Serial.println("opened config file"); + size_t size = configFile.size(); + // Allocate a buffer to store contents of the file. + std::unique_ptr buf(new char[size]); + + configFile.readBytes(buf.get(), size); + StaticJsonBuffer<200> jsonBuffer; + JsonObject& json = jsonBuffer.parseObject(buf.get()); + json.printTo(Serial); + if (json.success()) { + Serial.println("\nparsed json"); + + strcpy(mqtt_server, json["mqtt_server"]); + strcpy(mqtt_port, json["mqtt_port"]); + strcpy(blynk_token, json["blynk_token"]); + + //mqtt_server = json["mqtt_server"]; + //mqtt_port = json["mqtt_port"]; + //blynk_token = json["blynk_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"); + } + } + } + } else { + Serial.println("failed to mount FS"); + } + //end read + Serial.println(static_ip); + Serial.println(blynk_token); + Serial.println(mqtt_server); + + + // 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, 64); + + //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 + IPAddress _ip,_gw,_sn; + _ip.fromString(static_ip); + _gw.fromString(static_gw); + _sn.fromString(static_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 - 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" + //and goes into a blocking loop awaiting configuration + if (!wifiManager.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(); + delay(5000); + } + + //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()); + //mqtt_port = custom_mqtt_port.getValue(); + //blynk_token = custom_blynk_token.getValue(); + + //save the custom parameters to FS + if (shouldSaveConfig) { + Serial.println("saving config"); + StaticJsonBuffer<200> jsonBuffer; + JsonObject& json = jsonBuffer.createObject(); + json["mqtt_server"] = mqtt_server; + json["mqtt_port"] = mqtt_port; + json["blynk_token"] = blynk_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.prettyPrintTo(Serial); + json.printTo(configFile); + configFile.close(); + //end save + } + + Serial.println("local ip"); + Serial.println(WiFi.localIP()); + Serial.println(WiFi.gatewayIP()); + Serial.println(WiFi.subnetMask()); +} + +void loop() { + // put your main code here, to run repeatedly: + + +} From 478d291bd26b151a85390b9664fdc260c7118df7 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 18 Jan 2016 11:37:00 +0200 Subject: [PATCH 40/61] more readme --- README.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fca79af..c8f8e31 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - [Custom IP Configuration](#custom-ip-configuration) - [Filter Low Quality Networks](#filter-networks) - [Debug Output](#debug) + - [Troubleshooting](#troubleshooting) - [Releases](#releases) - [Contributors](#contributions-and-thanks) @@ -67,7 +68,7 @@ __Currently version 0.6 works with release 2.0.0 or newer of the [ESP8266 core f - 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 the HEAD (as of 18 jan 2016) or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ - Checkout library to your Arduino libraries folder ### Using @@ -205,11 +206,12 @@ This will set your captive portal to a specific IP should you need/want such a f wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); ``` -### Custom Station Static IP Configuration +### Custom Station (client) Static IP Configuration This will make use the specified IP configuration instead of using DHCP in station mode. ```cpp wifiManager.setSTAStaticIPConfig(IPAddress(192,168,0,99), IPAddress(192,168,0,1), IPAddress(255,255,255,0)); ``` +There are a couple of examples in the examples folder that show you how to set a static IP and even how to configure it through the web configuration portal. #### Filter Networks If you would like to filter low signal quality networks you can tell WiFiManager to not show networks below an arbitrary quality %; @@ -224,6 +226,11 @@ Debug is enabled by default on Serial. To disable add before autoConnect wifiManager.setDebugOutput(false); ``` +## Troubleshooting +If you get compilation errors, more often than not, you may need to install a newer version of the ESP8266 core for Arduino. + +I am trying to keep releases working with release versions of the core, so they can be installed through boards manager, but if you checkout the latest version directly from github, sometimes, the library will only work if you update the ESP8266 core to the latest version because I am using some newly added function. + ## Releases #### 0.6 - custom parameters From 0b06e465ce9fa94a9341ff1ded4e48a8a4f3547b Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 18 Jan 2016 15:33:45 +0200 Subject: [PATCH 41/61] updated example due to memory issues added more readme --- README.md | 4 +++ .../AutoConnectWithFSParameters.ino | 30 ++++++++++++------- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index c8f8e31..91ad77a 100644 --- a/README.md +++ b/README.md @@ -231,6 +231,10 @@ If you get compilation errors, more often than not, you may need to install a ne I am trying to keep releases working with release versions of the core, so they can be installed through boards manager, but if you checkout the latest version directly from github, sometimes, the library will only work if you update the ESP8266 core to the latest version because I am using some newly added function. + +If you connect to the created configuration Access Point but the configuration portal does not show up, just open a browser and type in the IP of the web portal, by default `192.168.4.1`. + + ## Releases #### 0.6 - custom parameters diff --git a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index e5c9d9f..447f99e 100644 --- a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -10,9 +10,9 @@ #include //https://github.com/bblanchon/ArduinoJson //define your default values here, if there are different values in config.json, they are overwritten. -const char *mqtt_server = NULL; -const char *mqtt_port = "8080"; -const char *blynk_token = "YOUR_BLYNK_TOKEN"; +char mqtt_server[40]; +char mqtt_port[6] = "8080"; +char blynk_token[34] = "YOUR_BLYNK_TOKEN"; //flag for saving data bool shouldSaveConfig = false; @@ -54,9 +54,10 @@ void setup() { if (json.success()) { Serial.println("\nparsed json"); - mqtt_server = json["mqtt_server"]; - mqtt_port = json["mqtt_port"]; - blynk_token = json["blynk_token"]; + strcpy(mqtt_server, json["mqtt_server"]); + strcpy(mqtt_port, json["mqtt_port"]); + strcpy(blynk_token, json["blynk_token"]); + } else { Serial.println("failed to load json config"); } @@ -73,7 +74,7 @@ void 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, 8); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5); WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 32); //WiFiManager @@ -83,13 +84,16 @@ void setup() { //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); //reset settings - for testing - wifiManager.resetSettings(); + //wifiManager.resetSettings(); //set minimu quality of signal so it ignores AP's under that quality //defaults to 8% @@ -116,9 +120,9 @@ void setup() { Serial.println("connected...yeey :)"); //read updated parameters - mqtt_server = custom_mqtt_server.getValue(); - mqtt_port = custom_mqtt_port.getValue(); - blynk_token = custom_blynk_token.getValue(); + strcpy(mqtt_server, custom_mqtt_server.getValue()); + strcpy(mqtt_port, custom_mqtt_port.getValue()); + strcpy(blynk_token, custom_blynk_token.getValue()); //save the custom parameters to FS if (shouldSaveConfig) { @@ -139,6 +143,10 @@ void setup() { configFile.close(); //end save } + + Serial.println("local ip"); + Serial.println(WiFi.localIP()); + } void loop() { From 823767cb8b85f8e2127638372468a4763950da01 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 18 Jan 2016 16:34:25 +0200 Subject: [PATCH 42/61] char array would cut off strings that were too small in size --- WiFiManager.cpp | 2 +- ...AutoConnectWithFSParametersAndCustomIP.ino | 19 +++++++------------ 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index a553a88..d8e3d1b 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -16,7 +16,7 @@ WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placehold _id = id; _placeholder = placeholder; _length = length; - _value = new char[length]; + _value = new char[length+1]; for (int i = 0; i < length; i++) { _value[i] = 0; } diff --git a/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino b/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino index bd44cbe..e76867b 100644 --- a/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino +++ b/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino @@ -10,13 +10,14 @@ #include //https://github.com/bblanchon/ArduinoJson //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[5] = "8080"; -char blynk_token[64] = "YOUR_BLYNK_TOKEN"; +char mqtt_port[6] = "8080"; +char blynk_token[33] = "YOUR_BLYNK_TOKEN"; //default custom static IP -char static_ip[18] = "10.0.1.56"; -char static_gw[18] = "10.0.1.1"; -char static_sn[18] = "255.255.255.0"; +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; @@ -61,10 +62,6 @@ void setup() { strcpy(mqtt_port, json["mqtt_port"]); strcpy(blynk_token, json["blynk_token"]); - //mqtt_server = json["mqtt_server"]; - //mqtt_port = json["mqtt_port"]; - //blynk_token = json["blynk_token"]; - if(json["ip"]) { Serial.println("setting custom ip from config"); //static_ip = json["ip"]; @@ -100,7 +97,7 @@ void setup() { // 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, 64); + WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 34); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around @@ -153,8 +150,6 @@ void setup() { strcpy(mqtt_server, custom_mqtt_server.getValue()); strcpy(mqtt_port, custom_mqtt_port.getValue()); strcpy(blynk_token, custom_blynk_token.getValue()); - //mqtt_port = custom_mqtt_port.getValue(); - //blynk_token = custom_blynk_token.getValue(); //save the custom parameters to FS if (shouldSaveConfig) { From e71b985c0d44852f31e0d231ecd602f15d81be14 Mon Sep 17 00:00:00 2001 From: Joakim G Date: Tue, 19 Jan 2016 13:51:48 +0100 Subject: [PATCH 43/61] Fixed typo in library.json Added missing comma that made the JSON invalid. Noticed this while trying to use the lib in platformio. --- library.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library.json b/library.json index e6e5435..5d96fd9 100644 --- a/library.json +++ b/library.json @@ -13,7 +13,7 @@ "url": "http://tzapu.com" }, "frameworks": "arduino", - "platforms": "esp8266" + "platforms": "esp8266", "version": "0.6", - "architecture": "esp8266", + "architecture": "esp8266" } From 5691eb160492136a57a39c7401b304ffeb31b7d5 Mon Sep 17 00:00:00 2001 From: Ivan Kravets Date: Tue, 19 Jan 2016 16:19:58 +0200 Subject: [PATCH 44/61] @PlatformIO Library Registry manifest file * This library in Web Registry: http://platformio.org/#!/lib/show/566/WifiManager * Specification: [library.json](http://docs.platformio.org/en/latest/librarymanager/config.html) * Library Manager: http://docs.platformio.org/en/latest/librarymanager/index.html --- WifiManager | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 WifiManager diff --git a/WifiManager b/WifiManager new file mode 100644 index 0000000..43793ab --- /dev/null +++ b/WifiManager @@ -0,0 +1,13 @@ +{ + "name": "WifiManager", + "keywords": "wifi, wi-fi", + "description": "ESP8266 WiFi Connection manager with fallback web configuration portal", + "repository": + { + "type": "git", + "url": "https://github.com/tzapu/WiFiManager.git" + }, + "frameworks": "arduino", + "platforms": "espressif", + "version": "0.6" +} From 62c621f783b32bbc5f5f2425f206a94b3c741ba9 Mon Sep 17 00:00:00 2001 From: Ivan Kravets Date: Tue, 19 Jan 2016 17:19:27 +0200 Subject: [PATCH 45/61] Delete typo file Sorry, it was my typo. The file should be named as `library.json` --- WifiManager | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 WifiManager diff --git a/WifiManager b/WifiManager deleted file mode 100644 index 43793ab..0000000 --- a/WifiManager +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "WifiManager", - "keywords": "wifi, wi-fi", - "description": "ESP8266 WiFi Connection manager with fallback web configuration portal", - "repository": - { - "type": "git", - "url": "https://github.com/tzapu/WiFiManager.git" - }, - "frameworks": "arduino", - "platforms": "espressif", - "version": "0.6" -} From 1208e03e616a269bc14f37883bcd46e33ed857b4 Mon Sep 17 00:00:00 2001 From: Ivan Kravets Date: Tue, 19 Jan 2016 17:19:49 +0200 Subject: [PATCH 46/61] Update library.json --- library.json | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/library.json b/library.json index 5d96fd9..43793ab 100644 --- a/library.json +++ b/library.json @@ -1,19 +1,13 @@ { "name": "WifiManager", - "keywords": "wifi, wi-fi, ESP8266", + "keywords": "wifi, wi-fi", "description": "ESP8266 WiFi Connection manager with fallback web configuration portal", "repository": { "type": "git", "url": "https://github.com/tzapu/WiFiManager.git" }, - "authors": - { - "name": "tzapu", - "url": "http://tzapu.com" - }, "frameworks": "arduino", - "platforms": "esp8266", - "version": "0.6", - "architecture": "esp8266" + "platforms": "espressif", + "version": "0.6" } From c1038ea3713f5e0c8c13cfccc1d7f96bbaa972c4 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Fri, 22 Jan 2016 10:28:31 +0200 Subject: [PATCH 47/61] fixed check for gateway and subnet --- WiFiManager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index d8e3d1b..0bfa0db 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -461,12 +461,12 @@ void WiFiManager::handleWifiSave() { DEBUG_WM(server->arg("ip")); _sta_static_ip.fromString(server->arg("ip")); } - if(server->arg("gw")) { + if(server->arg("gw") != "") { DEBUG_WM(F("static gateway")); DEBUG_WM(server->arg("gw")); _sta_static_gw.fromString(server->arg("gw")); } - if(server->arg("sn")) { + if(server->arg("sn") != "") { DEBUG_WM(F("static netmask")); DEBUG_WM(server->arg("sn")); _sta_static_sn.fromString(server->arg("sn")); From f33cb4fb323ba552cf113f2bf66536062993ff4c Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Sat, 23 Jan 2016 11:35:27 +0200 Subject: [PATCH 48/61] added feedback through LED blink example --- .../AutoConnectWithFeedbackLED.ino | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino diff --git a/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino b/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino new file mode 100644 index 0000000..77b264b --- /dev/null +++ b/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino @@ -0,0 +1,68 @@ +#include //https://github.com/esp8266/Arduino + +//needed for library +#include +#include +#include //https://github.com/tzapu/WiFiManager + +//for LED status +#include +Ticker ticker; + +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 +} + +//gets called when WiFiManager enters configuration mode +void configModeCallback (WiFiManager *myWiFiManager) { + Serial.println("Entered config mode"); + Serial.println(WiFi.softAPIP()); + //if you used auto generated SSID, print it + Serial.println(myWiFiManager->getConfigPortalSSID()); + //entered config mode, make led toggle faster + ticker.attach(0.2, tick); +} + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //set led pin as output + pinMode(BUILTIN_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; + //reset settings - for testing + //wifiManager.resetSettings(); + + //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode + wifiManager.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()) { + Serial.println("failed to connect and hit timeout"); + //reset and try again, or maybe put it to deep sleep + ESP.reset(); + delay(1000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + ticker.detach(); + //keep LED on + digitalWrite(BUILTIN_LED, LOW); +} + +void loop() { + // put your main code here, to run repeatedly: + +} From bdc7da660a37fa96f803d8a5fc204647213a72dc Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Sun, 24 Jan 2016 14:46:20 +0200 Subject: [PATCH 49/61] updated examples --- .../AutoConnectWithFSParameters.ino | 6 +++--- .../AutoConnectWithFSParametersAndCustomIP.ino | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index 447f99e..42dabf3 100644 --- a/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -48,7 +48,7 @@ void setup() { std::unique_ptr buf(new char[size]); configFile.readBytes(buf.get(), size); - StaticJsonBuffer<200> jsonBuffer; + DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { @@ -97,7 +97,7 @@ void setup() { //set minimu quality of signal so it ignores AP's under that quality //defaults to 8% - wifiManager.setMinimumSignalQuality(); + //wifiManager.setMinimumSignalQuality(); //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep @@ -127,7 +127,7 @@ void setup() { //save the custom parameters to FS if (shouldSaveConfig) { Serial.println("saving config"); - StaticJsonBuffer<200> jsonBuffer; + DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["mqtt_server"] = mqtt_server; json["mqtt_port"] = mqtt_port; diff --git a/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino b/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino index e76867b..3f391ae 100644 --- a/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino +++ b/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino @@ -52,7 +52,7 @@ void setup() { std::unique_ptr buf(new char[size]); configFile.readBytes(buf.get(), size); - StaticJsonBuffer<200> jsonBuffer; + DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { @@ -154,7 +154,7 @@ void setup() { //save the custom parameters to FS if (shouldSaveConfig) { Serial.println("saving config"); - StaticJsonBuffer<200> jsonBuffer; + DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["mqtt_server"] = mqtt_server; json["mqtt_port"] = mqtt_port; From 031b7c97bc24da384e013e43d198b9615a305387 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 25 Jan 2016 09:25:51 +0200 Subject: [PATCH 50/61] added ability of returning even if connection fails added example that resets after configuration if connection is unsuccessful --- WiFiManager.cpp | 32 +++++++++--- WiFiManager.h | 3 ++ .../AutoConnectWithReset.ino | 49 +++++++++++++++++++ keywords.txt | 13 ++++- 4 files changed, 89 insertions(+), 8 deletions(-) create mode 100644 examples/AutoConnectWithReset/AutoConnectWithReset.ino diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 0bfa0db..0819fb4 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -108,13 +108,13 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { DEBUG_WM(F("AutoConnect")); // read eeprom for ssid and pass - String ssid = getSSID(); - String pass = getPassword(); + //String ssid = getSSID(); + //String pass = getPassword(); // attempt to connect; should it fail, fall back to AP WiFi.mode(WIFI_STA); - if (connectWifi(ssid, pass) == WL_CONNECTED) { + if (connectWifi("", "") == WL_CONNECTED) { DEBUG_WM(F("IP Address:")); DEBUG_WM(WiFi.localIP()); //connected @@ -150,7 +150,8 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo connect = false; delay(2000); DEBUG_WM(F("Connecting to new AP")); - // using user-provided _ssid, _pass in place of system-stored ssid amd pass + + // 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 { @@ -163,7 +164,16 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo } 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; + } } yield(); } @@ -185,8 +195,13 @@ int WiFiManager::connectWifi(String ssid, String pass) { DEBUG_WM(WiFi.localIP()); } - - WiFi.begin(ssid.c_str(), pass.c_str()); + if(ssid !="" && pass != "") { + WiFi.begin(ssid.c_str(), pass.c_str()); + } else { + DEBUG_WM("Using last saved values, should be faster"); + WiFi.begin(); + } + int connRes = WiFi.waitForConnectResult(); DEBUG_WM ("Connection result: "); DEBUG_WM ( connRes ); @@ -285,6 +300,9 @@ void WiFiManager::setMinimumSignalQuality(int quality) { _minimumQuality = quality; } +void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { + _shouldBreakAfterConfig = shouldBreak; +} /** Handle root or redirect to captive portal */ void WiFiManager::handleRoot() { diff --git a/WiFiManager.h b/WiFiManager.h index 35919e8..301ae36 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -92,6 +92,8 @@ class WiFiManager void setSaveConfigCallback( void (*func)(void) ); //adds a custom parameter void addParameter(WiFiManagerParameter *p); + //if this is set, it will exit after config, even if connection is unsucessful. + void setBreakAfterConfig(boolean shouldBreak); private: std::unique_ptr dnsServer; @@ -119,6 +121,7 @@ class WiFiManager IPAddress _sta_static_sn; int _paramsCount = 0; int _minimumQuality = -1; + boolean _shouldBreakAfterConfig = false; //String getEEPROMString(int start, int len); //void setEEPROMString(int start, int len, String string); diff --git a/examples/AutoConnectWithReset/AutoConnectWithReset.ino b/examples/AutoConnectWithReset/AutoConnectWithReset.ino new file mode 100644 index 0000000..5af3b1f --- /dev/null +++ b/examples/AutoConnectWithReset/AutoConnectWithReset.ino @@ -0,0 +1,49 @@ +#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 + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wifiManager; + + //exit after config instead of connecting + wifiManager.setBreakAfterConfig(true); + + //reset settings - for testing + //wifiManager.resetSettings(); + + + //tries to connect to last known settings + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" with password "password" + //and goes into a blocking loop awaiting configuration + if (!wifiManager.autoConnect("AutoConnectAP", "password")) { + Serial.println("failed to connect, we should reset as see if it connects"); + delay(3000); + ESP.reset(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + + + Serial.println("local ip"); + Serial.println(WiFi.localIP()); +} + +void loop() { + // put your main code here, to run repeatedly: + + +} diff --git a/keywords.txt b/keywords.txt index 79774cf..4a5d552 100644 --- a/keywords.txt +++ b/keywords.txt @@ -7,6 +7,7 @@ ####################################### WiFiManager KEYWORD1 +WiFiManagerParameter KEYWORD1 ####################################### @@ -15,12 +16,22 @@ WiFiManager KEYWORD1 autoConnect KEYWORD2 getSSID KEYWORD2 getPassword KEYWORD2 +getConfigPortalSSID KEYWORD2 resetSettings KEYWORD2 urldecode KEYWORD2 setTimeout KEYWORD2 setDebugOutput KEYWORD2 -setAPConfig KEYWORD2 +setMinimumSignalQuality KEYWORD2 +setAPStaticIPConfig KEYWORD2 +setSTAStaticIPConfig KEYWORD2 setAPCallback KEYWORD2 +setSaveConfigCallback KEYWORD2 +addParameter KEYWORD2 + +getID KEYWORD2 +getValue KEYWORD2 +getPlaceholder KEYWORD2 +getValueLength KEYWORD2 ####################################### # Constants (LITERAL1) From 6e65f398958feb05b23b869a60e7896fa9798620 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 25 Jan 2016 10:51:25 +0200 Subject: [PATCH 51/61] added rescan option added reset option added info page precomposed page for A LOT faster page sending --- WiFiManager.cpp | 102 +++++++++++++++++++++++-------- WiFiManager.h | 9 ++- extras/WiFiManager.template.html | 3 + 3 files changed, 85 insertions(+), 29 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 0819fb4..8762b74 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -91,6 +91,8 @@ void WiFiManager::setupConfigPortal() { server->on("/wifi", std::bind(&WiFiManager::handleWifi, this, true)); server->on("/0wifi", std::bind(&WiFiManager::handleWifi, this, false)); server->on("/wifisave", std::bind(&WiFiManager::handleWifiSave, this)); + server->on("/i", std::bind(&WiFiManager::handleInfo, this)); + server->on("/r", std::bind(&WiFiManager::handleReset, this)); server->on("/generate_204", std::bind(&WiFiManager::handle204, this)); //Android/Chrome OS captive portal check. server->on("/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)); @@ -311,31 +313,20 @@ void WiFiManager::handleRoot() { return; } - server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); - server->sendHeader("Pragma", "no-cache"); - server->sendHeader("Expires", "-1"); - server->setContentLength(CONTENT_LENGTH_UNKNOWN); - server->send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + String page = FPSTR(HTTP_HEAD); + page.replace("{v}", "Options"); + page += FPSTR(HTTP_SCRIPT); + page += FPSTR(HTTP_STYLE); + page += FPSTR(HTTP_HEAD_END); + page += "

"; + page += _apName; + page += "

"; + page += F("

WiFiManager

"); + page += FPSTR(HTTP_PORTAL_OPTIONS); + page += FPSTR(HTTP_END); + + server->send(200, "text/html", page); - String head = HTTP_HEAD; - head.replace("{v}", "Options"); - server->sendContent(head); - server->sendContent_P(HTTP_SCRIPT); - server->sendContent_P(HTTP_STYLE); - server->sendContent_P(HTTP_HEAD_END); - - //server->sendContent(F("

")); - String title = "

"; - title += _apName; - title += "

"; - server->sendContent(title); - server->sendContent(F("

WiFiManager

")); - - - server->sendContent_P(HTTP_PORTAL_OPTIONS); - server->sendContent_P(HTTP_END); - - server->client().stop(); // Stop is needed because we sent no content length } /** Wifi config page handler */ @@ -347,7 +338,7 @@ void WiFiManager::handleWifi(boolean scan) { server->send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. server->setContentLength(CONTENT_LENGTH_UNKNOWN); - String head = HTTP_HEAD; + String head = FPSTR(HTTP_HEAD); head.replace("{v}", "Config ESP"); server->sendContent(head); server->sendContent_P(HTTP_SCRIPT); @@ -446,6 +437,7 @@ void WiFiManager::handleWifi(boolean scan) { } server->sendContent_P(HTTP_FORM_END); + server->sendContent_P(HTTP_SCAN_LINK); server->sendContent_P(HTTP_END); server->client().stop(); @@ -496,7 +488,7 @@ void WiFiManager::handleWifiSave() { server->setContentLength(CONTENT_LENGTH_UNKNOWN); server->send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. - String head = HTTP_HEAD; + String head = FPSTR(HTTP_HEAD); head.replace("{v}", "Credentials Saved"); server->sendContent(head); server->sendContent_P(HTTP_SCRIPT); @@ -513,6 +505,64 @@ void WiFiManager::handleWifiSave() { connect = true; //signal ready to connect/reset } +/** Handle the info page */ +void WiFiManager::handleInfo() { + DEBUG_WM(F("Info")); + +String page = FPSTR(HTTP_HEAD); + page.replace("{v}", "Info"); + page += FPSTR(HTTP_SCRIPT); + page += FPSTR(HTTP_STYLE); + 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("
Flash Size
"); + page += ESP.getFlashChipSize(); + 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); + + 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 += FPSTR(HTTP_HEAD_END); + page += F("Module will reset in a few seconds."); + page += FPSTR(HTTP_END); + server->send(200, "text/html", page); + + DEBUG_WM(F("Sent reset page")); + delay(5000); + ESP.reset(); + delay(2000); +} + + + + void WiFiManager::handle204() { DEBUG_WM(F("204 No Response")); server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); diff --git a/WiFiManager.h b/WiFiManager.h index 301ae36..f849bf3 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -20,16 +20,17 @@ const char HTTP_200[] PROGMEM = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"; -//const char HTTP_HEAD[] PROGMEM = "{v}"; +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_PORTAL_OPTIONS[] PROGMEM = "



"; const char HTTP_ITEM[] PROGMEM = "
{v} {r}% {i}
"; const char HTTP_ITEM_PADLOCK[] PROGMEM = ""; 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 = "
"; @@ -102,7 +103,7 @@ class WiFiManager const int WM_DONE = 0; const int WM_WAIT = 10; - const String HTTP_HEAD = "{v}"; + //const String HTTP_HEAD = "{v}"; void setupConfigPortal(); @@ -132,6 +133,8 @@ class WiFiManager void handleRoot(); void handleWifi(boolean scan); void handleWifiSave(); + void handleInfo(); + void handleReset(); void handleNotFound(); void handle204(); boolean captivePortal(); diff --git a/extras/WiFiManager.template.html b/extras/WiFiManager.template.html index 5ef5924..4b1aeba 100644 --- a/extras/WiFiManager.template.html +++ b/extras/WiFiManager.template.html @@ -10,8 +10,11 @@
PMica 110%



+


+
+ Scan
\ No newline at end of file From 6217ef8e6a0ff2b908fd3b0bb47c49997ebf1000 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Fri, 29 Jan 2016 08:48:27 +0200 Subject: [PATCH 52/61] bump ver --- extras/WiFiManager.template.html | 4 ++-- library.json | 2 +- library.properties | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/extras/WiFiManager.template.html b/extras/WiFiManager.template.html index 4b1aeba..f76c846 100644 --- a/extras/WiFiManager.template.html +++ b/extras/WiFiManager.template.html @@ -1,5 +1,5 @@ {v} - +
{v} {r}% {i}
@@ -15,6 +15,6 @@


- Scan +
\ No newline at end of file diff --git a/library.json b/library.json index 43793ab..5af1b01 100644 --- a/library.json +++ b/library.json @@ -1,7 +1,7 @@ { "name": "WifiManager", "keywords": "wifi, wi-fi", - "description": "ESP8266 WiFi Connection manager with fallback web configuration portal", + "description": "ESP8266 WiFi Connection manager with fallback web configuration portal **USE version 0.6 together with stable 2.0.0 ESP8266 core for Arduino and use 0.7 for core 2.1.0.rc2 or newer**", "repository": { "type": "git", diff --git a/library.properties b/library.properties index c43b894..54ed280 100644 --- a/library.properties +++ b/library.properties @@ -1,9 +1,9 @@ name=WiFiManager -version=0.6 +version=0.7 author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal -paragraph=Library for configuring ESP8266 modules WiFi credentials at runtime. +paragraph=Library for configuring ESP8266 modules WiFi credentials at runtime. **USE version 0.6 together with stable 2.0.0 ESP8266 core for Arduino and use 0.7 for core 2.1.0.rc2 or newer** category=Communication url=https://github.com/tzapu/WiFiManager.git architectures=esp8266 From ba1aa5496d899950e3a8df9b249fa0deb09f30d7 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Mon, 1 Feb 2016 12:34:29 +0200 Subject: [PATCH 53/61] added more examples, updated readme made it compile on older versions --- README.md | 22 ++++-- WiFiManager.cpp | 54 +++++++------ WiFiManager.h | 11 ++- .../AutoConnectWithStaticIP.ino | 75 +++++++++++++++++++ library.json | 2 +- library.properties | 2 +- 6 files changed, 135 insertions(+), 31 deletions(-) create mode 100644 examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino diff --git a/README.md b/README.md index 91ad77a..93bcaae 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - ~~add ability to configure more parameters than ssid/password~~ - ~~maybe allow setting ip of ESP after reboot~~ - ~~add to Arduino Boards Manager~~ -- add to PlatformIO +- ~~add to PlatformIO~~ - add multiple sets of network credentials - allow users to customize CSS @@ -58,7 +58,7 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are You can either install through the Arduino Boards Manager or checkout the latest changes or a release from github #### Install through Boards Manager -__Currently version 0.6 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.0.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) @@ -68,7 +68,7 @@ __Currently version 0.6 works with release 2.0.0 or newer of the [ESP8266 core f - click Install and start [using it](#using) #### Checkout from github -__Github version works with the HEAD (as of 18 jan 2016) or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ +__Github version works with release 2.0.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ - Checkout library to your Arduino libraries folder ### Using @@ -131,7 +131,7 @@ void configModeCallback (WiFiManager *myWiFiManager) { ``` ##### Save settings -This gets called when custom parameters have been set **AND** a connection has been established. Use it to set a flag, so when all the configuration finishes, you can save the extra parameters somewhere. +This gets called when custom parameters have been set **AND** a connection has been established. Use it to set a flag, so when all the configuration finishes, you can save the extra parameters somewhere. See [AutoConnectWithFSParameters Example](https://github.com/tzapu/WiFiManager/tree/master/examples/AutoConnectWithFSParameters). ```cpp @@ -229,6 +229,8 @@ wifiManager.setDebugOutput(false); ## Troubleshooting If you get compilation errors, more often than not, you may need to install a newer version of the ESP8266 core for Arduino. +Changes added on 0.8 should make the latest trunk work without compilation errors. Tested down to ESP8266 core 2.0.0. **Please update to version 0.8** + I am trying to keep releases working with release versions of the core, so they can be installed through boards manager, but if you checkout the latest version directly from github, sometimes, the library will only work if you update the ESP8266 core to the latest version because I am using some newly added function. @@ -236,7 +238,17 @@ If you connect to the created configuration Access Point but the configuration p ## Releases -#### 0.6 +#### 0.8 + - made it compile on older versions of ESP8266 core as well, tested down to 2.0.0 + - added simple example for Custom IP + +##### 0.7 + - added static IP in station mode + - added example of persisting custom IP to FS config.json + - more option on portal homepage + - added on PlatformIO + +##### 0.6 - custom parameters - prettier - on demand config portal diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 8762b74..29da023 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -16,7 +16,7 @@ WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placehold _id = id; _placeholder = placeholder; _length = length; - _value = new char[length+1]; + _value = new char[length + 1]; for (int i = 0; i < length; i++) { _value[i] = 0; } @@ -98,6 +98,11 @@ void WiFiManager::setupConfigPortal() { server->onNotFound (std::bind(&WiFiManager::handleNotFound, this)); server->begin(); // Web server start DEBUG_WM(F("HTTP server started")); + /* + String ip = "10.1.2.3"; + optionalIPFromString(&_sta_static_ip, ip.c_str()); + DEBUG_WM(_sta_static_ip);*/ + } boolean WiFiManager::autoConnect() { @@ -152,7 +157,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo 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.")); @@ -166,8 +171,8 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo } break; } - - if(_shouldBreakAfterConfig) { + + 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) { @@ -197,13 +202,14 @@ int WiFiManager::connectWifi(String ssid, String pass) { DEBUG_WM(WiFi.localIP()); } - if(ssid !="" && pass != "") { + //check if we have ssid and pass and force those, if not, try with last saved values + if (ssid != "" && pass != "") { WiFi.begin(ssid.c_str(), pass.c_str()); } else { DEBUG_WM("Using last saved values, should be faster"); WiFi.begin(); } - + int connRes = WiFi.waitForConnectResult(); DEBUG_WM ("Connection result: "); DEBUG_WM ( connRes ); @@ -273,7 +279,7 @@ String WiFiManager::urldecode(const char *src) void WiFiManager::resetSettings() { DEBUG_WM(F("settings invalidated")); - DEBUG_WM(F("THIS MAY CAUSE AP NOT TO STRT UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA.")); + 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); //delay(200); } @@ -324,7 +330,7 @@ void WiFiManager::handleRoot() { page += F("

WiFiManager

"); page += FPSTR(HTTP_PORTAL_OPTIONS); page += FPSTR(HTTP_END); - + server->send(200, "text/html", page); } @@ -404,8 +410,8 @@ void WiFiManager::handleWifi(boolean scan) { server->sendContent_P("
"); } - if(_sta_static_ip) { - + if (_sta_static_ip) { + String item = FPSTR(HTTP_FORM_PARAM); item.replace("{i}", "ip"); item.replace("{n}", "ip"); @@ -413,8 +419,8 @@ void WiFiManager::handleWifi(boolean scan) { item.replace("{l}", "15"); item.replace("{v}", _sta_static_ip.toString()); - server->sendContent(item); - + server->sendContent(item); + item = FPSTR(HTTP_FORM_PARAM); item.replace("{i}", "gw"); item.replace("{n}", "gw"); @@ -423,7 +429,7 @@ void WiFiManager::handleWifi(boolean scan) { item.replace("{v}", _sta_static_gw.toString()); server->sendContent(item); - + item = FPSTR(HTTP_FORM_PARAM); item.replace("{i}", "sn"); item.replace("{n}", "sn"); @@ -431,7 +437,7 @@ void WiFiManager::handleWifi(boolean scan) { item.replace("{l}", "15"); item.replace("{v}", _sta_static_sn.toString()); - server->sendContent(item); + server->sendContent(item); server->sendContent_P("
"); } @@ -466,20 +472,24 @@ void WiFiManager::handleWifiSave() { DEBUG_WM(value); } - if(server->arg("ip") != "") { + if (server->arg("ip") != "") { DEBUG_WM(F("static ip")); DEBUG_WM(server->arg("ip")); - _sta_static_ip.fromString(server->arg("ip")); + //_sta_static_ip.fromString(server->arg("ip")); + String ip = server->arg("ip"); + optionalIPFromString(&_sta_static_ip, ip.c_str()); } - if(server->arg("gw") != "") { + if (server->arg("gw") != "") { DEBUG_WM(F("static gateway")); DEBUG_WM(server->arg("gw")); - _sta_static_gw.fromString(server->arg("gw")); + String gw = server->arg("gw"); + optionalIPFromString(&_sta_static_gw, gw.c_str()); } - if(server->arg("sn") != "") { + if (server->arg("sn") != "") { DEBUG_WM(F("static netmask")); DEBUG_WM(server->arg("sn")); - _sta_static_sn.fromString(server->arg("sn")); + String sn = server->arg("sn"); + optionalIPFromString(&_sta_static_sn, sn.c_str()); } server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); @@ -509,7 +519,7 @@ void WiFiManager::handleWifiSave() { void WiFiManager::handleInfo() { DEBUG_WM(F("Info")); -String page = FPSTR(HTTP_HEAD); + String page = FPSTR(HTTP_HEAD); page.replace("{v}", "Info"); page += FPSTR(HTTP_SCRIPT); page += FPSTR(HTTP_STYLE); @@ -535,7 +545,7 @@ String page = FPSTR(HTTP_HEAD); page += F(""); page += F(""); page += FPSTR(HTTP_END); - + server->send(200, "text/html", page); DEBUG_WM(F("Sent info page")); diff --git a/WiFiManager.h b/WiFiManager.h index f849bf3..cd6a8a6 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -157,8 +157,15 @@ class WiFiManager template void DEBUG_WM(Generic text); + + 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."); + return false; + } }; - - #endif diff --git a/examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino b/examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino new file mode 100644 index 0000000..af343cd --- /dev/null +++ b/examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino @@ -0,0 +1,75 @@ +#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 + + +/************************************************************************************** + * this example shows how to set a static IP configuration for the ESP + * although the IP shows in the config portal, the changes will revert + * to the IP set in the source file. + * 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"; +//char static_sn[16] = "255.255.255.0"; + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wifiManager; + + //reset settings - for testing + //wifiManager.resetSettings(); + + //set static ip + //the commented bit only works for ESP8266 core 2.1.0 or newer + /*IPAddress _ip,_gw,_sn; + _ip.fromString(static_ip); + _gw.fromString(static_gw); + _sn.fromString(static_sn); +*/ + IPAddress _ip = IPAddress(10, 0, 1, 78); + IPAddress _gw = IPAddress(10, 0, 1, 1); + IPAddress _sn = IPAddress(255, 255, 255, 0); + + wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); + + + //tries to connect to last known settings + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" with password "password" + //and goes into a blocking loop awaiting configuration + if (!wifiManager.autoConnect("AutoConnectAP", "password")) { + Serial.println("failed to connect, we should reset as see if it connects"); + delay(3000); + ESP.reset(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + + + Serial.println("local ip"); + Serial.println(WiFi.localIP()); +} + +void loop() { + // put your main code here, to run repeatedly: + + +} diff --git a/library.json b/library.json index 5af1b01..72170c5 100644 --- a/library.json +++ b/library.json @@ -9,5 +9,5 @@ }, "frameworks": "arduino", "platforms": "espressif", - "version": "0.6" + "version": "0.8" } diff --git a/library.properties b/library.properties index 54ed280..ee09442 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=WiFiManager -version=0.7 +version=0.8 author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal From 0f75d745feafdcd2f3ac26f2d3ceba02a6f1bb60 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Thu, 4 Feb 2016 14:38:48 +0200 Subject: [PATCH 54/61] 0.9 fixed encoding problems --- README.md | 5 +++- WiFiManager.cpp | 64 +++++++++++++--------------------------------- WiFiManager.h | 32 ++++++++++++----------- library.json | 2 +- library.properties | 2 +- 5 files changed, 41 insertions(+), 64 deletions(-) diff --git a/README.md b/README.md index 93bcaae..3c8b9b1 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,10 @@ If you connect to the created configuration Access Point but the configuration p ## Releases -#### 0.8 +#### 0.9 + - fixed support for encoded characters in ssid/pass + +##### 0.8 - made it compile on older versions of ESP8266 core as well, tested down to 2.0.0 - added simple example for Custom IP diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 29da023..12a36ca 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -98,10 +98,6 @@ void WiFiManager::setupConfigPortal() { server->onNotFound (std::bind(&WiFiManager::handleNotFound, this)); server->begin(); // Web server start DEBUG_WM(F("HTTP server started")); - /* - String ip = "10.1.2.3"; - optionalIPFromString(&_sta_static_ip, ip.c_str()); - DEBUG_WM(_sta_static_ip);*/ } @@ -134,6 +130,7 @@ boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { //setup AP WiFi.mode(WIFI_AP); + DEBUG_WM("SET AP"); _apName = apName; _apPassword = apPassword; @@ -203,7 +200,7 @@ int WiFiManager::connectWifi(String ssid, String pass) { } //check if we have ssid and pass and force those, if not, try with last saved values - if (ssid != "" && pass != "") { + if (ssid != "") { WiFi.begin(ssid.c_str(), pass.c_str()); } else { DEBUG_WM("Using last saved values, should be faster"); @@ -213,10 +210,21 @@ int WiFiManager::connectWifi(String ssid, String pass) { int connRes = WiFi.waitForConnectResult(); DEBUG_WM ("Connection result: "); DEBUG_WM ( connRes ); + //not connected, WPS enabled, no pass - first attempt + if (_tryWPS && connRes != WL_CONNECTED && pass == "") { + startWPS(); + //should be connected at the end of WPS + connRes = WiFi.waitForConnectResult(); + } return connRes; } - +void WiFiManager::startWPS() { + DEBUG_WM("START WPS"); + WiFi.beginWPSConfig(); + DEBUG_WM("END WPS"); +} +/* String WiFiManager::getSSID() { if (_ssid == "") { DEBUG_WM(F("Reading SSID")); @@ -236,47 +244,11 @@ String WiFiManager::getPassword() { } return _pass; } - +*/ String WiFiManager::getConfigPortalSSID() { return _apName; } -String WiFiManager::urldecode(const char *src) -{ - String decoded = ""; - char a, b; - while (*src) { - if ((*src == '%') && - ((a = src[1]) && (b = src[2])) && - (isxdigit(a) && isxdigit(b))) { - if (a >= 'a') - a -= 'a' - 'A'; - if (a >= 'A') - a -= ('A' - 10); - else - a -= '0'; - if (b >= 'a') - b -= 'a' - 'A'; - if (b >= 'A') - b -= ('A' - 10); - else - b -= '0'; - - decoded += char(16 * a + b); - src += 3; - } else if (*src == '+') { - decoded += ' '; - *src++; - } else { - decoded += *src; - *src++; - } - } - decoded += '\0'; - - return decoded; -} - 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.")); @@ -455,8 +427,8 @@ void WiFiManager::handleWifiSave() { DEBUG_WM(F("WiFi save")); //SAVE/connect here - _ssid = urldecode(server->arg("s").c_str()); - _pass = urldecode(server->arg("p").c_str()); + _ssid = server->arg("s").c_str(); + _pass = server->arg("p").c_str(); //parameters for (int i = 0; i < _paramsCount; i++) { @@ -464,7 +436,7 @@ void WiFiManager::handleWifiSave() { break; } //read parameter - String value = urldecode(server->arg(_params[i]->getID()).c_str()); + String value = server->arg(_params[i]->getID()).c_str(); //store it in array value.toCharArray(_params[i]->_value, _params[i]->_length); DEBUG_WM(F("Parameter")); diff --git a/WiFiManager.h b/WiFiManager.h index cd6a8a6..24d037f 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -66,15 +66,13 @@ class WiFiManager //if you want to always start the config portal, without trying to connect first boolean startConfigPortal(char const *apName, char const *apPassword = NULL); - String getSSID(); - String getPassword(); + //String getSSID(); + //String getPassword(); // get the AP name of the config portal, so it can be used in the callback String getConfigPortalSSID(); void resetSettings(); - //for convenience - String urldecode(const char*); //sets timeout before webserver loop ends and exits even if there has been no setup. //usefully for devices that failed to connect at some point and got stuck in a webserver loop @@ -95,34 +93,38 @@ class WiFiManager void addParameter(WiFiManagerParameter *p); //if this is set, it will exit after config, even if connection is unsucessful. void setBreakAfterConfig(boolean shouldBreak); + //if this is set, try WPS setup when starting (this will delay config portal for up to 2 mins) private: std::unique_ptr dnsServer; std::unique_ptr server; - const int WM_DONE = 0; - const int WM_WAIT = 10; + //const int WM_DONE = 0; + //const int WM_WAIT = 10; //const String HTTP_HEAD = "{v}"; void setupConfigPortal(); + void startWPS(); - int _eepromStart; - const char* _apName = "no-net"; - const char* _apPassword = NULL; - String _ssid = ""; - String _pass = ""; - unsigned long timeout = 0; - unsigned long start = 0; + const char* _apName = "no-net"; + const char* _apPassword = NULL; + String _ssid = ""; + String _pass = ""; + unsigned long timeout = 0; + unsigned long start = 0; + IPAddress _ap_static_ip; IPAddress _ap_static_gw; IPAddress _ap_static_sn; IPAddress _sta_static_ip; IPAddress _sta_static_gw; IPAddress _sta_static_sn; - int _paramsCount = 0; - int _minimumQuality = -1; + + int _paramsCount = 0; + int _minimumQuality = -1; boolean _shouldBreakAfterConfig = false; + boolean _tryWPS = false; //String getEEPROMString(int start, int len); //void setEEPROMString(int start, int len, String string); diff --git a/library.json b/library.json index 72170c5..7853b91 100644 --- a/library.json +++ b/library.json @@ -9,5 +9,5 @@ }, "frameworks": "arduino", "platforms": "espressif", - "version": "0.8" + "version": "0.9" } diff --git a/library.properties b/library.properties index ee09442..eda57aa 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=WiFiManager -version=0.8 +version=0.9 author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal From 55c751c133285aba0e5826d14d9ecbf23a85fff5 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Sun, 7 Feb 2016 12:51:32 +0200 Subject: [PATCH 55/61] removed some warnings --- library.json | 2 +- library.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/library.json b/library.json index 7853b91..8f8b24d 100644 --- a/library.json +++ b/library.json @@ -1,7 +1,7 @@ { "name": "WifiManager", "keywords": "wifi, wi-fi", - "description": "ESP8266 WiFi Connection manager with fallback web configuration portal **USE version 0.6 together with stable 2.0.0 ESP8266 core for Arduino and use 0.7 for core 2.1.0.rc2 or newer**", + "description": "ESP8266 WiFi Connection manager with fallback web configuration portal", "repository": { "type": "git", diff --git a/library.properties b/library.properties index eda57aa..e656e67 100644 --- a/library.properties +++ b/library.properties @@ -3,7 +3,7 @@ version=0.9 author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal -paragraph=Library for configuring ESP8266 modules WiFi credentials at runtime. **USE version 0.6 together with stable 2.0.0 ESP8266 core for Arduino and use 0.7 for core 2.1.0.rc2 or newer** +paragraph=Library for configuring ESP8266 modules WiFi credentials at runtime. category=Communication url=https://github.com/tzapu/WiFiManager.git architectures=esp8266 From 7b23c892047671792d95120ff5f7e7a4ebad1938 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Tue, 9 Feb 2016 08:58:35 +0200 Subject: [PATCH 56/61] fixed library manager name --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 3c8b9b1..8303df5 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - [Wishlist](#wishlist) - [Quick start](#quick-start) - Installing - - [Through Boards Manager](#install-through-boards-manager) + - [Through Library Manager](#install-through-library-manager) - [From Github](#checkout-from-github) - [Using](#using) - [Documentation](#documentation) @@ -47,7 +47,7 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - if timeout is set, extend it when a page is fetched in AP mode - ~~add ability to configure more parameters than ssid/password~~ - ~~maybe allow setting ip of ESP after reboot~~ -- ~~add to Arduino Boards Manager~~ +- ~~add to Arduino Library Manager~~ - ~~add to PlatformIO~~ - add multiple sets of network credentials - allow users to customize CSS @@ -55,9 +55,9 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are ## Quick Start ### Installing -You can either install through the Arduino Boards Manager or checkout the latest changes or a release from github +You can either install through the Arduino Library Manager or checkout the latest changes or a release from github -#### Install through Boards Manager +#### 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)__ - in Arduino IDE got to Sketch/Include Library/Manage Libraries ![Manage Libraries](http://i.imgur.com/9BkEBkR.png) @@ -240,7 +240,7 @@ If you connect to the created configuration Access Point but the configuration p ## Releases #### 0.9 - fixed support for encoded characters in ssid/pass - + ##### 0.8 - made it compile on older versions of ESP8266 core as well, tested down to 2.0.0 - added simple example for Custom IP From 6f0c16d74fec7e91d3c567371a9a2ef5382f975e Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Sun, 14 Feb 2016 15:04:20 +0200 Subject: [PATCH 57/61] added flash chip real size to info page --- WiFiManager.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 12a36ca..1cf4f70 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -503,9 +503,12 @@ void WiFiManager::handleInfo() { page += F("
Flash Chip ID
"); page += ESP.getFlashChipId(); page += F("
"); - page += F("
Flash Size
"); + 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("
"); From 3f617c745524ee207cdfebbd3f959272b85b7e7c Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Sun, 14 Feb 2016 15:46:01 +0200 Subject: [PATCH 58/61] fixed all pages so they don t return unknown content length, much faster now --- WiFiManager.cpp | 80 +++++++++++++++++++++---------------------------- 1 file changed, 34 insertions(+), 46 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 1cf4f70..127c9d3 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -225,7 +225,7 @@ void WiFiManager::startWPS() { DEBUG_WM("END WPS"); } /* -String WiFiManager::getSSID() { + String WiFiManager::getSSID() { if (_ssid == "") { DEBUG_WM(F("Reading SSID")); _ssid = WiFi.SSID(); @@ -233,9 +233,9 @@ String WiFiManager::getSSID() { DEBUG_WM(_ssid); } return _ssid; -} + } -String WiFiManager::getPassword() { + String WiFiManager::getPassword() { if (_pass == "") { DEBUG_WM(F("Reading Password")); _pass = WiFi.psk(); @@ -243,7 +243,7 @@ String WiFiManager::getPassword() { //DEBUG_WM(_pass); } return _pass; -} + } */ String WiFiManager::getConfigPortalSSID() { return _apName; @@ -309,26 +309,19 @@ void WiFiManager::handleRoot() { /** Wifi config page handler */ void WiFiManager::handleWifi(boolean scan) { - server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); - server->sendHeader("Pragma", "no-cache"); - server->sendHeader("Expires", "-1"); - server->setContentLength(CONTENT_LENGTH_UNKNOWN); - server->send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. - server->setContentLength(CONTENT_LENGTH_UNKNOWN); - String head = FPSTR(HTTP_HEAD); - head.replace("{v}", "Config ESP"); - server->sendContent(head); - server->sendContent_P(HTTP_SCRIPT); - server->sendContent_P(HTTP_STYLE); - server->sendContent_P(HTTP_HEAD_END); + String page = FPSTR(HTTP_HEAD); + page.replace("{v}", "Config ESP"); + page += FPSTR(HTTP_SCRIPT); + page += FPSTR(HTTP_STYLE); + page += FPSTR(HTTP_HEAD_END); if (scan) { int n = WiFi.scanNetworks(); DEBUG_WM(F("Scan done")); if (n == 0) { DEBUG_WM(F("No networks found")); - server->sendContent("No networks found. Refresh to scan again."); + page += F("No networks found. Refresh to scan again."); } else { for (int i = 0; i < n; ++i) @@ -349,18 +342,18 @@ void WiFiManager::handleWifi(boolean scan) { item.replace("{i}", ""); } //DEBUG_WM(item); - server->sendContent(item); + page += item; delay(0); } else { DEBUG_WM(F("Skipping due to quality")); } } - server->sendContent("
"); + page += "
"; } } - server->sendContent_P(HTTP_FORM_START); + page += FPSTR(HTTP_FORM_START); char parLength[2]; // add the extra parameters to the form for (int i = 0; i < _paramsCount; i++) { @@ -376,10 +369,10 @@ void WiFiManager::handleWifi(boolean scan) { pitem.replace("{l}", parLength); pitem.replace("{v}", _params[i]->getValue()); - server->sendContent(pitem); + page += pitem; } if (_params[0] != NULL) { - server->sendContent_P("
"); + page += "
"; } if (_sta_static_ip) { @@ -391,7 +384,7 @@ void WiFiManager::handleWifi(boolean scan) { item.replace("{l}", "15"); item.replace("{v}", _sta_static_ip.toString()); - server->sendContent(item); + page += item; item = FPSTR(HTTP_FORM_PARAM); item.replace("{i}", "gw"); @@ -400,7 +393,7 @@ void WiFiManager::handleWifi(boolean scan) { item.replace("{l}", "15"); item.replace("{v}", _sta_static_gw.toString()); - server->sendContent(item); + page += item; item = FPSTR(HTTP_FORM_PARAM); item.replace("{i}", "sn"); @@ -409,15 +402,18 @@ void WiFiManager::handleWifi(boolean scan) { item.replace("{l}", "15"); item.replace("{v}", _sta_static_sn.toString()); - server->sendContent(item); + page += item; - server->sendContent_P("
"); + page += "
"; } - server->sendContent_P(HTTP_FORM_END); - server->sendContent_P(HTTP_SCAN_LINK); - server->sendContent_P(HTTP_END); - server->client().stop(); + page += FPSTR(HTTP_FORM_END); + page += FPSTR(HTTP_SCAN_LINK); + + page += FPSTR(HTTP_END); + + server->send(200, "text/html", page); + DEBUG_WM(F("Sent config page")); } @@ -464,23 +460,15 @@ void WiFiManager::handleWifiSave() { optionalIPFromString(&_sta_static_sn, sn.c_str()); } - server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); - server->sendHeader("Pragma", "no-cache"); - server->sendHeader("Expires", "-1"); - server->setContentLength(CONTENT_LENGTH_UNKNOWN); - server->send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + String page = FPSTR(HTTP_HEAD); + page.replace("{v}", "Credentials Saved"); + page += FPSTR(HTTP_SCRIPT); + page += FPSTR(HTTP_STYLE); + page += FPSTR(HTTP_HEAD_END); + page += FPSTR(HTTP_SAVED); + page += FPSTR(HTTP_END); - String head = FPSTR(HTTP_HEAD); - head.replace("{v}", "Credentials Saved"); - server->sendContent(head); - server->sendContent_P(HTTP_SCRIPT); - server->sendContent_P(HTTP_STYLE); - server->sendContent_P(HTTP_HEAD_END); - - server->sendContent_P(HTTP_SAVED); - - server->sendContent_P(HTTP_END); - server->client().stop(); + server->send(200, "text/html", page); DEBUG_WM(F("Sent wifi save page")); From 9cde9a81706fb0d333a6c7173a9162005e5ed804 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Tue, 16 Feb 2016 11:17:34 +0200 Subject: [PATCH 59/61] added a new version of wait for connect result added setConnectTimeout renamed setTimeout to setConfigPortalTimeout --- WiFiManager.cpp | 42 ++++++++++++++++++++++++++++++++++++------ WiFiManager.h | 19 ++++++++++++------- 2 files changed, 48 insertions(+), 13 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 127c9d3..1b08301 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -53,7 +53,7 @@ void WiFiManager::setupConfigPortal() { server.reset(new ESP8266WebServer(80)); DEBUG_WM(F("")); - start = millis(); + _configPortalStart = millis(); DEBUG_WM(F("Configuring access point... ")); DEBUG_WM(_apName); @@ -143,7 +143,7 @@ boolean WiFiManager::startConfigPortal(char const *apName, char const *apPasswo connect = false; setupConfigPortal(); - while (timeout == 0 || millis() < start + timeout) { + while (_configPortalTimeout == 0 || millis() < _configPortalStart + _configPortalTimeout) { //DNS dnsServer->processNextRequest(); //HTTP @@ -207,18 +207,41 @@ int WiFiManager::connectWifi(String ssid, String pass) { WiFi.begin(); } - int connRes = WiFi.waitForConnectResult(); + int connRes = waitForConnectResult(); DEBUG_WM ("Connection result: "); DEBUG_WM ( connRes ); //not connected, WPS enabled, no pass - first attempt if (_tryWPS && connRes != WL_CONNECTED && pass == "") { startWPS(); //should be connected at the end of WPS - connRes = WiFi.waitForConnectResult(); + connRes = waitForConnectResult(); } return connRes; } +uint8_t WiFiManager::waitForConnectResult() { + if (_connectTimeout == 0) { + return WiFi.waitForConnectResult(); + } else { + DEBUG_WM (F("Waiting for connection result with timed 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; + } +} + void WiFiManager::startWPS() { DEBUG_WM("START WPS"); WiFi.beginWPSConfig(); @@ -255,9 +278,16 @@ void WiFiManager::resetSettings() { WiFi.disconnect(true); //delay(200); } - void WiFiManager::setTimeout(unsigned long seconds) { - timeout = seconds * 1000; + 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) { diff --git a/WiFiManager.h b/WiFiManager.h index 24d037f..0e0da98 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -66,9 +66,6 @@ class WiFiManager //if you want to always start the config portal, without trying to connect first boolean startConfigPortal(char const *apName, char const *apPassword = NULL); - //String getSSID(); - //String getPassword(); - // get the AP name of the config portal, so it can be used in the callback String getConfigPortalSSID(); @@ -76,8 +73,14 @@ class WiFiManager //sets timeout before webserver loop ends and exits even if there has been no setup. //usefully for devices that failed to connect at some point and got stuck in a webserver loop - //in seconds + //in seconds setConfigPortalTimeout is a new name for setTimeout + void setConfigPortalTimeout(unsigned long seconds); void setTimeout(unsigned long seconds); + + //sets timeout for which to attempt connecting, usefull if you get a lot of failed connects + void setConnectTimeout(unsigned long seconds); + + void setDebugOutput(boolean debug); //defaults to not showing anything under 8% signal quality if called void setMinimumSignalQuality(int quality = 8); @@ -111,8 +114,9 @@ class WiFiManager const char* _apPassword = NULL; String _ssid = ""; String _pass = ""; - unsigned long timeout = 0; - unsigned long start = 0; + unsigned long _configPortalTimeout = 0; + unsigned long _connectTimeout = 0; + unsigned long _configPortalStart = 0; IPAddress _ap_static_ip; IPAddress _ap_static_gw; @@ -131,6 +135,7 @@ class WiFiManager int status = WL_IDLE_STATUS; int connectWifi(String ssid, String pass); + uint8_t waitForConnectResult(); void handleRoot(); void handleWifi(boolean scan); @@ -140,7 +145,7 @@ class WiFiManager void handleNotFound(); void handle204(); boolean captivePortal(); - + // DNS server const byte DNS_PORT = 53; From f82141c98c18cb01b2effb73958056f36c07fd74 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Tue, 16 Feb 2016 14:46:18 +0200 Subject: [PATCH 60/61] changed styling --- WiFiManager.cpp | 4 ++-- WiFiManager.h | 10 +++++----- extras/WiFiManager.template.html | 24 +++++++++++++++++++++--- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 1b08301..10b8dc0 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -223,7 +223,7 @@ uint8_t WiFiManager::waitForConnectResult() { if (_connectTimeout == 0) { return WiFi.waitForConnectResult(); } else { - DEBUG_WM (F("Waiting for connection result with timed out")); + DEBUG_WM (F("Waiting for connection result with time out")); unsigned long start = millis(); boolean keepConnecting = true; uint8_t status; @@ -367,7 +367,7 @@ void WiFiManager::handleWifi(boolean scan) { item.replace("{v}", WiFi.SSID(i)); item.replace("{r}", rssiQ); if (WiFi.encryptionType(i) != ENC_TYPE_NONE) { - item.replace("{i}", FPSTR(HTTP_ITEM_PADLOCK)); + item.replace("{i}", "l"); } else { item.replace("{i}", ""); } diff --git a/WiFiManager.h b/WiFiManager.h index 0e0da98..512d51f 100644 --- a/WiFiManager.h +++ b/WiFiManager.h @@ -21,16 +21,16 @@ const char HTTP_200[] PROGMEM = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"; const char HTTP_HEAD[] PROGMEM = "{v}"; -const char HTTP_STYLE[] PROGMEM = ""; +const char HTTP_STYLE[] PROGMEM = ""; const char HTTP_SCRIPT[] PROGMEM = ""; -const char HTTP_HEAD_END[] PROGMEM = "
"; +const char HTTP_HEAD_END[] PROGMEM = "
"; const char HTTP_PORTAL_OPTIONS[] PROGMEM = "



"; -const char HTTP_ITEM[] PROGMEM = "
{v} {r}% {i}
"; -const char HTTP_ITEM_PADLOCK[] PROGMEM = ""; +const char HTTP_ITEM[] PROGMEM = "
{v} {r}%
"; +//const char HTTP_ITEM_PADLOCK[] PROGMEM = ""; 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_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 = "
"; diff --git a/extras/WiFiManager.template.html b/extras/WiFiManager.template.html index f76c846..0cf8604 100644 --- a/extras/WiFiManager.template.html +++ b/extras/WiFiManager.template.html @@ -1,14 +1,32 @@ {v} - + + -
+
+ + + + +
{v} {r}%
+
PMisa 100%
+ +
PMisa 8%
+ + +
+ +




From 2582dd8735a6e9f517deb0e334bfe15771b97394 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Tue, 16 Feb 2016 18:24:12 +0200 Subject: [PATCH 61/61] version 0.10 ordered networks based on signal quality --- README.md | 6 +++--- WiFiManager.cpp | 35 ++++++++++++++++++++++++++--------- keywords.txt | 5 ++--- library.json | 2 +- library.properties | 2 +- 5 files changed, 33 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 8303df5..62707b1 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ First attempt at a library. Lots more changes and fixes to do. Contributions are - [Documentation](#documentation) - [Access Point Password](#password-protect-the-configuration-access-point) - [Callbacks](#callbacks) - - [Timeout](#timeout) + - [Configuration Portal Timeout](#configuration-portal-timeout) - [On Demand Configuration](#on-demand-configuration-portal) - [Custom Parameters](#custom-parameters) - [Custom IP Configuration](#custom-ip-configuration) @@ -149,10 +149,10 @@ void saveConfigCallback () { } ``` -#### Timeout +#### Configuration Portal Timeout If you need to set a timeout so the ESP doesn't hang waiting to be configured, for instance after a power failure, you can add ```cpp -wifiManager.setTimeout(180); +wifiManager.setConfigPortalTimeout(180); ``` which will wait 3 minutes (180 seconds). When the time passes, the autoConnect function will return, no matter the outcome. Check for connection and if it's still not established do whatever is needed (on some modules I restart them to retry, on others I enter deep sleep) diff --git a/WiFiManager.cpp b/WiFiManager.cpp index 10b8dc0..45ffb9f 100644 --- a/WiFiManager.cpp +++ b/WiFiManager.cpp @@ -352,21 +352,38 @@ void WiFiManager::handleWifi(boolean scan) { if (n == 0) { DEBUG_WM(F("No networks found")); page += F("No networks found. Refresh to scan again."); - } - else { - for (int i = 0; i < n; ++i) - { - DEBUG_WM(WiFi.SSID(i)); - DEBUG_WM(WiFi.RSSI(i)); - int quality = getRSSIasQuality(WiFi.RSSI(i)); + } else { + //sort networks + int indices[n]; + + for (int i = 0; i < n; i++) { + indices[i] = i; + } + + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) { + //int temp = indices[j]; + //indices[j] = indices[i]; + //indices[i] = temp; + std::swap(indices[i], indices[j]); + } + } + } + + //display networks in page + for (int i = 0; i < n; i++) { + 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(i)); + item.replace("{v}", WiFi.SSID(indices[i])); item.replace("{r}", rssiQ); - if (WiFi.encryptionType(i) != ENC_TYPE_NONE) { + if (WiFi.encryptionType(indices[i]) != ENC_TYPE_NONE) { item.replace("{i}", "l"); } else { item.replace("{i}", ""); diff --git a/keywords.txt b/keywords.txt index 4a5d552..7159e74 100644 --- a/keywords.txt +++ b/keywords.txt @@ -18,8 +18,8 @@ getSSID KEYWORD2 getPassword KEYWORD2 getConfigPortalSSID KEYWORD2 resetSettings KEYWORD2 -urldecode KEYWORD2 -setTimeout KEYWORD2 +setConfigPortalTimeout KEYWORD2 +setConnectTimeout KEYWORD2 setDebugOutput KEYWORD2 setMinimumSignalQuality KEYWORD2 setAPStaticIPConfig KEYWORD2 @@ -27,7 +27,6 @@ setSTAStaticIPConfig KEYWORD2 setAPCallback KEYWORD2 setSaveConfigCallback KEYWORD2 addParameter KEYWORD2 - getID KEYWORD2 getValue KEYWORD2 getPlaceholder KEYWORD2 diff --git a/library.json b/library.json index 8f8b24d..5c36330 100644 --- a/library.json +++ b/library.json @@ -9,5 +9,5 @@ }, "frameworks": "arduino", "platforms": "espressif", - "version": "0.9" + "version": "0.10" } diff --git a/library.properties b/library.properties index e656e67..d22ee1d 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=WiFiManager -version=0.9 +version=0.10 author=tzapu maintainer=tzapu sentence=ESP8266 WiFi Connection manager with fallback web configuration portal