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 1/6] 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 2/6] 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 3/6] 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 4/6] 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 ab5902e27342d4718f337e9c2b2b8ac241417680 Mon Sep 17 00:00:00 2001 From: Alex Tudorache Date: Fri, 8 Jan 2016 11:44:50 +0200 Subject: [PATCH 5/6] 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 6/6] 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() {