From e361cdfd421b4c4354008988aad217eacf406a19 Mon Sep 17 00:00:00 2001 From: Maarten Claes Date: Fri, 14 Aug 2020 16:00:58 +0200 Subject: [PATCH 1/5] Working on esp32 --- lib/MQTT/HomeAssistantDiscoveryClient.cpp | 8 +- lib/MQTT/MqttClient.cpp | 3 +- lib/MiLightState/GroupStatePersistence.cpp | 1 + lib/Settings/AboutHelper.cpp | 7 +- lib/Settings/Settings.cpp | 34 +- lib/Udp/MiLightDiscoveryServer.cpp | 7 +- lib/Udp/MiLightUdpServer.cpp | 3 +- lib/Udp/V6MiLightUdpServer.cpp | 3 +- lib/WebServer/MiLightHttpServer.cpp | 77 +- lib/WebServer/MiLightHttpServer.h | 5 +- .../.github/CONTRIBUTING.md | 12 + .../.github/ISSUE_TEMPLATE.md | 56 + lib/WiFiManager-2.0.3-alpha/.gitignore | 1 + lib/WiFiManager-2.0.3-alpha/.travis.yml | 53 + lib/WiFiManager-2.0.3-alpha/LICENSE | 22 + lib/WiFiManager-2.0.3-alpha/README.md | 558 ++++ lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp | 2966 +++++++++++++++++ lib/WiFiManager-2.0.3-alpha/WiFiManager.h | 616 ++++ .../examples/Advanced/Advanced.ino | 134 + .../AutoConnectWithFSParameters.ino | 175 + ...AutoConnectWithFSParametersAndCustomIP.ino | 172 + .../AutoConnectWithFeedbackLED.ino | 71 + .../examples/Basic/Basic.ino | 41 + .../OnDemandConfigPortal.ino | 347 ++ .../AutoConnectNonBlocking.ino | 27 + .../AutoConnectNonBlockingwParams.ino | 36 + .../onDemandNonBlocking.ino | 83 + .../AutoConnectWithFeedback.ino | 42 + .../AutoConnectWithReset.ino | 43 + .../AutoConnectWithStaticIP.ino | 71 + .../AutoConnectWithTimeout.ino | 38 + .../OnDemandConfigPortal.ino | 47 + .../OnDemandWebPortal/onDemandWebPortal.ino | 51 + .../ParamsChildClass/ParamsChildClass.ino | 141 + .../examples/Tests/AnonymousCB.ino | 26 + .../extras/WiFiManager.template.html | 324 ++ lib/WiFiManager-2.0.3-alpha/extras/parse.js | 60 + .../extras/png_signal_strength_master.png | Bin 0 -> 59671 bytes lib/WiFiManager-2.0.3-alpha/extras/template.h | 12 + lib/WiFiManager-2.0.3-alpha/extras/test.html | 182 + lib/WiFiManager-2.0.3-alpha/keywords.txt | 39 + lib/WiFiManager-2.0.3-alpha/library.json | 29 + .../library.properties | 9 + lib/WiFiManager-2.0.3-alpha/strings_en.h | 363 ++ lib/WiFiManager-2.0.3-alpha/travis/common.sh | 60 + platformio.ini | 17 +- src/main.cpp | 108 +- 47 files changed, 7097 insertions(+), 83 deletions(-) create mode 100644 lib/WiFiManager-2.0.3-alpha/.github/CONTRIBUTING.md create mode 100644 lib/WiFiManager-2.0.3-alpha/.github/ISSUE_TEMPLATE.md create mode 100644 lib/WiFiManager-2.0.3-alpha/.gitignore create mode 100644 lib/WiFiManager-2.0.3-alpha/.travis.yml create mode 100644 lib/WiFiManager-2.0.3-alpha/LICENSE create mode 100644 lib/WiFiManager-2.0.3-alpha/README.md create mode 100644 lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp create mode 100644 lib/WiFiManager-2.0.3-alpha/WiFiManager.h create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Advanced/Advanced.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Basic/Basic.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/ParamsChildClass/ParamsChildClass.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Tests/AnonymousCB.ino create mode 100644 lib/WiFiManager-2.0.3-alpha/extras/WiFiManager.template.html create mode 100644 lib/WiFiManager-2.0.3-alpha/extras/parse.js create mode 100644 lib/WiFiManager-2.0.3-alpha/extras/png_signal_strength_master.png create mode 100644 lib/WiFiManager-2.0.3-alpha/extras/template.h create mode 100644 lib/WiFiManager-2.0.3-alpha/extras/test.html create mode 100644 lib/WiFiManager-2.0.3-alpha/keywords.txt create mode 100644 lib/WiFiManager-2.0.3-alpha/library.json create mode 100644 lib/WiFiManager-2.0.3-alpha/library.properties create mode 100644 lib/WiFiManager-2.0.3-alpha/strings_en.h create mode 100644 lib/WiFiManager-2.0.3-alpha/travis/common.sh diff --git a/lib/MQTT/HomeAssistantDiscoveryClient.cpp b/lib/MQTT/HomeAssistantDiscoveryClient.cpp index b7445523..23d0f0ae 100644 --- a/lib/MQTT/HomeAssistantDiscoveryClient.cpp +++ b/lib/MQTT/HomeAssistantDiscoveryClient.cpp @@ -46,7 +46,9 @@ void HomeAssistantDiscoveryClient::addConfig(const char* alias, const BulbId& bu deviceMetadata[F("sw_version")] = QUOTE(MILIGHT_HUB_VERSION); JsonArray identifiers = deviceMetadata.createNestedArray(F("identifiers")); - identifiers.add(ESP.getChipId()); + // identifiers.add(ESP.getChipId()); + identifiers.add(ESP.getEfuseMac()); + bulbId.serialize(identifiers); // HomeAssistant only supports simple client availability @@ -138,7 +140,9 @@ String HomeAssistantDiscoveryClient::buildTopic(const BulbId& bulbId) { topic += "light/"; // Use a static ID that doesn't depend on configuration. - topic += "milight_hub_" + String(ESP.getChipId()); + // topic += "milight_hub_" + String(ESP.getChipId()); + topic += "milight_hub_" + String((uint32_t)ESP.getEfuseMac()); // lower 4 bytes (6 in total) + // make the object ID based on the actual parameters rather than the alias. topic += "/"; diff --git a/lib/MQTT/MqttClient.cpp b/lib/MQTT/MqttClient.cpp index f5ad6529..8c87db62 100644 --- a/lib/MQTT/MqttClient.cpp +++ b/lib/MQTT/MqttClient.cpp @@ -56,7 +56,8 @@ void MqttClient::begin() { bool MqttClient::connect() { char nameBuffer[30]; - sprintf_P(nameBuffer, PSTR("milight-hub-%u"), ESP.getChipId()); + sprintf_P(nameBuffer, PSTR("milight-hub-%u"), ESP.getEfuseMac()); + #ifdef MQTT_DEBUG Serial.println(F("MqttClient - connecting using name")); diff --git a/lib/MiLightState/GroupStatePersistence.cpp b/lib/MiLightState/GroupStatePersistence.cpp index 14a1f718..df8b3657 100644 --- a/lib/MiLightState/GroupStatePersistence.cpp +++ b/lib/MiLightState/GroupStatePersistence.cpp @@ -1,5 +1,6 @@ #include #include +#include static const char FILE_PREFIX[] = "group_states/"; diff --git a/lib/Settings/AboutHelper.cpp b/lib/Settings/AboutHelper.cpp index aac1233d..f6b49ccc 100644 --- a/lib/Settings/AboutHelper.cpp +++ b/lib/Settings/AboutHelper.cpp @@ -1,7 +1,8 @@ #include #include #include -#include +// #include +#include String AboutHelper::generateAboutString(bool abbreviated) { DynamicJsonDocument buffer(1024); @@ -18,11 +19,11 @@ void AboutHelper::generateAboutObject(JsonDocument& obj, bool abbreviated) { obj["firmware"] = QUOTE(FIRMWARE_NAME); obj["version"] = QUOTE(MILIGHT_HUB_VERSION); obj["ip_address"] = WiFi.localIP().toString(); - obj["reset_reason"] = ESP.getResetReason(); +// obj["reset_reason"] = ESP.getResetReason(); if (! abbreviated) { obj["variant"] = QUOTE(FIRMWARE_VARIANT); obj["free_heap"] = ESP.getFreeHeap(); - obj["arduino_version"] = ESP.getCoreVersion(); +// obj["arduino_version"] = ESP.getCoreVersion(); } } \ No newline at end of file diff --git a/lib/Settings/Settings.cpp b/lib/Settings/Settings.cpp index 40b320d6..9df80f0b 100644 --- a/lib/Settings/Settings.cpp +++ b/lib/Settings/Settings.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -61,12 +62,14 @@ void Settings::updateGatewayConfigs(JsonArray arr) { } } -void Settings::patch(JsonObject parsedSettings) { +void Settings::patch(JsonObject parsedSettings) { if (parsedSettings.isNull()) { Serial.println(F("Skipping patching loaded settings. Parsed settings was null.")); return; } + Serial.println("Patching settings..."); + this->setIfPresent(parsedSettings, "admin_username", adminUsername); this->setIfPresent(parsedSettings, "admin_password", adminPassword); this->setIfPresent(parsedSettings, "ce_pin", cePin); @@ -102,59 +105,76 @@ void Settings::patch(JsonObject parsedSettings) { this->setIfPresent(parsedSettings, "home_assistant_discovery_prefix", homeAssistantDiscoveryPrefix); this->setIfPresent(parsedSettings, "default_transition_period", defaultTransitionPeriod); + if (parsedSettings.containsKey("wifi_mode")) { + Serial.println("Patching wifi_mode"); this->wifiMode = wifiModeFromString(parsedSettings["wifi_mode"]); } + if (parsedSettings.containsKey("rf24_channels")) { + Serial.println("Patching rf24_channels"); JsonArray arr = parsedSettings["rf24_channels"]; rf24Channels = JsonHelpers::jsonArrToVector(arr, RF24ChannelHelpers::valueFromName); } if (parsedSettings.containsKey("rf24_listen_channel")) { + Serial.println("Patching rf24_listen_channel"); this->rf24ListenChannel = RF24ChannelHelpers::valueFromName(parsedSettings["rf24_listen_channel"]); } if (parsedSettings.containsKey("rf24_power_level")) { + Serial.println("Patching rf24_power_level"); this->rf24PowerLevel = RF24PowerLevelHelpers::valueFromName(parsedSettings["rf24_power_level"]); } if (parsedSettings.containsKey("led_mode_wifi_config")) { + Serial.println("Patching led_mode_wifi_config"); this->ledModeWifiConfig = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_config"]); } if (parsedSettings.containsKey("led_mode_wifi_failed")) { + Serial.println("Patching led_mode_wifi_failed"); this->ledModeWifiFailed = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_failed"]); } if (parsedSettings.containsKey("led_mode_operating")) { + Serial.println("Patching led_mode_operating"); this->ledModeOperating = LEDStatus::stringToLEDMode(parsedSettings["led_mode_operating"]); } if (parsedSettings.containsKey("led_mode_packet")) { + Serial.println("Patching led_mode_packet"); this->ledModePacket = LEDStatus::stringToLEDMode(parsedSettings["led_mode_packet"]); } if (parsedSettings.containsKey("radio_interface_type")) { + Serial.println("Patching radio_interface_type"); this->radioInterfaceType = Settings::typeFromString(parsedSettings["radio_interface_type"]); } if (parsedSettings.containsKey("device_ids")) { + Serial.println("Patching device_ids"); JsonArray arr = parsedSettings["device_ids"]; updateDeviceIds(arr); } if (parsedSettings.containsKey("gateway_configs")) { + Serial.println("Patching gateway_configs"); JsonArray arr = parsedSettings["gateway_configs"]; updateGatewayConfigs(arr); } if (parsedSettings.containsKey("group_state_fields")) { + Serial.println("Patching group_state_fields"); JsonArray arr = parsedSettings["group_state_fields"]; groupStateFields = JsonHelpers::jsonArrToVector(arr, GroupStateFieldHelpers::getFieldByName); } if (parsedSettings.containsKey("group_id_aliases")) { + Serial.println("Patching group_id_aliases"); parseGroupIdAliases(parsedSettings); } + + Serial.println("Patched settings"); } std::map::const_iterator Settings::findAlias(MiLightRemoteType deviceType, uint16_t deviceId, uint8_t groupId) { @@ -207,24 +227,34 @@ void Settings::dumpGroupIdAliases(JsonObject json) { } void Settings::load(Settings& settings) { + + Serial.println("Settings loading..."); + if (SPIFFS.exists(SETTINGS_FILE)) { // Clear in-memory settings settings = Settings(); + + Serial.println("Settings loading from file " + String(SETTINGS_FILE)); File f = SPIFFS.open(SETTINGS_FILE, "r"); + Serial.println("Settings loading... file opened"); + DynamicJsonDocument json(MILIGHT_HUB_SETTINGS_BUFFER_SIZE); auto error = deserializeJson(json, f); + Serial.println("Settings loading... json deserialized"); f.close(); if (! error) { JsonObject parsedSettings = json.as(); - settings.patch(parsedSettings); + settings.patch(parsedSettings); } else { Serial.print(F("Error parsing saved settings file: ")); Serial.println(error.c_str()); } } else { + Serial.println("Settings loading... no existing file found. Loadingd defaults."); + settings.save(); } } diff --git a/lib/Udp/MiLightDiscoveryServer.cpp b/lib/Udp/MiLightDiscoveryServer.cpp index 3e501b8b..a5af70f9 100644 --- a/lib/Udp/MiLightDiscoveryServer.cpp +++ b/lib/Udp/MiLightDiscoveryServer.cpp @@ -1,6 +1,7 @@ #include #include -#include +// #include +#include const char V3_SEARCH_STRING[] = "Link_Wi-Fi"; const char V6_SEARCH_STRING[] = "HF-A11ASSISTHREAD"; @@ -24,7 +25,9 @@ MiLightDiscoveryServer::~MiLightDiscoveryServer() { } void MiLightDiscoveryServer::begin() { + Serial.println("MiLightDiscoveryServer::begin beginning..."); socket.begin(settings.discoveryPort); + Serial.println("MiLightDiscoveryServer::begin begon"); } void MiLightDiscoveryServer::handleClient() { @@ -85,6 +88,6 @@ void MiLightDiscoveryServer::sendResponse(char* buffer) { #endif socket.beginPacket(socket.remoteIP(), socket.remotePort()); - socket.write(buffer); + socket.write(*buffer); socket.endPacket(); } diff --git a/lib/Udp/MiLightUdpServer.cpp b/lib/Udp/MiLightUdpServer.cpp index 71fa931e..8354e0d3 100644 --- a/lib/Udp/MiLightUdpServer.cpp +++ b/lib/Udp/MiLightUdpServer.cpp @@ -1,7 +1,8 @@ #include #include #include -#include +// #include +#include MiLightUdpServer::MiLightUdpServer(MiLightClient*& client, uint16_t port, uint16_t deviceId) : client(client), diff --git a/lib/Udp/V6MiLightUdpServer.cpp b/lib/Udp/V6MiLightUdpServer.cpp index a1b93fe8..3af23c5d 100644 --- a/lib/Udp/V6MiLightUdpServer.cpp +++ b/lib/Udp/V6MiLightUdpServer.cpp @@ -1,5 +1,6 @@ #include -#include +#include +// #include #include #include #include diff --git a/lib/WebServer/MiLightHttpServer.cpp b/lib/WebServer/MiLightHttpServer.cpp index 6c84d328..9fe6204c 100644 --- a/lib/WebServer/MiLightHttpServer.cpp +++ b/lib/WebServer/MiLightHttpServer.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -101,7 +102,7 @@ WiFiClient MiLightHttpServer::client() { return server.client(); } -void MiLightHttpServer::on(const char* path, HTTPMethod method, ESP8266WebServer::THandlerFunction handler) { +void MiLightHttpServer::on(const char* path, HTTPMethod method, THandlerFunction handler) { server.on(path, method, handler); } @@ -125,7 +126,7 @@ void MiLightHttpServer::handleSystemPost(RequestContext& request) { server.send_P(200, TEXT_PLAIN, PSTR("true")); delay(100); - ESP.eraseConfig(); + // ESP.eraseConfig(); delay(100); ESP.restart(); @@ -225,47 +226,47 @@ void MiLightHttpServer::handleUpdateSettingsPost(RequestContext& request) { } void MiLightHttpServer::handleFirmwarePost() { - server.sendHeader("Connection", "close"); - server.sendHeader("Access-Control-Allow-Origin", "*"); - - if (Update.hasError()) { - server.send_P( - 500, - TEXT_PLAIN, - PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.") - ); - } else { - server.send_P( - 200, - TEXT_PLAIN, - PSTR("Success. Device will now reboot.") - ); - } + // server.sendHeader("Connection", "close"); + // server.sendHeader("Access-Control-Allow-Origin", "*"); + + // if (Update.hasError()) { + // server.send_P( + // 500, + // TEXT_PLAIN, + // PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.") + // ); + // } else { + // server.send_P( + // 200, + // TEXT_PLAIN, + // PSTR("Success. Device will now reboot.") + // ); + // } - delay(1000); + // delay(1000); - ESP.restart(); + // ESP.restart(); } void MiLightHttpServer::handleFirmwareUpload() { - HTTPUpload& upload = server.upload(); - if(upload.status == UPLOAD_FILE_START){ - WiFiUDP::stopAll(); - uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; - if(!Update.begin(maxSketchSpace)){//start with max available size - Update.printError(Serial); - } - } else if(upload.status == UPLOAD_FILE_WRITE){ - if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){ - Update.printError(Serial); - } - } else if(upload.status == UPLOAD_FILE_END){ - if(Update.end(true)){ //true to set the size to the current progress - } else { - Update.printError(Serial); - } - } - yield(); + // HTTPUpload& upload = server.upload(); + // if(upload.status == UPLOAD_FILE_START){ + // WiFiUDP::stopAll(); + // uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; + // if(!Update.begin(maxSketchSpace)){//start with max available size + // Update.printError(Serial); + // } + // } else if(upload.status == UPLOAD_FILE_WRITE){ + // if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){ + // Update.printError(Serial); + // } + // } else if(upload.status == UPLOAD_FILE_END){ + // if(Update.end(true)){ //true to set the size to the current progress + // } else { + // Update.printError(Serial); + // } + // } + // yield(); } diff --git a/lib/WebServer/MiLightHttpServer.h b/lib/WebServer/MiLightHttpServer.h index ff272aa8..48ebfb32 100644 --- a/lib/WebServer/MiLightHttpServer.h +++ b/lib/WebServer/MiLightHttpServer.h @@ -14,6 +14,7 @@ typedef std::function SettingsSavedHandler; typedef std::function GroupDeletedHandler; +typedef std::function THandlerFunction; using RichHttpConfig = RichHttp::Generics::Configs::EspressifBuiltin; using RequestContext = RichHttpConfig::RequestContextType; @@ -47,7 +48,7 @@ class MiLightHttpServer { void handleClient(); void onSettingsSaved(SettingsSavedHandler handler); void onGroupDeleted(GroupDeletedHandler handler); - void on(const char* path, HTTPMethod method, ESP8266WebServer::THandlerFunction handler); + void on(const char* path, HTTPMethod method, THandlerFunction handler); void handlePacketSent(uint8_t* packet, const MiLightRemoteConfig& config); WiFiClient client(); @@ -101,7 +102,7 @@ class MiLightHttpServer { GroupStateStore*& stateStore; SettingsSavedHandler settingsSavedHandler; GroupDeletedHandler groupDeletedHandler; - ESP8266WebServer::THandlerFunction _handleRootPage; + THandlerFunction _handleRootPage; PacketSender*& packetSender; RadioSwitchboard*& radios; TransitionController& transitions; diff --git a/lib/WiFiManager-2.0.3-alpha/.github/CONTRIBUTING.md b/lib/WiFiManager-2.0.3-alpha/.github/CONTRIBUTING.md new file mode 100644 index 00000000..6760b62f --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/.github/CONTRIBUTING.md @@ -0,0 +1,12 @@ +## Contributing PRs and ISSUES + +The development branch is the active branch, no features or bugs will be fixed against master ( hotfixes may be considered ). + +Please test against development branch before submitting issues, issues against master will be closed, + +PRs against master may be kept open if provides something useful to other members. + +Please open issues before sumbitting PRs against development, as commits might be occuring very frequently. + +### Documentation is in progress +https://github.com/tzapu/WiFiManager/issues/500 diff --git a/lib/WiFiManager-2.0.3-alpha/.github/ISSUE_TEMPLATE.md b/lib/WiFiManager-2.0.3-alpha/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..2deb9427 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,56 @@ +## PLEASE TRY DEVELOPMENT BRANCH before submitting bugs on release or master, in case they were already fixed. ## + +Issues without basic info will be ignored or closed! + +Please fill the info fields, it helps to get you faster support ;) + +if you have a stack dump decode it: +https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/stack_dump.rst + +for better debug messages: +https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/debugging.rst + +----------------------------- Remove above ----------------------------- + +### Basic Infos + +#### Hardware +WiFimanager Branch/Release: Development + +Esp8266/Esp32: + +Hardware: ESP-12e, esp01, esp25 + +Core Version: 2.4.0, staging + +### Description + +Problem description + +### Settings in IDE + +Module: NodeMcu, Wemos D1 + +Additional libraries: + +### Sketch + +```cpp + +#include + +void setup() { + +} + +void loop() { + +} +``` + +### Debug Messages + +``` +messages here +``` + diff --git a/lib/WiFiManager-2.0.3-alpha/.gitignore b/lib/WiFiManager-2.0.3-alpha/.gitignore new file mode 100644 index 00000000..d837572a --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/.gitignore @@ -0,0 +1 @@ +platformio.ini diff --git a/lib/WiFiManager-2.0.3-alpha/.travis.yml b/lib/WiFiManager-2.0.3-alpha/.travis.yml new file mode 100644 index 00000000..cc63c554 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/.travis.yml @@ -0,0 +1,53 @@ +language: c +sudo: false + +before_install: + - "/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16" + - sleep 3 + - export DISPLAY=:1.0 + - wget http://downloads.arduino.cc/arduino-1.8.10-linux64.tar.xz + - tar xf arduino-1.8.10-linux64.tar.xz + - sudo mv arduino-1.8.10 /usr/local/share/arduino + - sudo ln -s /usr/local/share/arduino/arduino /usr/local/bin/arduino + +install: + - ln -s $PWD /usr/local/share/arduino/libraries/WiFiManager + - arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json,http://dl.espressif.com/dl/package_esp32_index.json" --save-prefs + - arduino --install-library "ArduinoJson:5.13.2" + - arduino --install-boards esp8266:esp8266 + - arduino --pref "compiler.warning_level=all" --save-prefs +# install esp32 + - arduino --install-boards esp32:esp32 + # - pushd . + # - mkdir -p ~/Arduino/hardware/espressif + # - cd ~/Arduino/hardware/espressif + # - git clone https://github.com/espressif/arduino-esp32.git esp32 + # - cd esp32 + # - git submodule update --init --recursive + # - cd tools + # - python2 get.py + # - popd +# esp32 needs WebServer_tng for now + # - git clone https://github.com/bbx10/WebServer_tng.git /usr/local/share/arduino/libraries/WebServer_tng + +script: + - "echo $PWD" + - "echo $HOME" + - "ls $PWD" + - source $TRAVIS_BUILD_DIR/travis/common.sh + - arduino --board esp8266:esp8266:generic:xtal=80,eesz=4M1M,FlashMode=qio,FlashFreq=80,dbg=Serial,lvl=CORE --save-prefs + - build_examples + - arduino --board esp32:esp32:esp32:FlashFreq=80,FlashSize=4M,DebugLevel=info --save-prefs +# some examples fail (SPIFFS defines differ esp32 vs esp8266) so we exclude them + - build_examples +# - arduino -v --verbose-build --verify $PWD/examples/AutoConnect/AutoConnect.ino + +# no coverage generated, no need to run +# +#after_success: +# - bash <(curl -s https://codecov.io/bash) + +notifications: + email: + on_success: change + on_failure: change diff --git a/lib/WiFiManager-2.0.3-alpha/LICENSE b/lib/WiFiManager-2.0.3-alpha/LICENSE new file mode 100644 index 00000000..1dabff57 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 tzapu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/lib/WiFiManager-2.0.3-alpha/README.md b/lib/WiFiManager-2.0.3-alpha/README.md new file mode 100644 index 00000000..9405479f --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/README.md @@ -0,0 +1,558 @@ + +# WiFiManager +## DEVELOPMENT BRANCH + +ESP8266 WiFi Connection manager with fallback web configuration portal + +:warning: This Documentation is out of date for this branch, see notes below + +[![Build Status](https://travis-ci.org/tzapu/WiFiManager.svg?branch=development)](https://travis-ci.org/tzapu/WiFiManager) + +![ESP8266](https://img.shields.io/badge/ESP-8266-000000.svg?longCache=true&style=flat&colorA=CC101F) +![ESP32](https://img.shields.io/badge/ESP-32-000000.svg?longCache=true&style=flat&colorA=CC101F) + +The configuration portal is of the captive variety, so on various devices it will present the configuration dialogue as soon as you connect to the created access point. + +First attempt at a library. Lots more changes and fixes to do. Contributions are welcome. + +**This works with the ESP8266 Arduino platform** + +[https://github.com/esp8266/Arduino](https://github.com/esp8266/Arduino) + +**This works with the ESP32 Arduino platform** + +[https://github.com/espressif/arduino-esp32](https://github.com/espressif/arduino-esp32) + +### Known Issues +* Documentation needs to be updated, see [https://github.com/tzapu/WiFiManager/issues/500](https://github.com/tzapu/WiFiManager/issues/500) + +## Contents + - [How it works](#how-it-works) + - [Wishlist](#wishlist) + - [Quick start](#quick-start) + - Installing + - [Arduino - Through Library Manager](#install-through-library-manager) + - [Arduino - From Github](#checkout-from-github) + - [PlatformIO](#install-using-platformio) + - [Using](#using) + - [Documentation](#documentation) + - [Access Point Password](#password-protect-the-configuration-access-point) + - [Callbacks](#callbacks) + - [Configuration Portal Timeout](#configuration-portal-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) + - [Troubleshooting](#troubleshooting) + - [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 +- because of the Captive Portal and the DNS server you will either get a 'Join to network' type of popup or get any domain you try to access redirected to the configuration portal +- choose one of the access points scanned, enter password, click save +- ESP will try to connect. If successful, it relinquishes control back to your app. If not, reconnect to AP and reconfigure. +- There are options to change this behavior or manually start the configportal and webportal independantly as well as run them in non blocking mode. + +## How It Looks +![ESP8266 WiFi Captive Portal Homepage](http://i.imgur.com/YPvW9eql.png) ![ESP8266 WiFi Captive Portal Configuration](http://i.imgur.com/oicWJ4gl.png) + +## Wishlist +- [x] remove dependency on EEPROM library +- [x] move HTML Strings to PROGMEM +- [x] cleanup and streamline code (although this is ongoing) +- [x] if timeout is set, extend it when a page is fetched in AP mode +- [x] add ability to configure more parameters than ssid/password +- [x] maybe allow setting ip of ESP after reboot +- [x] add to Arduino Library Manager +- [x] add to PlatformIO +- [ ] add multiple sets of network credentials +- [x] allow users to customize CSS +- [ ] rewrite documentation for simplicity, based on scenarios/goals + +### Development +- [x] ESP32 support +- [x] rely on the SDK's built in auto connect more than forcing a connect +- [x] add non blocking mode +- [x] easy customization of strings +- [x] hostname support +- [x] fix various bugs and workarounds for esp SDK issues +- [x] additional info page items +- [x] last status display / faiilure reason +- [x] customizeable menu +- [x] seperate custom params page +- [x] ondemand webportal +- [x] complete refactor of code to segment functions +- [x] wiif scan icons or percentage display +- [x] invert class for dark mode +- [x] more template tokens +- [x] progmem for all strings +- [ ] new callbacks +- [ ] new callouts / filters +- [ ] shared web server instance +- [x] latest esp idf/sdk support +- [x] wm is now non persistent, will not erase or change stored esp config on esp8266 +- [x] tons of debugging output / levels +- [ ] disable captiveportal +- [ ] preload wiifscans, faster page loads +- [ ] softap stability fixes when sta is not connected + + +## Quick Start + +### Installing +You can either install through the Arduino Library Manager or checkout the latest changes or a release from github + +#### Install through Library Manager +__Currently version 0.8+ works with release 2.4.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ + - in Arduino IDE got to Sketch/Include Library/Manage Libraries + ![Manage Libraries](http://i.imgur.com/9BkEBkR.png) + + - search for WiFiManager + ![WiFiManager package](http://i.imgur.com/18yIai8.png) + + - click Install and start [using it](#using) + +#### Checkout from github +__Github version works with release 2.4.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ +- Checkout library to your Arduino libraries folder + +### Using +- Include in your sketch +```cpp +#include //https://github.com/tzapu/WiFiManager WiFi Configuration Magic +``` + +- Initialize library, in your setup function add, NOTEif you are using non blocking you will make sure you create this in global scope or handle appropriatly , it will not work if in setup and using non blocking mode. +```cpp +WiFiManager wifiManager; +``` + +- Also in the setup function add +```cpp +//first parameter is name of access point, second is the password +wifiManager.autoConnect("AP-NAME", "AP-PASSWORD"); +``` +if you just want an unsecured access point +```cpp +wifiManager.autoConnect("AP-NAME"); +``` +or if you want to use and auto generated name from 'ESP' and the esp's Chip ID use +```cpp +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](https://github.com/tzapu/WiFiManager/tree/master/examples). + +#### Install Using PlatformIO + +[PlatformIO](https://platformio.org/) is an emerging ecosystem for IoT development, and +is an alternative to using the Arduino IDE. Install `WiFiManager` +using the platformio [library manager](https://docs.platformio.org/en/latest/librarymanager/index.htm) in your editor, +or using the [PlatformIO Core CLI](https://docs.platformio.org/en/latest/userguide/demo.html#library-manager), +or by adding it to your `platformio.ini` as shown below (recommended approach). + +The simplest way is to open the `platformio.ini` file at the root of your project, and `WifiManager` to the common top-level env +`lib_deps` key like so: + +``` +[env] +lib_deps = + WiFiManager +``` + +If you want to install the development branch, then you'll need to use the `repository#tag` format instead: + +``` +[env] +lib_deps = + https://github.com/tzapu/WiFiManager.git#development +``` + +## 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) +```cpp +wifiManager.autoConnect("AutoConnectAP", "password") +``` + +#### 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()` +```cpp +wifiManager.setAPCallback(configModeCallback); +``` +`configModeCallback` declaration and example +```cpp +void configModeCallback (WiFiManager *myWiFiManager) { + Serial.println("Entered config mode"); + Serial.println(WiFi.softAPIP()); + + Serial.println(myWiFiManager->getConfigPortalSSID()); +} +``` + +##### 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; +} +``` + +#### 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.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) + +#### 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()`. __Do not use BOTH.__ + +Example usage +```cpp +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) + +#### Exiting from the Configuration Portal +Normally, once entered, the configuration portal will continue to loop until WiFi credentials have been successfully entered or a timeout is reached. +If you'd prefer to exit without joining a WiFi network, say becuase you're going to put the ESP into AP mode, then press the "Exit" button +on the main webpage. +If started via `autoConnect` or `startConfigPortal` then it will return `false (portalAbortResult)` + +#### Custom Parameters +You can use WiFiManager to collect more parameters than just SSID and password. +This could be helpful for configuring stuff like MQTT host and port, [blynk](http://www.blynk.cc) or [emoncms](http://emoncms.org) tokens, just to name a few. +**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. +You should also take a look at adding custom HTML to your form. + +- 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 +You can set a custom IP for both AP (access point, config mode) and STA (station mode, client mode, normal project state) + +##### 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.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); +``` + +##### 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)); // optional DNS 4th argument +``` +There are a couple of examples in the examples folder that show you how to set a static IP and even how to configure it through the web configuration portal. + +NOTE: You should fill DNS server if you have HTTP requests with hostnames or syncronize time (NTP). It's the same as gateway ip or a popular (Google DNS: 8.8.8.8). + +#### Custom HTML, CSS, Javascript +There are various ways in which you can inject custom HTML, CSS or Javascript into the configuration portal. +The options are: +- inject custom head element +You can use this to any html bit to the head of the configuration portal. If you add a `"); +``` +- inject a custom bit of html in the configuration/param form +```cpp +WiFiManagerParameter custom_text("

This is just a text paragraph

"); +wifiManager.addParameter(&custom_text); +``` +- inject a custom bit of html in a configuration form element +Just add the bit you want added as the last parameter to the custom parameter constructor. +```cpp +WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "iot.eclipse", 40, " readonly"); +wifiManager.addParameter(&custom_mqtt_server); +``` + +#### Theming +You can customize certain elements of the default template with some builtin classes +```CPP +wifiManager.setClass("invert"); // dark theme +wifiManager.setScanDispPerc(true); // display percentages instead of graphs for RSSI +``` +There are additional classes in the css you can use in your custom html , see the example template. + +#### Filter Networks +You can filter networks based on signal quality and show/hide duplicate networks. + +- 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%; + +- You can also remove or show duplicate networks (default is remove). +Use this function to show (or hide) all networks. +```cpp +wifiManager.setRemoveDuplicateAPs(false); +``` + +#### Debug +Debug is enabled by default on `Serial` in non-stable releases. To disable add before autoConnect/startConfigPortal +```cpp +wifiManager.setDebugOutput(false); +``` + +You can pass in a custom stream via constructor +```CPP +WiFiManager wifiManager(Serial1); +``` + +You can customize the debug level by changing `_debugLevel` in source +options are: +* DEBUG_ERROR +* DEBUG_NOTIFY +* DEBUG_VERBOSE +* DEBUG_DEV +* DEBUG_MAX + +## Troubleshooting +If you get compilation errors, more often than not, you may need to install a newer version of the ESP8266 core for Arduino. + +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. + +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`. + +If trying to connect ends up in an endless loop, try to add `setConnectTimeout(60)` before `autoConnect();`. The parameter is timeout to try connecting in seconds. + +I get stuck in ap mode when the power goes out or modem resets, try a setConfigPortalTimeout(seconds). This will cause the configportal to close after no activity, and you can reboot or attempt reconnection in your code. + +## Releases +### 1.0.1 + +### Development Overview + +#### Added Public Methods +`setConfigPortalBlocking` + +`setShowStaticFields` + +`setCaptivePortalEnable` + +`setRestorePersistent` + +`setCaptivePortalClientCheck` + +`setWebPortalClientCheck` + +`startWebPortal` + +`stopWebPortal` + +`process` + +`disconnect` + +`erase` + +` debugSoftAPConfig` + +` debugPlatformInfo` + +`setScanDispPerc` + +`setHostname` + +`setMenu(menu_page_t[])` + +`setWiFiAutoReconnect` + +` setSTAStaticIPConfig(..,dns)` + +`setShowDnsFields` + +`getLastConxResult` + +`getWLStatusString` + +`getModeString` + +`getWiFiIsSaved` + +`setShowInfoErase` + +`setEnableConfigPortal` + +`setCountry` + +`setClass` + +`htmleEtities` + + +#### WiFiManagerParameter +`WiFiManagerParameter(id,label)` + +`WiFiManagerParameter.setValue(value,length)` + +`getParameters` + +`getParametersCount` + + +#### Constructors +`WiFiManager(Stream& consolePort)` + +#### define flags +❗️ **Defines cannot be set in user sketches** +`#define WM_MDNS // use MDNS` + +`#define WM_FIXERASECONFIG // use erase flash fix, esp8266 2.4.0` + +`#define WM_ERASE_NVS // esp32 erase(true) will erase NVS` + +`#include // esp32 info page will show last reset reasons if this file is included` + +#### Changes Overview +- ESP32 support ( fairly stable ) +- complete refactor of strings `strings_en.h` +- adds new tokens for wifiscan, and some classes (left , invert icons, MSG color) +- adds status callout panel default, primary, special colors +- adds tons of info on info page, and erase capability +- adds signal icons, replaces percentage ( has hover titles ) +- adds labels to all inputs (replaces placeholders) +- all html ( and eventually all strings except debug) moved to `strings_en.h` +- added additional debugging, compressed debug lines, debuglevels +- persistent disabled, and restored via de/con-stuctor (uses `setRestorePersistent`) +- should retain all user modes including AP, should not overwrite or persist user modes or configs,even STA (`storeSTAmode`) (BUGGY) +- ⚠️ return values may have changed depending on portal abort, or timeout ( `portalTimeoutResult`,`portalAbortResult`) +- params memory is auto allocated by increment of `WIFI_MANAGER_MAX_PARAMS(5)` when exceeded, user no longer needs to specify this at all. +- addparameter now returns bool, and it returns false if param ID is not alphanum [0-9,A-Z,a-z,_] +- param field ids allow {I} token to use param_n instead of string in case someones wants to change this due to i18n or character issues +- provides `#DEFINE FIXERASECONFIG` to help deal with https://github.com/esp8266/Arduino/pull/3635 +- failure reason reporting on portal +- set esp8266 sta hostname, esp32 sta+ap hostname ( DHCP client id) +- pass in debug stream in constructor WiFiManager(Stream& consolePort) +- you can force ip fields off with showxfields(false) if you set _disableIpFields=true +- param menu/page (setup) added to separate params from wifi page, handled automatically by setMenu +- set custom root menu +- disable configportal on autoconnect +- wm parameters init is now protected, allowing child classes, example included +- wifiscans are precached and async for faster page loads, refresh forces rescan +- adds esp32 gettemperature ( currently commented out, useful for relative measurement only ) + +#### 0.12 +- removed 204 header response +- fixed incompatibility with other libs using isnan and other std:: functions without namespace + +##### 0.11 +- a lot more reliable reconnecting to networks +- custom html in custom parameters (for read only params) +- custom html in custom parameter form (like labels) +- custom head element (like custom css) +- sort networks based on signal quality +- remove duplicate networks + +##### 0.10 +- some css changes +- bug fixes and speed improvements +- added an alternative to waitForConnectResult() for debugging +- changed `setTimeout(seconds)` to `setConfigPortalTimeout(seconds)` + +### 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__ + +The esp8266 and esp32 arduino and idf maintainers! + +[Shawn A aka tablatronix](https://github.com/tablatronix) + +[liebman](https://github.com/liebman) + +[Evgeny Dontsov](https://github.com/dontsovcmc) + +[Chris Marrin](https://github.com/cmarrin) + +[bbx10](https://github.com/bbx10) + +[kentaylor](https://github.com/kentaylor) + +[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) + +[jonathanendersby](https://github.com/jonathanendersby) + +[walthercarsten](https://github.com/walthercarsten) + +And countless others + +#### Inspiration + * http://www.esp8266.com/viewtopic.php?f=29&t=2520 + * https://github.com/chriscook8/esp-arduino-apboot + * https://github.com/esp8266/Arduino/tree/master/libraries/DNSServer/examples/CaptivePortalAdvanced + * Built by AlexT https://github.com/tzapu + diff --git a/lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp b/lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp new file mode 100644 index 00000000..1686a3e2 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp @@ -0,0 +1,2966 @@ +/** + * WiFiManager.cpp + * + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ + +#include "WiFiManager.h" + +#if defined(ESP8266) || defined(ESP32) + +#ifdef ESP32 +uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS; +#endif + +/** + * -------------------------------------------------------------------------------- + * WiFiManagerParameter + * -------------------------------------------------------------------------------- +**/ + +WiFiManagerParameter::WiFiManagerParameter() { + WiFiManagerParameter(""); +} + +WiFiManagerParameter::WiFiManagerParameter(const char *custom) { + _id = NULL; + _label = NULL; + _length = 1; + _value = NULL; + _labelPlacement = WFM_LABEL_BEFORE; + _customHTML = custom; +} + +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label) { + init(id, label, "", 0, "", WFM_LABEL_BEFORE); +} + +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length) { + init(id, label, defaultValue, length, "", WFM_LABEL_BEFORE); +} + +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom) { + init(id, label, defaultValue, length, custom, WFM_LABEL_BEFORE); +} + +WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { + init(id, label, defaultValue, length, custom, labelPlacement); +} + +void WiFiManagerParameter::init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { + _id = id; + _label = label; + _labelPlacement = labelPlacement; + _customHTML = custom; + setValue(defaultValue,length); +} + +WiFiManagerParameter::~WiFiManagerParameter() { + if (_value != NULL) { + delete[] _value; + } + _length=0; // setting length 0, ideally the entire parameter should be removed, or added to wifimanager scope so it follows +} + +// WiFiManagerParameter& WiFiManagerParameter::operator=(const WiFiManagerParameter& rhs){ +// Serial.println("copy assignment op called"); +// (*this->_value) = (*rhs._value); +// return *this; +// } + +// @note debug is not available in wmparameter class +void WiFiManagerParameter::setValue(const char *defaultValue, int length) { + if(!_id){ + // Serial.println("cannot set value of this parameter"); + return; + } + + // if(strlen(defaultValue) > length){ + // // Serial.println("defaultValue length mismatch"); + // // return false; //@todo bail + // } + + _length = length; + _value = new char[_length + 1]; + memset(_value, 0, _length + 1); // explicit null + + if (defaultValue != NULL) { + strncpy(_value, defaultValue, _length); + } +} +const char* WiFiManagerParameter::getValue() { + // Serial.println(printf("Address of _value is %p\n", (void *)_value)); + return _value; +} +const char* WiFiManagerParameter::getID() { + return _id; +} +const char* WiFiManagerParameter::getPlaceholder() { + return _label; +} +const char* WiFiManagerParameter::getLabel() { + return _label; +} +int WiFiManagerParameter::getValueLength() { + return _length; +} +int WiFiManagerParameter::getLabelPlacement() { + return _labelPlacement; +} +const char* WiFiManagerParameter::getCustomHTML() { + return _customHTML; +} + +/** + * [addParameter description] + * @access public + * @param {[type]} WiFiManagerParameter *p [description] + */ +bool WiFiManager::addParameter(WiFiManagerParameter *p) { + + // check param id is valid, unless null + if(p->getID()){ + for (size_t i = 0; i < strlen(p->getID()); i++){ + if(!(isAlphaNumeric(p->getID()[i])) && !(p->getID()[i]=='_')){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] parameter IDs can only contain alpha numeric chars"); + return false; + } + } + } + + // init params if never malloc + if(_params == NULL){ + DEBUG_WM(DEBUG_DEV,"allocating params bytes:",_max_params * sizeof(WiFiManagerParameter*)); + _params = (WiFiManagerParameter**)malloc(_max_params * sizeof(WiFiManagerParameter*)); + } + + // resize the params array by increment of WIFI_MANAGER_MAX_PARAMS + if(_paramsCount == _max_params){ + _max_params += WIFI_MANAGER_MAX_PARAMS; + DEBUG_WM(DEBUG_DEV,F("Updated _max_params:"),_max_params); + DEBUG_WM(DEBUG_DEV,"re-allocating params bytes:",_max_params * sizeof(WiFiManagerParameter*)); + WiFiManagerParameter** new_params = (WiFiManagerParameter**)realloc(_params, _max_params * sizeof(WiFiManagerParameter*)); + // DEBUG_WM(WIFI_MANAGER_MAX_PARAMS); + // DEBUG_WM(_paramsCount); + // DEBUG_WM(_max_params); + if (new_params != NULL) { + _params = new_params; + } else { + DEBUG_WM(DEBUG_ERROR,"[ERROR] failed to realloc params, size not increased!"); + return false; + } + } + + _params[_paramsCount] = p; + _paramsCount++; + + DEBUG_WM(DEBUG_VERBOSE,"Added Parameter:",p->getID()); + return true; +} + +/** + * [getParameters description] + * @access public + */ +WiFiManagerParameter** WiFiManager::getParameters() { + return _params; +} + +/** + * [getParametersCount description] + * @access public + */ +int WiFiManager::getParametersCount() { + return _paramsCount; +} + +/** + * -------------------------------------------------------------------------------- + * WiFiManager + * -------------------------------------------------------------------------------- +**/ + +// constructors +WiFiManager::WiFiManager(Stream& consolePort):_debugPort(consolePort){ + WiFiManagerInit(); +} + +WiFiManager::WiFiManager() { + WiFiManagerInit(); +} + +void WiFiManager::WiFiManagerInit(){ + setMenu(_menuIdsDefault); + if(_debug && _debugLevel > DEBUG_DEV) debugPlatformInfo(); + _max_params = WIFI_MANAGER_MAX_PARAMS; +} + +// destructor +WiFiManager::~WiFiManager() { + _end(); + // parameters + // @todo below belongs to wifimanagerparameter + if (_params != NULL){ + DEBUG_WM(DEBUG_DEV,F("freeing allocated params!")); + free(_params); + _params = NULL; + } + + // @todo remove event + // WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); + #ifdef ESP32 + WiFi.removeEvent(wm_event_id); + #endif + + DEBUG_WM(DEBUG_DEV,F("unloading")); +} + +void WiFiManager::_begin(){ + if(_hasBegun) return; + _hasBegun = true; + // _usermode = WiFi.getMode(); + + #ifndef ESP32 + WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites + #endif +} + +void WiFiManager::_end(){ + _hasBegun = false; + if(_userpersistent) WiFi.persistent(true); // reenable persistent, there is no getter we rely on _userpersistent + // if(_usermode != WIFI_OFF) WiFi.mode(_usermode); +} + +// AUTOCONNECT + +boolean WiFiManager::autoConnect() { + String ssid = getDefaultAPName(); + return autoConnect(ssid.c_str(), NULL); +} + +/** + * [autoConnect description] + * @access public + * @param {[type]} char const *apName [description] + * @param {[type]} char const *apPassword [description] + * @return {[type]} [description] + */ +boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { + DEBUG_WM(F("AutoConnect")); + if(getWiFiIsSaved()){ + + _begin(); + + // attempt to connect using saved settings, on fail fallback to AP config portal + if(!WiFi.enableSTA(true)){ + // handle failure mode Brownout detector etc. + DEBUG_WM(DEBUG_ERROR,"[FATAL] Unable to enable wifi!"); + return false; + } + + WiFiSetCountry(); + + #ifdef ESP32 + if(esp32persistent) WiFi.persistent(false); // disable persistent for esp32 after esp_wifi_start or else saves wont work + #endif + + _usermode = WIFI_STA; // When using autoconnect , assume the user wants sta mode on permanently. + + // no getter for autoreconnectpolicy before this + // https://github.com/esp8266/Arduino/pull/4359 + // so we must force it on else, if not connectimeout then waitforconnectionresult gets stuck endless loop + WiFi_autoReconnect(); + + // set hostname before stating + if((String)_hostname != ""){ + setupHostname(true); + } + + // if already connected, or try stored connect + // @note @todo ESP32 has no autoconnect, so connectwifi will always be called unless user called begin etc before + // @todo check if correct ssid == saved ssid when already connected + bool connected = false; + if (WiFi.status() == WL_CONNECTED){ + connected = true; + DEBUG_WM(F("AutoConnect: ESP Already Connected")); + setSTAConfig(); + // @todo not sure if this check makes sense, causes dup setSTAConfig in connectwifi, + // and we have no idea WHAT we are connected to + } + + if(connected || connectWifi("", "") == WL_CONNECTED){ + //connected + DEBUG_WM(F("AutoConnect: SUCCESS")); + DEBUG_WM(F("STA IP Address:"),WiFi.localIP()); + _lastconxresult = WL_CONNECTED; + + if((String)_hostname != ""){ + #ifdef ESP8266 + DEBUG_WM(DEBUG_DEV,"hostname: STA: ",WiFi.hostname()); + #elif defined(ESP32) + DEBUG_WM(DEBUG_DEV,"hostname: STA: ",WiFi.getHostname()); + #endif + } + + return true; // connected success + } + + // possibly skip the config portal + if (!_enableConfigPortal) { + return false; // not connected and not cp + } + + DEBUG_WM(F("AutoConnect: FAILED")); + } + else DEBUG_WM(F("No Credentials are Saved, skipping connect")); + + // not connected start configportal + bool res = startConfigPortal(apName, apPassword); + return res; +} + +bool WiFiManager::setupHostname(bool restart){ + if((String)_hostname == "") { + DEBUG_WM(DEBUG_DEV,"No Hostname to set"); + return false; + } else DEBUG_WM(DEBUG_DEV,"setupHostname: ",_hostname); + bool res = true; + #ifdef ESP8266 + DEBUG_WM(DEBUG_VERBOSE,"Setting WiFi hostname"); + res = WiFi.hostname(_hostname); + // #ifdef ESP8266MDNS_H + #ifdef WM_MDNS + DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname, tcp 80"); + if(MDNS.begin(_hostname)){ + MDNS.addService("http", "tcp", 80); + } + #endif + #elif defined(ESP32) + // @note hostname must be set after STA_START + delay(200); // do not remove, give time for STA_START + res = WiFi.setHostname(_hostname); + // #ifdef ESP32MDNS_H + #ifdef WM_MDNS + DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname, tcp 80"); + if(MDNS.begin(_hostname)){ + MDNS.addService("http", "tcp", 80); + } + #endif + #endif + + if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: set failed!")); + + // in sta mode restart , not sure about softap + if(restart && (WiFi.status() == WL_CONNECTED)){ + DEBUG_WM(DEBUG_VERBOSE,F("reconnecting to set new hostname")); + // WiFi.reconnect(); // This does not reset dhcp + WiFi_Disconnect(); + delay(200); // do not remove, need a delay for disconnect to change status() + } + + return res; +} + +// CONFIG PORTAL +bool WiFiManager::startAP(){ + bool ret = true; + DEBUG_WM(F("StartAP with SSID: "),_apName); + + #ifdef ESP8266 + // @bug workaround for bug #4372 https://github.com/esp8266/Arduino/issues/4372 + if(!WiFi.enableAP(true)) { + DEBUG_WM(DEBUG_ERROR,"[ERROR] enableAP failed!"); + return false; + } + delay(500); // workaround delay + #endif + + // setup optional soft AP static ip config + if (_ap_static_ip) { + DEBUG_WM(F("Custom AP IP/GW/Subnet:")); + if(!WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn)){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] softAPConfig failed!"); + } + } + + //@todo add callback here if needed to modify ap but cannot use setAPStaticIPConfig + //@todo rework wifi channelsync as it will work unpredictably when not connected in sta + + int32_t channel = 0; + if(_channelSync) channel = WiFi.channel(); + else channel = _apChannel; + + if(channel>0){ + DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",channel); + } + + // start soft AP with password or anonymous + // default channel is 1 here and in esplib, @todo just change to default remove conditionals + if (_apPassword != "") { + if(channel>0){ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),channel,_apHidden); + } + else{ + ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),1,_apHidden);//password option + } + } else { + DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!")); + if(channel>0){ + ret = WiFi.softAP(_apName.c_str(),"",channel,_apHidden); + } + else{ + ret = WiFi.softAP(_apName.c_str(),"",1,_apHidden); + } + } + + if(_debugLevel >= DEBUG_DEV) debugSoftAPConfig(); + + if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] There was a problem starting the AP"); + // @todo add softAP retry here + + delay(500); // slight delay to make sure we get an AP IP + DEBUG_WM(F("AP IP address:"),WiFi.softAPIP()); + + // set ap hostname + #ifdef ESP32 + if(ret && (String)_hostname != ""){ + DEBUG_WM(DEBUG_VERBOSE,"setting softAP Hostname:",_hostname); + bool res = WiFi.softAPsetHostname(_hostname); + if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: AP set failed!")); + DEBUG_WM(DEBUG_DEV,F("hostname: AP: "),WiFi.softAPgetHostname()); + } + #endif + + return ret; +} + +/** + * [startWebPortal description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::startWebPortal() { + if(configPortalActive || webPortalActive) return; + setupConfigPortal(); + webPortalActive = true; +} + +/** + * [stopWebPortal description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::stopWebPortal() { + if(!configPortalActive && !webPortalActive) return; + DEBUG_WM(DEBUG_VERBOSE,F("Stopping Web Portal")); + webPortalActive = false; + shutdownConfigPortal(); +} + +boolean WiFiManager::configPortalHasTimeout(){ + + if(_configPortalTimeout == 0 || (_apClientCheck && (WiFi_softap_num_stations() > 0))){ + if(millis() - timer > 30000){ + timer = millis(); + DEBUG_WM(DEBUG_VERBOSE,"NUM CLIENTS: " + (String)WiFi_softap_num_stations()); + } + _configPortalStart = millis(); // kludge, bump configportal start time to skew timeouts + return false; + } + // handle timeout + if(_webClientCheck && (_webPortalAccessed>_configPortalStart)>0) _configPortalStart = _webPortalAccessed; + + if(millis() > _configPortalStart + _configPortalTimeout){ + DEBUG_WM(F("config portal has timed out")); + return true; + } else if(_debugLevel > 0) { + // log timeout + if(_debug){ + uint16_t logintvl = 30000; // how often to emit timeing out counter logging + if((millis() - timer) > logintvl){ + timer = millis(); + DEBUG_WM(DEBUG_VERBOSE,F("Portal Timeout In"),(String)((_configPortalStart + _configPortalTimeout-millis())/1000) + (String)F(" seconds")); + } + } + } + + return false; +} + +void WiFiManager::setupConfigPortal() { + + DEBUG_WM(F("Starting Web Portal")); + + // setup dns and web servers + dnsServer.reset(new DNSServer()); + server.reset(new WM_WebServer(_httpPort)); + + if(_httpPort != 80) DEBUG_WM(DEBUG_VERBOSE,"http server started with custom port: ",_httpPort); // @todo not showing ip + + /* Setup the DNS server redirecting all the domains to the apIP */ + dnsServer->setErrorReplyCode(DNSReplyCode::NoError); + // DEBUG_WM("dns server started port: ",DNS_PORT); + DEBUG_WM(DEBUG_DEV,"dns server started with ip: ",WiFi.softAPIP()); // @todo not showing ip + dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); + + // @todo new callback, webserver started, callback cannot override handlers, but can grab them first + + if ( _webservercallback != NULL) { + _webservercallback(); + } + + /* Setup httpd callbacks, web pages: root, wifi config pages, SO captive portal detectors and not found. */ + server->on(String(FPSTR(R_root)).c_str(), std::bind(&WiFiManager::handleRoot, this)); + server->on(String(FPSTR(R_wifi)).c_str(), std::bind(&WiFiManager::handleWifi, this, true)); + server->on(String(FPSTR(R_wifinoscan)).c_str(), std::bind(&WiFiManager::handleWifi, this, false)); + server->on(String(FPSTR(R_wifisave)).c_str(), std::bind(&WiFiManager::handleWifiSave, this)); + server->on(String(FPSTR(R_info)).c_str(), std::bind(&WiFiManager::handleInfo, this)); + server->on(String(FPSTR(R_param)).c_str(), std::bind(&WiFiManager::handleParam, this)); + server->on(String(FPSTR(R_paramsave)).c_str(), std::bind(&WiFiManager::handleParamSave, this)); + server->on(String(FPSTR(R_restart)).c_str(), std::bind(&WiFiManager::handleReset, this)); + server->on(String(FPSTR(R_exit)).c_str(), std::bind(&WiFiManager::handleExit, this)); + server->on(String(FPSTR(R_close)).c_str(), std::bind(&WiFiManager::handleClose, this)); + server->on(String(FPSTR(R_erase)).c_str(), std::bind(&WiFiManager::handleErase, this, false)); + server->on(String(FPSTR(R_status)).c_str(), std::bind(&WiFiManager::handleWiFiStatus, this)); + server->onNotFound (std::bind(&WiFiManager::handleNotFound, this)); + + server->begin(); // Web server start + DEBUG_WM(DEBUG_VERBOSE,F("HTTP server started")); + + if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan , async +} + +boolean WiFiManager::startConfigPortal() { + String ssid = getDefaultAPName(); + return startConfigPortal(ssid.c_str(), NULL); +} + +/** + * [startConfigPortal description] + * @access public + * @param {[type]} char const *apName [description] + * @param {[type]} char const *apPassword [description] + * @return {[type]} [description] + */ +boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { + _begin(); + + //setup AP + _apName = apName; // @todo check valid apname ? + _apPassword = apPassword; + + DEBUG_WM(DEBUG_VERBOSE,F("Starting Config Portal")); + + if(_apName == "") _apName = getDefaultAPName(); + + if(!validApPassword()) return false; + + // HANDLE issues with STA connections, shutdown sta if not connected, or else this will hang channel scanning and softap will not respond + // @todo sometimes still cannot connect to AP for no known reason, no events in log either + if(_disableSTA || (!WiFi.isConnected() && _disableSTAConn)){ + // this fixes most ap problems, however, simply doing mode(WIFI_AP) does not work if sta connection is hanging, must `wifi_station_disconnect` + WiFi_Disconnect(); + WiFi_enableSTA(false); + DEBUG_WM(DEBUG_VERBOSE,F("Disabling STA")); + } + else { + // @todo even if sta is connected, it is possible that softap connections will fail, IOS says "invalid password", windows says "cannot connect to this network" researching + WiFi_enableSTA(true); + } + + // init configportal globals to known states + configPortalActive = true; + bool result = connect = abort = false; // loop flags, connect true success, abort true break + uint8_t state; + + _configPortalStart = millis(); + + // start access point + DEBUG_WM(DEBUG_VERBOSE,F("Enabling AP")); + startAP(); + WiFiSetCountry(); + + // do AP callback if set + if ( _apcallback != NULL) { + _apcallback(this); + } + + // init configportal + DEBUG_WM(DEBUG_DEV,F("setupConfigPortal")); + setupConfigPortal(); + + if(!_configPortalIsBlocking){ + DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, non blocking/processing")); + return result; + } + + DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, blocking, waiting for clients...")); + // blocking loop waiting for config + while(1){ + + // if timed out or abort, break + if(configPortalHasTimeout() || abort){ + DEBUG_WM(DEBUG_DEV,F("configportal abort")); + shutdownConfigPortal(); + result = abort ? portalAbortResult : portalTimeoutResult; // false, false + break; + } + + state = processConfigPortal(); + + // status change, break + if(state != WL_IDLE_STATUS){ + result = (state == WL_CONNECTED); // true if connected + break; + } + + yield(); // watchdog + } + + DEBUG_WM(DEBUG_NOTIFY,F("config portal exiting")); + return result; +} + +/** + * [process description] + * @access public + * @return {[type]} [description] + */ +boolean WiFiManager::process(){ + // process mdns, esp32 not required + #if defined(WM_MDNS) && defined(ESP8266) + MDNS.update(); + #endif + + if(webPortalActive || (configPortalActive && !_configPortalIsBlocking)){ + uint8_t state = processConfigPortal(); + return state == WL_CONNECTED; + } + return false; +} + +//using esp enums returns for now, should be fine +uint8_t WiFiManager::processConfigPortal(){ + //DNS handler + dnsServer->processNextRequest(); + //HTTP handler + server->handleClient(); + + // Waiting for save... + if(connect) { + connect = false; + DEBUG_WM(DEBUG_VERBOSE,F("processing save")); + if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast. + + // skip wifi if no ssid + if(_ssid == ""){ + DEBUG_WM(DEBUG_VERBOSE,F("No ssid, skipping wifi save")); + } + else{ + // attempt sta connection to submitted _ssid, _pass + if (connectWifi(_ssid, _pass) == WL_CONNECTED) { + + DEBUG_WM(F("Connect to new AP [SUCCESS]")); + DEBUG_WM(F("Got IP Address:")); + DEBUG_WM(WiFi.localIP()); + + if ( _savewificallback != NULL) { + _savewificallback(); + } + shutdownConfigPortal(); + return WL_CONNECTED; // CONNECT SUCCESS + } + DEBUG_WM(DEBUG_ERROR,F("[ERROR] Connect to new AP Failed")); + } + + if (_shouldBreakAfterConfig) { + + // do save callback + // @todo this is more of an exiting callback than a save, clarify when this should actually occur + // confirm or verify data was saved to make this more accurate callback + if ( _savewificallback != NULL) { + DEBUG_WM(DEBUG_VERBOSE,F("WiFi/Param save callback")); + _savewificallback(); + } + shutdownConfigPortal(); + return WL_CONNECT_FAILED; // CONNECT FAIL + } + else{ + // clear save strings + _ssid = ""; + _pass = ""; + // if connect fails, turn sta off to stabilize AP + WiFi_Disconnect(); + WiFi_enableSTA(false); + DEBUG_WM(DEBUG_VERBOSE,F("Disabling STA")); + } + } + + return WL_IDLE_STATUS; +} + +/** + * [shutdownConfigPortal description] + * @access public + * @return bool success (softapdisconnect) + */ +bool WiFiManager::shutdownConfigPortal(){ + if(webPortalActive) return false; + + //DNS handler + dnsServer->processNextRequest(); + //HTTP handler + server->handleClient(); + + // @todo what is the proper way to shutdown and free the server up + server->stop(); + server.reset(); + dnsServer->stop(); // free heap ? + dnsServer.reset(); + + WiFi.scanDelete(); // free wifi scan results + + if(!configPortalActive) return false; + + // turn off AP + // @todo bug workaround + // https://github.com/esp8266/Arduino/issues/3793 + // [APdisconnect] set_config failed! *WM: disconnect configportal - softAPdisconnect failed + // still no way to reproduce reliably + DEBUG_WM(DEBUG_VERBOSE,F("disconnect configportal")); + bool ret = false; + ret = WiFi.softAPdisconnect(false); + if(!ret)DEBUG_WM(DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); + delay(1000); + DEBUG_WM(DEBUG_VERBOSE,"restoring usermode",getModeString(_usermode)); + WiFi_Mode(_usermode); // restore users wifi mode, BUG https://github.com/esp8266/Arduino/issues/4372 + if(WiFi.status()==WL_IDLE_STATUS){ + WiFi.reconnect(); // restart wifi since we disconnected it in startconfigportal + DEBUG_WM(DEBUG_VERBOSE,"WiFi Reconnect, was idle"); + } + DEBUG_WM(DEBUG_VERBOSE,"wifi status:",getWLStatusString(WiFi.status())); + DEBUG_WM(DEBUG_VERBOSE,"wifi mode:",getModeString(WiFi.getMode())); + configPortalActive = false; + _end(); + return ret; +} + +// @todo refactor this up into seperate functions +// one for connecting to flash , one for new client +// clean up, flow is convoluted, and causes bugs +uint8_t WiFiManager::connectWifi(String ssid, String pass) { + DEBUG_WM(DEBUG_VERBOSE,F("Connecting as wifi client...")); + + uint8_t connRes = (uint8_t)WL_NO_SSID_AVAIL; + + setSTAConfig(); + //@todo catch failures in set_config + + // make sure sta is on before `begin` so it does not call enablesta->mode while persistent is ON ( which would save WM AP state to eeprom !) + + if(_cleanConnect) WiFi_Disconnect(); // disconnect before begin, in case anything is hung, this causes a 2 seconds delay for connect + // @todo find out what status is when this is needed, can we detect it and handle it, say in between states or idle_status + + // if ssid argument provided connect to that + if (ssid != "") { + wifiConnectNew(ssid,pass); + if(_saveTimeout > 0){ + connRes = waitForConnectResult(_saveTimeout); // use default save timeout for saves to prevent bugs in esp->waitforconnectresult loop + } + else { + connRes = waitForConnectResult(0); + } + } + else { + // connect using saved ssid if there is one + if (WiFi_hasAutoConnect()) { + wifiConnectDefault(); + connRes = waitForConnectResult(); + } + else { + DEBUG_WM(F("No wifi save required, skipping")); + } + } + + DEBUG_WM(DEBUG_VERBOSE,F("Connection result:"),getWLStatusString(connRes)); + +// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 +#ifdef NO_EXTRA_4K_HEAP + // do WPS, if WPS options enabled and not connected and no password was supplied + // @todo this seems like wrong place for this, is it a fallback or option? + if (_tryWPS && connRes != WL_CONNECTED && pass == "") { + startWPS(); + // should be connected at the end of WPS + connRes = waitForConnectResult(); + } +#endif + + if(connRes != WL_SCAN_COMPLETED){ + updateConxResult(connRes); + } + + return connRes; +} + +/** + * connect to a new wifi ap + * @since $dev + * @param String ssid + * @param String pass + * @return bool success + */ +bool WiFiManager::wifiConnectNew(String ssid, String pass){ + bool ret = false; + DEBUG_WM(F("CONNECTED:"),WiFi.status() == WL_CONNECTED); + DEBUG_WM(F("Connecting to NEW AP:"),ssid); + DEBUG_WM(DEBUG_DEV,F("Using Password:"),pass); + WiFi_enableSTA(true,storeSTAmode); // storeSTAmode will also toggle STA on in default opmode (persistent) if true (default) + WiFi.persistent(true); + ret = WiFi.begin(ssid.c_str(), pass.c_str()); + WiFi.persistent(false); + if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed"); + return ret; +} + +/** + * connect to stored wifi + * @since dev + * @return bool success + */ +bool WiFiManager::wifiConnectDefault(){ + bool ret = false; + DEBUG_WM(F("Connecting to SAVED AP:"),WiFi_SSID(true)); + DEBUG_WM(DEBUG_DEV,F("Using Password:"),WiFi_psk(true)); + ret = WiFi_enableSTA(true,storeSTAmode); + if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi enableSta failed"); + ret = WiFi.begin(); + if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed"); + return ret; +} + + +/** + * set sta config if set + * @since $dev + * @return bool success + */ +bool WiFiManager::setSTAConfig(){ + DEBUG_WM(DEBUG_DEV,F("STA static IP:"),_sta_static_ip); + bool ret = true; + if (_sta_static_ip) { + DEBUG_WM(DEBUG_VERBOSE,F("Custom static IP/GW/Subnet/DNS")); + if(_sta_static_dns) { + DEBUG_WM(DEBUG_VERBOSE,F("Custom static DNS")); + ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn, _sta_static_dns); + } + else { + DEBUG_WM(DEBUG_VERBOSE,F("Custom STA IP/GW/Subnet")); + ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn); + } + + if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi config failed"); + else DEBUG_WM(F("STA IP set:"),WiFi.localIP()); + } else { + DEBUG_WM(DEBUG_VERBOSE,F("setSTAConfig static ip not set, skipping")); + } + return ret; +} + +// @todo change to getLastFailureReason and do not touch conxresult +void WiFiManager::updateConxResult(uint8_t status){ + // hack in wrong password detection + _lastconxresult = status; + #ifdef ESP8266 + if(_lastconxresult == WL_CONNECT_FAILED){ + if(wifi_station_get_connect_status() == STATION_WRONG_PASSWORD){ + _lastconxresult = WL_STATION_WRONG_PASSWORD; + } + } + #elif defined(ESP32) + // if(_lastconxresult == WL_CONNECT_FAILED){ + if(_lastconxresult == WL_CONNECT_FAILED || _lastconxresult == WL_DISCONNECTED){ + DEBUG_WM(DEBUG_DEV,"lastconxresulttmp:",getWLStatusString(_lastconxresulttmp)); + if(_lastconxresulttmp != WL_IDLE_STATUS){ + _lastconxresult = _lastconxresulttmp; + // _lastconxresulttmp = WL_IDLE_STATUS; + } + } + #endif + DEBUG_WM(DEBUG_DEV,"lastconxresult:",getWLStatusString(_lastconxresult)); +} + + +uint8_t WiFiManager::waitForConnectResult() { + if(_connectTimeout > 0) DEBUG_WM(DEBUG_VERBOSE,_connectTimeout,F("ms connectTimeout set")); + return waitForConnectResult(_connectTimeout); +} + +/** + * waitForConnectResult + * @param uint16_t timeout in seconds + * @return uint8_t WL Status + */ +uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) { + if (timeout == 0){ + DEBUG_WM(F("connectTimeout not set, ESP waitForConnectResult...")); + return WiFi.waitForConnectResult(); + } + + unsigned long timeoutmillis = millis() + timeout; + DEBUG_WM(DEBUG_VERBOSE,timeout,F("ms timeout, waiting for connect...")); + uint8_t status = WiFi.status(); + + while(millis() < timeoutmillis) { + status = WiFi.status(); + // @todo detect additional states, connect happens, then dhcp then get ip, there is some delay here, make sure not to timeout if waiting on IP + if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) { + return status; + } + DEBUG_WM (DEBUG_VERBOSE,F(".")); + delay(100); + } + return status; +} + +// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 +#ifdef NO_EXTRA_4K_HEAP +void WiFiManager::startWPS() { + DEBUG_WM(F("START WPS")); + #ifdef ESP8266 + WiFi.beginWPSConfig(); + #else + // @todo + #endif + DEBUG_WM(F("END WPS")); +} +#endif + +String WiFiManager::getHTTPHead(String title){ + String page; + page += FPSTR(HTTP_HEAD_START); + page.replace(FPSTR(T_v), title); + page += FPSTR(HTTP_SCRIPT); + page += FPSTR(HTTP_STYLE); + page += _customHeadElement; + + if(_bodyClass != ""){ + String p = FPSTR(HTTP_HEAD_END); + p.replace(FPSTR(T_c), _bodyClass); // add class str + page += p; + } + else { + page += FPSTR(HTTP_HEAD_END); + } + + return page; +} + +/** + * HTTPD handler for page requests + */ +void WiFiManager::handleRequest() { + _webPortalAccessed = millis(); +} + +/** + * HTTPD CALLBACK root or redirect to captive portal + */ +void WiFiManager::handleRoot() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Root")); + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + handleRequest(); + String page = getHTTPHead(FPSTR(S_options)); // @token options @todo replace options with title + String str = FPSTR(HTTP_ROOT_MAIN); + str.replace(FPSTR(T_v),configPortalActive ? _apName : WiFi.localIP().toString()); // use ip if ap is not active for heading + page += str; + page += FPSTR(HTTP_PORTAL_OPTIONS); + page += getMenuOut(); + reportStatus(page); + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + // server->close(); // testing reliability fix for content length mismatches during mutiple flood hits WiFi_scanNetworks(); // preload wifiscan + if(_preloadwifiscan) WiFi_scanNetworks(_scancachetime,true); // preload wifiscan throttled, async + // @todo buggy, captive portals make a query on every page load, causing this to run every time in addition to the real page load + // I dont understand why, when you are already in the captive portal, I guess they want to know that its still up and not done or gone + // if we can detect these and ignore them that would be great, since they come from the captive portal redirect maybe there is a refferer +} + +/** + * HTTPD CALLBACK Wifi config page handler + */ +void WiFiManager::handleWifi(boolean scan) { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Wifi")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi + if (scan) { + // DEBUG_WM(DEBUG_DEV,"refresh flag:",server->hasArg(F("refresh"))); + WiFi_scanNetworks(server->hasArg(F("refresh")),false); //wifiscan, force if arg refresh + page += getScanItemOut(); + } + String pitem = ""; + + pitem = FPSTR(HTTP_FORM_START); + pitem.replace(FPSTR(T_v), F("wifisave")); // set form action + page += pitem; + + pitem = FPSTR(HTTP_FORM_WIFI); + pitem.replace(FPSTR(T_v), WiFi_SSID()); + + if(_showPassword){ + pitem.replace(FPSTR(T_p), WiFi_psk()); + } + else { + pitem.replace(FPSTR(T_p),FPSTR(S_passph)); + } + page += pitem; + + page += getStaticOut(); + page += FPSTR(HTTP_FORM_WIFI_END); + if(_paramsInWifi && _paramsCount>0){ + page += FPSTR(HTTP_FORM_PARAM_HEAD); + page += getParamOut(); + } + page += FPSTR(HTTP_FORM_END); + page += FPSTR(HTTP_SCAN_LINK); + if(_showBack) page += FPSTR(HTTP_BACKBTN); + reportStatus(page); + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + // server->close(); // testing reliability fix for content length mismatches during mutiple flood hits + + DEBUG_WM(DEBUG_DEV,F("Sent config page")); +} + +/** + * HTTPD CALLBACK Wifi param page handler + */ +void WiFiManager::handleParam(){ + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Param")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleparam)); // @token titlewifi + + String pitem = ""; + + pitem = FPSTR(HTTP_FORM_START); + pitem.replace(FPSTR(T_v), F("paramsave")); + page += pitem; + + page += getParamOut(); + page += FPSTR(HTTP_FORM_END); + if(_showBack) page += FPSTR(HTTP_BACKBTN); + reportStatus(page); + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + + DEBUG_WM(DEBUG_DEV,F("Sent param page")); +} + + +String WiFiManager::getMenuOut(){ + String page; + + for(auto menuId :_menuIds ){ + if(((String)menuId == "param") && (_paramsCount == 0)) continue; // no params set, omit params from menu, @todo this may be undesired by someone + page += HTTP_PORTAL_MENU[menuId]; + } + + return page; +} + +// // is it possible in softap mode to detect aps without scanning +// bool WiFiManager::WiFi_scanNetworksForAP(bool force){ +// WiFi_scanNetworks(force); +// } + +void WiFiManager::WiFi_scanComplete(int networksFound){ + _lastscan = millis(); + _numNetworks = networksFound; + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC completed"), "in "+(String)(_lastscan - _startscan)+" ms"); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC found:"),_numNetworks); +} + +bool WiFiManager::WiFi_scanNetworks(){ + return WiFi_scanNetworks(false,false); +} + +bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime,bool async){ + return WiFi_scanNetworks(millis()-_lastscan > cachetime,async); +} +bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime){ + return WiFi_scanNetworks(millis()-_lastscan > cachetime,false); +} +bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ + // DEBUG_WM(DEBUG_DEV,"scanNetworks async:",async == true); + // DEBUG_WM(DEBUG_DEV,_numNetworks,(millis()-_lastscan )); + // DEBUG_WM(DEBUG_DEV,"scanNetworks force:",force == true); + if(force || _numNetworks == 0 || (millis()-_lastscan > 60000)){ + int8_t res; + _startscan = millis(); + if(async && _asyncScan){ + #ifdef ESP8266 + #ifndef WM_NOASYNC // no async available < 2.4.0 + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); + using namespace std::placeholders; // for `_1` + WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); + #else + res = WiFi.scanNetworks(); + #endif + #else + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); + res = WiFi.scanNetworks(true); + #endif + return false; + } + else{ + res = WiFi.scanNetworks(); + } + if(res == WIFI_SCAN_FAILED) DEBUG_WM(DEBUG_ERROR,"[ERROR] scan failed"); + else if(res == WIFI_SCAN_RUNNING){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] scan waiting"); + while(WiFi.scanComplete() == WIFI_SCAN_RUNNING){ + DEBUG_WM(DEBUG_ERROR,"."); + delay(100); + } + _numNetworks = WiFi.scanComplete(); + } + else if(res >=0 ) _numNetworks = res; + _lastscan = millis(); + DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); + return true; + } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+" ms ago"); + return false; +} + +String WiFiManager::WiFiManager::getScanItemOut(){ + String page; + + if(!_numNetworks) WiFi_scanNetworks(); // scan in case this gets called before any scans + + int n = _numNetworks; + if (n == 0) { + DEBUG_WM(F("No networks found")); + page += FPSTR(S_nonetworks); // @token nonetworks + } + else { + DEBUG_WM(n,F("networks found")); + //sort networks + int indices[n]; + for (int i = 0; i < n; i++) { + indices[i] = i; + } + + // RSSI SORT + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) { + std::swap(indices[i], indices[j]); + } + } + } + + /* test std:sort + std::sort(indices, indices + n, [](const int & a, const int & b) -> bool + { + return WiFi.RSSI(a) > WiFi.RSSI(b); + }); + */ + + // remove duplicates ( must be RSSI sorted ) + if (_removeDuplicateAPs) { + String cssid; + for (int i = 0; i < n; i++) { + if (indices[i] == -1) continue; + cssid = WiFi.SSID(indices[i]); + for (int j = i + 1; j < n; j++) { + if (cssid == WiFi.SSID(indices[j])) { + DEBUG_WM(DEBUG_VERBOSE,F("DUP AP:"),WiFi.SSID(indices[j])); + indices[j] = -1; // set dup aps to index -1 + } + } + } + } + + // token precheck, to speed up replacements on large ap lists + String HTTP_ITEM_STR = FPSTR(HTTP_ITEM); + + // toggle icons with percentage + HTTP_ITEM_STR.replace("{qp}", FPSTR(HTTP_ITEM_QP)); + HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "" : "h"); + HTTP_ITEM_STR.replace("{qi}", FPSTR(HTTP_ITEM_QI)); + HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "h" : ""); + + // set token precheck flags + bool tok_r = HTTP_ITEM_STR.indexOf(FPSTR(T_r)) > 0; + bool tok_R = HTTP_ITEM_STR.indexOf(FPSTR(T_R)) > 0; + bool tok_e = HTTP_ITEM_STR.indexOf(FPSTR(T_e)) > 0; + bool tok_q = HTTP_ITEM_STR.indexOf(FPSTR(T_q)) > 0; + bool tok_i = HTTP_ITEM_STR.indexOf(FPSTR(T_i)) > 0; + + //display networks in page + for (int i = 0; i < n; i++) { + if (indices[i] == -1) continue; // skip dups + + DEBUG_WM(DEBUG_VERBOSE,F("AP: "),(String)WiFi.RSSI(indices[i]) + " " + (String)WiFi.SSID(indices[i])); + + int rssiperc = getRSSIasQuality(WiFi.RSSI(indices[i])); + uint8_t enc_type = WiFi.encryptionType(indices[i]); + + if (_minimumQuality == -1 || _minimumQuality < rssiperc) { + String item = HTTP_ITEM_STR; + item.replace(FPSTR(T_v), htmlEntities(WiFi.SSID(indices[i]))); // ssid no encoding + if(tok_e) item.replace(FPSTR(T_e), encryptionTypeStr(enc_type)); + if(tok_r) item.replace(FPSTR(T_r), (String)rssiperc); // rssi percentage 0-100 + if(tok_R) item.replace(FPSTR(T_R), (String)WiFi.RSSI(indices[i])); // rssi db + if(tok_q) item.replace(FPSTR(T_q), (String)int(round(map(rssiperc,0,100,1,4)))); //quality icon 1-4 + if(tok_i){ + if (enc_type != WM_WIFIOPEN) { + item.replace(FPSTR(T_i), F("l")); + } else { + item.replace(FPSTR(T_i), ""); + } + } + //DEBUG_WM(item); + page += item; + delay(0); + } else { + DEBUG_WM(DEBUG_VERBOSE,F("Skipping , does not meet _minimumQuality")); + } + + } + page += FPSTR(HTTP_BR); + } + + return page; +} + +String WiFiManager::getIpForm(String id, String title, String value){ + String item = FPSTR(HTTP_FORM_LABEL); + item += FPSTR(HTTP_FORM_PARAM); + item.replace(FPSTR(T_i), id); + item.replace(FPSTR(T_n), id); + item.replace(FPSTR(T_p), FPSTR(T_t)); + // item.replace(FPSTR(T_p), default); + item.replace(FPSTR(T_t), title); + item.replace(FPSTR(T_l), F("15")); + item.replace(FPSTR(T_v), value); + item.replace(FPSTR(T_c), ""); + return item; +} + +String WiFiManager::getStaticOut(){ + String page; + if ((_staShowStaticFields || _sta_static_ip) && _staShowStaticFields>=0) { + DEBUG_WM(DEBUG_DEV,"_staShowStaticFields"); + page += FPSTR(HTTP_FORM_STATIC_HEAD); + // @todo how can we get these accurate settings from memory , wifi_get_ip_info does not seem to reveal if struct ip_info is static or not + page += getIpForm(FPSTR(S_ip),FPSTR(S_staticip),(_sta_static_ip ? _sta_static_ip.toString() : "")); // @token staticip + // WiFi.localIP().toString(); + page += getIpForm(FPSTR(S_gw),FPSTR(S_staticgw),(_sta_static_gw ? _sta_static_gw.toString() : "")); // @token staticgw + // WiFi.gatewayIP().toString(); + page += getIpForm(FPSTR(S_sn),FPSTR(S_subnet),(_sta_static_sn ? _sta_static_sn.toString() : "")); // @token subnet + // WiFi.subnetMask().toString(); + } + + if((_staShowDns || _sta_static_dns) && _staShowDns>=0){ + page += getIpForm(FPSTR(S_dns),FPSTR(S_staticdns),(_sta_static_dns ? _sta_static_dns.toString() : "")); // @token dns + } + + if(page!="") page += FPSTR(HTTP_BR); // @todo remove these, use css + + return page; +} + +String WiFiManager::getParamOut(){ + String page; + + if(_paramsCount > 0){ + + String HTTP_PARAM_temp = FPSTR(HTTP_FORM_LABEL); + HTTP_PARAM_temp += FPSTR(HTTP_FORM_PARAM); + bool tok_I = HTTP_PARAM_temp.indexOf(FPSTR(T_I)) > 0; + bool tok_i = HTTP_PARAM_temp.indexOf(FPSTR(T_i)) > 0; + bool tok_n = HTTP_PARAM_temp.indexOf(FPSTR(T_n)) > 0; + bool tok_p = HTTP_PARAM_temp.indexOf(FPSTR(T_p)) > 0; + bool tok_t = HTTP_PARAM_temp.indexOf(FPSTR(T_t)) > 0; + bool tok_l = HTTP_PARAM_temp.indexOf(FPSTR(T_l)) > 0; + bool tok_v = HTTP_PARAM_temp.indexOf(FPSTR(T_v)) > 0; + bool tok_c = HTTP_PARAM_temp.indexOf(FPSTR(T_c)) > 0; + + char valLength[5]; + // add the extra parameters to the form + for (int i = 0; i < _paramsCount; i++) { + if (_params[i] == NULL || _params[i]->_length == 0) { + DEBUG_WM(DEBUG_ERROR,"[ERROR] WiFiManagerParameter is out of scope"); + break; + } + + // label before or after, @todo this could be done via floats or CSS and eliminated + String pitem; + switch (_params[i]->getLabelPlacement()) { + case WFM_LABEL_BEFORE: + pitem = FPSTR(HTTP_FORM_LABEL); + pitem += FPSTR(HTTP_FORM_PARAM); + break; + case WFM_LABEL_AFTER: + pitem = FPSTR(HTTP_FORM_PARAM); + pitem += FPSTR(HTTP_FORM_LABEL); + break; + default: + // WFM_NO_LABEL + pitem = FPSTR(HTTP_FORM_PARAM); + break; + } + + // Input templating + // "
"; + // if no ID use customhtml for item, else generate from param string + if (_params[i]->getID() != NULL) { + if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); // T_I id number + if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); // T_i id name + if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); // T_n id name alias + if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); // T_p replace legacy placeholder token + if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getLabel()); // T_t title/label + snprintf(valLength, 5, "%d", _params[i]->getValueLength()); + if(tok_l)pitem.replace(FPSTR(T_l), valLength); // T_l value length + if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); // T_v value + if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // T_c meant for additional attributes, not html, but can stuff + } else { + pitem = _params[i]->getCustomHTML(); + } + + page += pitem; + } + } + + return page; +} + +void WiFiManager::handleWiFiStatus(){ + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi status ")); + handleRequest(); + String page; + // String page = "{\"result\":true,\"count\":1}"; + #ifdef WM_JSTEST + page = FPSTR(HTTP_JS); + #endif + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); +} + +/** + * HTTPD CALLBACK save form and redirect to WLAN config page again + */ +void WiFiManager::handleWifiSave() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); + DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); + handleRequest(); + + // @todo use new callback for before paramsaves + if ( _presavecallback != NULL) { + _presavecallback(); + } + + //SAVE/connect here + _ssid = server->arg(F("s")).c_str(); + _pass = server->arg(F("p")).c_str(); + + if(_paramsInWifi) doParamSave(); + + if (server->arg(FPSTR(S_ip)) != "") { + //_sta_static_ip.fromString(server->arg(FPSTR(S_ip)); + String ip = server->arg(FPSTR(S_ip)); + optionalIPFromString(&_sta_static_ip, ip.c_str()); + DEBUG_WM(DEBUG_DEV,F("static ip:"),ip); + } + if (server->arg(FPSTR(S_gw)) != "") { + String gw = server->arg(FPSTR(S_gw)); + optionalIPFromString(&_sta_static_gw, gw.c_str()); + DEBUG_WM(DEBUG_DEV,F("static gateway:"),gw); + } + if (server->arg(FPSTR(S_sn)) != "") { + String sn = server->arg(FPSTR(S_sn)); + optionalIPFromString(&_sta_static_sn, sn.c_str()); + DEBUG_WM(DEBUG_DEV,F("static netmask:"),sn); + } + if (server->arg(FPSTR(S_dns)) != "") { + String dns = server->arg(FPSTR(S_dns)); + optionalIPFromString(&_sta_static_dns, dns.c_str()); + DEBUG_WM(DEBUG_DEV,F("static DNS:"),dns); + } + + String page; + + if(_ssid == ""){ + page = getHTTPHead(FPSTR(S_titlewifisettings)); // @token titleparamsaved + page += FPSTR(HTTP_PARAMSAVED); + } + else { + page = getHTTPHead(FPSTR(S_titlewifisaved)); // @token titlewifisaved + page += FPSTR(HTTP_SAVED); + } + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->sendHeader(FPSTR(HTTP_HEAD_CORS), FPSTR(HTTP_HEAD_CORS_ALLOW_ALL)); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + + DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); + + connect = true; //signal ready to connect/reset process in processConfigPortal +} + +void WiFiManager::handleParamSave() { + + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); + DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); + handleRequest(); + + doParamSave(); + + String page = getHTTPHead(FPSTR(S_titleparamsaved)); // @token titleparamsaved + page += FPSTR(HTTP_PARAMSAVED); + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + + DEBUG_WM(DEBUG_DEV,F("Sent param save page")); +} + +void WiFiManager::doParamSave(){ + // @todo use new callback for before paramsaves, is this really needed? + if ( _presavecallback != NULL) { + _presavecallback(); + } + + //parameters + if(_paramsCount > 0){ + DEBUG_WM(DEBUG_VERBOSE,F("Parameters")); + DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + + for (int i = 0; i < _paramsCount; i++) { + if (_params[i] == NULL || _params[i]->_length == 0) { + DEBUG_WM(DEBUG_ERROR,"[ERROR] WiFiManagerParameter is out of scope"); + break; // @todo might not be needed anymore + } + //read parameter from server + String name = (String)FPSTR(S_parampre)+(String)i; + String value; + if(server->hasArg(name)) { + value = server->arg(name); + } else { + value = server->arg(_params[i]->getID()); + } + + //store it in params array + value.toCharArray(_params[i]->_value, _params[i]->_length+1); // length+1 null terminated + DEBUG_WM(DEBUG_VERBOSE,(String)_params[i]->getID() + ":",value); + } + DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + } + + if ( _saveparamscallback != NULL) { + _saveparamscallback(); + } + +} + +/** + * HTTPD CALLBACK info page + */ +void WiFiManager::handleInfo() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Info")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo + reportStatus(page); + + uint16_t infos = 0; + + //@todo convert to enum or refactor to strings + //@todo wrap in build flag to remove all info code for memory saving + #ifdef ESP8266 + infos = 27; + String infoids[] = { + F("esphead"), + F("uptime"), + F("chipid"), + F("fchipid"), + F("idesize"), + F("flashsize"), + F("sdkver"), + F("corever"), + F("bootver"), + F("cpufreq"), + F("freeheap"), + F("memsketch"), + F("memsmeter"), + F("lastreset"), + F("wifihead"), + F("apip"), + F("apmac"), + F("apssid"), + F("apbssid"), + F("staip"), + F("stagw"), + F("stasub"), + F("dnss"), + F("host"), + F("stamac"), + F("conx"), + F("autoconx") + }; + + #elif defined(ESP32) + infos = 22; + String infoids[] = { + F("esphead"), + F("uptime"), + F("chipid"), + F("chiprev"), + F("idesize"), + F("sdkver"), + F("cpufreq"), + F("freeheap"), + F("lastreset"), + // F("temp"), + F("wifihead"), + F("apip"), + F("apmac"), + F("aphost"), + F("apssid"), + F("apbssid"), + F("staip"), + F("stagw"), + F("stasub"), + F("dnss"), + F("host"), + F("stamac"), + F("conx") + }; + #endif + + for(size_t i=0; i"); + if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); + if(_showBack) page += FPSTR(HTTP_BACKBTN); + page += FPSTR(HTTP_HELP); + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + + DEBUG_WM(DEBUG_DEV,F("Sent info page")); +} + +String WiFiManager::getInfoData(String id){ + + String p; + // @todo add WM versioning + if(id==F("esphead"))p = FPSTR(HTTP_INFO_esphead); + else if(id==F("wifihead"))p = FPSTR(HTTP_INFO_wifihead); + else if(id==F("uptime")){ + // subject to rollover! + p = FPSTR(HTTP_INFO_uptime); + p.replace(FPSTR(T_1),(String)(millis() / 1000 / 60)); + p.replace(FPSTR(T_2),(String)((millis() / 1000) % 60)); + } + else if(id==F("chipid")){ + p = FPSTR(HTTP_INFO_chipid); + p.replace(FPSTR(T_1),String(WIFI_getChipId(),HEX)); + } + #ifdef ESP32 + else if(id==F("chiprev")){ + p = FPSTR(HTTP_INFO_chiprev); + String rev = (String)ESP.getChipRevision(); + #ifdef _SOC_EFUSE_REG_H_ + String revb = (String)(REG_READ(EFUSE_BLK0_RDATA3_REG) >> (EFUSE_RD_CHIP_VER_RESERVE_S)&&EFUSE_RD_CHIP_VER_RESERVE_V); + p.replace(FPSTR(T_1),rev+"
"+revb); + #else + p.replace(FPSTR(T_1),rev); + #endif + } + #endif + #ifdef ESP8266 + else if(id==F("fchipid")){ + p = FPSTR(HTTP_INFO_fchipid); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipId()); + } + #endif + else if(id==F("idesize")){ + p = FPSTR(HTTP_INFO_idesize); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipSize()); + } + else if(id==F("flashsize")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_flashsize); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipRealSize()); + #endif + } + else if(id==F("sdkver")){ + p = FPSTR(HTTP_INFO_sdkver); + #ifdef ESP32 + p.replace(FPSTR(T_1),(String)esp_get_idf_version()); + #else + p.replace(FPSTR(T_1),(String)system_get_sdk_version()); + #endif + } + else if(id==F("corever")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_corever); + p.replace(FPSTR(T_1),(String)ESP.getCoreVersion()); + #endif + } + #ifdef ESP8266 + else if(id==F("bootver")){ + p = FPSTR(HTTP_INFO_bootver); + p.replace(FPSTR(T_1),(String)system_get_boot_version()); + } + #endif + else if(id==F("cpufreq")){ + p = FPSTR(HTTP_INFO_cpufreq); + p.replace(FPSTR(T_1),(String)ESP.getCpuFreqMHz()); + } + else if(id==F("freeheap")){ + p = FPSTR(HTTP_INFO_freeheap); + p.replace(FPSTR(T_1),(String)ESP.getFreeHeap()); + } + #ifdef ESP8266 + else if(id==F("memsketch")){ + p = FPSTR(HTTP_INFO_memsketch); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + } + #endif + #ifdef ESP8266 + else if(id==F("memsmeter")){ + p = FPSTR(HTTP_INFO_memsmeter); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + } + #endif + else if(id==F("lastreset")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_lastreset); + p.replace(FPSTR(T_1),(String)ESP.getResetReason()); + #elif defined(ESP32) && defined(_ROM_RTC_H_) + // requires #include + p = FPSTR(HTTP_INFO_lastreset); + for(int i=0;i<2;i++){ + int reason = rtc_get_reset_reason(i); + String tok = (String)T_ss+(String)(i+1)+(String)T_es; + switch (reason) + { + //@todo move to array + case 1 : p.replace(tok,F("Vbat power on reset"));break; + case 3 : p.replace(tok,F("Software reset digital core"));break; + case 4 : p.replace(tok,F("Legacy watch dog reset digital core"));break; + case 5 : p.replace(tok,F("Deep Sleep reset digital core"));break; + case 6 : p.replace(tok,F("Reset by SLC module, reset digital core"));break; + case 7 : p.replace(tok,F("Timer Group0 Watch dog reset digital core"));break; + case 8 : p.replace(tok,F("Timer Group1 Watch dog reset digital core"));break; + case 9 : p.replace(tok,F("RTC Watch dog Reset digital core"));break; + case 10 : p.replace(tok,F("Instrusion tested to reset CPU"));break; + case 11 : p.replace(tok,F("Time Group reset CPU"));break; + case 12 : p.replace(tok,F("Software reset CPU"));break; + case 13 : p.replace(tok,F("RTC Watch dog Reset CPU"));break; + case 14 : p.replace(tok,F("for APP CPU, reseted by PRO CPU"));break; + case 15 : p.replace(tok,F("Reset when the vdd voltage is not stable"));break; + case 16 : p.replace(tok,F("RTC Watch dog reset digital core and rtc module"));break; + default : p.replace(tok,F("NO_MEAN")); + } + } + #endif + } + else if(id==F("apip")){ + p = FPSTR(HTTP_INFO_apip); + p.replace(FPSTR(T_1),WiFi.softAPIP().toString()); + } + else if(id==F("apmac")){ + p = FPSTR(HTTP_INFO_apmac); + p.replace(FPSTR(T_1),(String)WiFi.softAPmacAddress()); + } + #ifdef ESP32 + else if(id==F("aphost")){ + p = FPSTR(HTTP_INFO_aphost); + p.replace(FPSTR(T_1),WiFi.softAPgetHostname()); + } + #endif + else if(id==F("apssid")){ + p = FPSTR(HTTP_INFO_apssid); + p.replace(FPSTR(T_1),htmlEntities((String)WiFi_SSID())); + } + else if(id==F("apbssid")){ + p = FPSTR(HTTP_INFO_apbssid); + p.replace(FPSTR(T_1),(String)WiFi.BSSIDstr()); + } + else if(id==F("staip")){ + p = FPSTR(HTTP_INFO_staip); + p.replace(FPSTR(T_1),WiFi.localIP().toString()); + } + else if(id==F("stagw")){ + p = FPSTR(HTTP_INFO_stagw); + p.replace(FPSTR(T_1),WiFi.gatewayIP().toString()); + } + else if(id==F("stasub")){ + p = FPSTR(HTTP_INFO_stasub); + p.replace(FPSTR(T_1),WiFi.subnetMask().toString()); + } + else if(id==F("dnss")){ + p = FPSTR(HTTP_INFO_dnss); + p.replace(FPSTR(T_1),WiFi.dnsIP().toString()); + } + else if(id==F("host")){ + p = FPSTR(HTTP_INFO_host); + #ifdef ESP32 + p.replace(FPSTR(T_1),WiFi.getHostname()); + #else + p.replace(FPSTR(T_1),WiFi.hostname()); + #endif + } + else if(id==F("stamac")){ + p = FPSTR(HTTP_INFO_stamac); + p.replace(FPSTR(T_1),WiFi.macAddress()); + } + else if(id==F("conx")){ + p = FPSTR(HTTP_INFO_conx); + p.replace(FPSTR(T_1),WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); + } + #ifdef ESP8266 + else if(id==F("autoconx")){ + p = FPSTR(HTTP_INFO_autoconx); + p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); + } + #endif + #ifdef ESP32 + else if(id==F("temp")){ + // temperature is not calibrated, varying large offsets are present, use for relative temp changes only + p = FPSTR(HTTP_INFO_temp); + p.replace(FPSTR(T_1),(String)temperatureRead()); + p.replace(FPSTR(T_2),(String)((temperatureRead()+32)*1.8)); + } + #endif + return p; +} + +/** + * HTTPD CALLBACK root or redirect to captive portal + */ +void WiFiManager::handleExit() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Exit")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleexit)); // @token titleexit + page += FPSTR(S_exiting); // @token exiting + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + abort = true; +} + +/** + * HTTPD CALLBACK reset page + */ +void WiFiManager::handleReset() { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Reset")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titlereset)); //@token titlereset + page += FPSTR(S_resetting); //@token resetting + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + + DEBUG_WM(F("RESETTING ESP")); + delay(1000); + reboot(); +} + +/** + * HTTPD CALLBACK erase page + */ + +// void WiFiManager::handleErase() { +// handleErase(false); +// } +void WiFiManager::handleErase(boolean opt) { + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Erase")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase + + bool ret = erase(opt); + + if(ret) page += FPSTR(S_resetting); // @token resetting + else { + page += FPSTR(S_error); // @token erroroccur + DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFi EraseConfig failed")); + } + + page += FPSTR(HTTP_END); + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); + + if(ret){ + delay(2000); + DEBUG_WM(F("RESETTING ESP")); + reboot(); + } +} + +/** + * HTTPD CALLBACK 404 + */ +void WiFiManager::handleNotFound() { + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + handleRequest(); + String message = FPSTR(S_notfound); // @token notfound + message += FPSTR(S_uri); // @token uri + message += server->uri(); + message += FPSTR(S_method); // @token method + message += ( server->method() == HTTP_GET ) ? FPSTR(S_GET) : FPSTR(S_POST); + message += FPSTR(S_args); // @token args + message += server->args(); + message += F("\n"); + + for ( uint8_t i = 0; i < server->args(); i++ ) { + message += " " + server->argName ( i ) + ": " + server->arg ( i ) + "\n"; + } + server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); + server->sendHeader(F("Pragma"), F("no-cache")); + server->sendHeader(F("Expires"), F("-1")); + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(message.length())); + server->send ( 404, FPSTR(HTTP_HEAD_CT2), message ); +} + +/** + * HTTPD redirector + * Redirect to captive portal if we got a request for another domain. + * Return true in that case so the page handler do not try to handle the request again. + */ +boolean WiFiManager::captivePortal() { + DEBUG_WM(DEBUG_DEV,"-> " + server->hostHeader()); + + if(!_enableCaptivePortal) return false; // skip redirections, @todo maybe allow redirection even when no cp ? might be useful + + String serverLoc = toStringIp(server->client().localIP()); + if(_httpPort != 80) serverLoc += ":" + (String)_httpPort; // add port if not default + bool doredirect = serverLoc != server->hostHeader(); // redirect if hostheader not server ip, prevent redirect loops + // doredirect = !isIp(server->hostHeader()) // old check + + if (doredirect) { + DEBUG_WM(DEBUG_VERBOSE,F("<- Request redirected to captive portal")); + server->sendHeader(F("Location"), (String)F("http://") + serverLoc, true); + server->send ( 302, FPSTR(HTTP_HEAD_CT2), ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + server->client().stop(); // Stop is needed because we sent no content length + return true; + } + return false; +} + +void WiFiManager::stopCaptivePortal(){ + _enableCaptivePortal= false; + // @todo maybe disable configportaltimeout(optional), or just provide callback for user +} + +void WiFiManager::handleClose(){ + stopCaptivePortal(); + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP close")); + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleclose)); // @token titleclose + page += FPSTR(S_closing); // @token closing + server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); + server->send(200, FPSTR(HTTP_HEAD_CT), page); +} + +void WiFiManager::reportStatus(String &page){ + updateConxResult(WiFi.status()); + String str; + if (WiFi_SSID() != ""){ + if (WiFi.status()==WL_CONNECTED){ + str = FPSTR(HTTP_STATUS_ON); + str.replace(FPSTR(T_i),WiFi.localIP().toString()); + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + } + else { + str = FPSTR(HTTP_STATUS_OFF); + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + if(_lastconxresult == WL_STATION_WRONG_PASSWORD){ + // wrong password + str.replace(FPSTR(T_c),"D"); // class + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFPW)); + } + else if(_lastconxresult == WL_NO_SSID_AVAIL){ + // connect failed, or ap not found + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFNOAP)); + } + else if(_lastconxresult == WL_CONNECT_FAILED){ + // connect failed + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFFAIL)); + } + else{ + str.replace(FPSTR(T_c),""); + str.replace(FPSTR(T_r),""); + } + } + } + else { + str = FPSTR(HTTP_STATUS_NONE); + } + page += str; +} + +// PUBLIC + +// METHODS + +/** + * reset wifi settings, clean stored ap password + */ + +/** + * [stopConfigPortal description] + * @return {[type]} [description] + */ +bool WiFiManager::stopConfigPortal(){ + if(_configPortalIsBlocking){ + abort = true; + return true; + } + return shutdownConfigPortal(); +} + +/** + * disconnect + * @access public + * @since $dev + * @return bool success + */ +bool WiFiManager::disconnect(){ + if(WiFi.status() != WL_CONNECTED){ + DEBUG_WM(DEBUG_VERBOSE,"Disconnecting: Not connected"); + return false; + } + DEBUG_WM("Disconnecting"); + return WiFi_Disconnect(); +} + +/** + * reboot the device + * @access public + */ +void WiFiManager::reboot(){ + DEBUG_WM("Restarting"); + ESP.restart(); +} + +/** + * reboot the device + * @access public + */ +bool WiFiManager::erase(){ + return erase(false); +} + +bool WiFiManager::erase(bool opt){ + DEBUG_WM("Erasing"); + + #if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) + // if opt true, do nvs erase + if(opt){ + DEBUG_WM("Erasing NVS"); + esp_err_t err; + err = nvs_flash_init(); + DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_init: ",err!=ESP_OK ? (String)err : "Success"); + err = nvs_flash_erase(); + DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_erase: ", err!=ESP_OK ? (String)err : "Success"); + return err == ESP_OK; + } + #elif defined(ESP8266) && defined(spiffs_api_h) + if(opt){ + bool ret = false; + if(SPIFFS.begin()){ + DEBUG_WM("Erasing SPIFFS"); + bool ret = SPIFFS.format(); + DEBUG_WM(DEBUG_VERBOSE,"spiffs erase: ",ret ? "Success" : "ERROR"); + } else DEBUG_WM("[ERROR] Could not start SPIFFS"); + return ret; + } + #else + (void)opt; + #endif + + DEBUG_WM("Erasing WiFi Config"); + return WiFi_eraseConfig(); +} + +/** + * [resetSettings description] + * ERASES STA CREDENTIALS + * @access public + */ +void WiFiManager::resetSettings() { + DEBUG_WM(F("resetSettings")); + WiFi_enableSTA(true,true); // must be sta to disconnect erase + + if (_resetcallback != NULL) + _resetcallback(); + + #ifdef ESP32 + WiFi.disconnect(true,true); + #else + WiFi.persistent(true); + WiFi.disconnect(true); + WiFi.persistent(false); + #endif + DEBUG_WM(F("SETTINGS ERASED")); +} + +// SETTERS + +/** + * [setTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setTimeout(unsigned long seconds) { + setConfigPortalTimeout(seconds); +} + +/** + * [setConfigPortalTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { + _configPortalTimeout = seconds * 1000; +} + +/** + * [setConnectTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setConnectTimeout(unsigned long seconds) { + _connectTimeout = seconds * 1000; +} +/** + * toggle _cleanconnect, always disconnect before connecting + * @param {[type]} bool enable [description] + */ +void WiFiManager::setCleanConnect(bool enable){ + _cleanConnect = enable; +} + +/** + * [setConnectTimeout description + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setSaveConnectTimeout(unsigned long seconds) { + _saveTimeout = seconds * 1000; +} + +/** + * [setDebugOutput description] + * @access public + * @param {[type]} boolean debug [description] + */ +void WiFiManager::setDebugOutput(boolean debug) { + _debug = debug; + if(_debug && _debugLevel == DEBUG_DEV) debugPlatformInfo(); +} + +/** + * [setAPStaticIPConfig description] + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + */ +void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { + _ap_static_ip = ip; + _ap_static_gw = gw; + _ap_static_sn = sn; +} + +/** + * [setSTAStaticIPConfig description] + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + */ +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { + _sta_static_ip = ip; + _sta_static_gw = gw; + _sta_static_sn = sn; +} + +/** + * [setSTAStaticIPConfig description] + * @since $dev + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + * @param {[type]} IPAddress dns [description] + */ +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns) { + setSTAStaticIPConfig(ip,gw,sn); + _sta_static_dns = dns; +} + +/** + * [setMinimumSignalQuality description] + * @access public + * @param {[type]} int quality [description] + */ +void WiFiManager::setMinimumSignalQuality(int quality) { + _minimumQuality = quality; +} + +/** + * [setBreakAfterConfig description] + * @access public + * @param {[type]} boolean shouldBreak [description] + */ +void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { + _shouldBreakAfterConfig = shouldBreak; +} + +/** + * setAPCallback, set a callback when softap is started + * @access public + * @param {[type]} void (*func)(WiFiManager* wminstance) + */ +void WiFiManager::setAPCallback( std::function func ) { + _apcallback = func; +} + +/** + * setWebServerCallback, set a callback after webserver is reset, and before routes are setup + * if we set webserver handlers before wm, they are used and wm is not by esp webserver + * on events cannot be overrided once set, and are not mutiples + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setWebServerCallback( std::function func ) { + _webservercallback = func; +} + +/** + * setSaveConfigCallback, set a save config callback after closing configportal + * @note calls only if wifi is saved or changed, or setBreakAfterConfig(true) + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setSaveConfigCallback( std::function func ) { + _savewificallback = func; +} + +/** + * setConfigResetCallback, set a callback to occur when a resetSettings() occurs + * @access public + * @param {[type]} void(*func)(void) + */ +void WiFiManager::setConfigResetCallback( std::function func ) { + _resetcallback = func; +} + +/** + * setSaveParamsCallback, set a save params callback on params save in wifi or params pages + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setSaveParamsCallback( std::function func ) { + _saveparamscallback = func; +} + +/** + * setPreSaveConfigCallback, set a callback to fire before saving wifi or params + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreSaveConfigCallback( std::function func ) { + _presavecallback = func; +} + +/** + * set custom head html + * custom element will be added to head, eg. new style tag etc. + * @access public + * @param char element + */ +void WiFiManager::setCustomHeadElement(const char* element) { + _customHeadElement = element; +} + +/** + * toggle wifiscan hiding of duplicate ssid names + * if this is false, wifiscan will remove duplicat Access Points - defaut true + * @access public + * @param boolean removeDuplicates [true] + */ +void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) { + _removeDuplicateAPs = removeDuplicates; +} + +/** + * toggle configportal blocking loop + * if enabled, then the configportal will enter a blocking loop and wait for configuration + * if disabled use with process() to manually process webserver + * @since $dev + * @access public + * @param boolean shoudlBlock [false] + */ +void WiFiManager::setConfigPortalBlocking(boolean shoudlBlock) { + _configPortalIsBlocking = shoudlBlock; +} + +/** + * toggle restore persistent, track internally + * sets ESP wifi.persistent so we can remember it and restore user preference on destruct + * there is no getter in esp8266 platform prior to https://github.com/esp8266/Arduino/pull/3857 + * @since $dev + * @access public + * @param boolean persistent [true] + */ +void WiFiManager::setRestorePersistent(boolean persistent) { + _userpersistent = persistent; + if(!persistent) DEBUG_WM(F("persistent is off")); +} + +/** + * toggle showing static ip form fields + * if enabled, then the static ip, gateway, subnet fields will be visible, even if not set in code + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowStaticFields(boolean alwaysShow){ + if(_disableIpFields) _staShowStaticFields = alwaysShow ? 1 : -1; + else _staShowStaticFields = alwaysShow ? 1 : 0; +} + +/** + * toggle showing dns fields + * if enabled, then the dns1 field will be visible, even if not set in code + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowDnsFields(boolean alwaysShow){ + if(_disableIpFields) _staShowDns = alwaysShow ? 1 : -1; + _staShowDns = alwaysShow ? 1 : 0; +} + +/** + * toggle showing password in wifi password field + * if not enabled, placeholder will be S_passph + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowPassword(boolean show){ + _showPassword = show; +} + +/** + * toggle captive portal + * if enabled, then devices that use captive portal checks will be redirected to root + * if not you will automatically have to navigate to ip [192.168.4.1] + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setCaptivePortalEnable(boolean enabled){ + _enableCaptivePortal = enabled; +} + +/** + * toggle wifi autoreconnect policy + * if enabled, then wifi will autoreconnect automatically always + * On esp8266 we force this on when autoconnect is called, see notes + * On esp32 this is handled on SYSTEM_EVENT_STA_DISCONNECTED since it does not exist in core yet + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setWiFiAutoReconnect(boolean enabled){ + _wifiAutoReconnect = enabled; +} + +/** + * toggle configportal timeout wait for station client + * if enabled, then the configportal will start timeout when no stations are connected to softAP + * disabled by default as rogue stations can keep it open if there is no auth + * @since $dev + * @access public + * @param boolean enabled [false] + */ +void WiFiManager::setAPClientCheck(boolean enabled){ + _apClientCheck = enabled; +} + +/** + * toggle configportal timeout wait for web client + * if enabled, then the configportal will restart timeout when client requests come in + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setWebPortalClientCheck(boolean enabled){ + _webClientCheck = enabled; +} + +/** + * toggle wifiscan percentages or quality icons + * @since $dev + * @access public + * @param boolean enabled [false] + */ +void WiFiManager::setScanDispPerc(boolean enabled){ + _scanDispOptions = enabled; +} + +/** + * toggle configportal if autoconnect failed + * if enabled, then the configportal will be activated on autoconnect failure + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setEnableConfigPortal(boolean enable) +{ + _enableConfigPortal = enable; +} + + +/** + * set the hostname (dhcp client id) + * @since $dev + * @access public + * @param char* hostname 32 character hostname to use for sta+ap in esp32, sta in esp8266 + * @return bool false if hostname is not valid + */ +bool WiFiManager::setHostname(const char * hostname){ + //@todo max length 32 + _hostname = hostname; + return true; +} + +/** + * set the soft ao channel, ignored if channelsync is true and connected + * @param int32_t wifi channel, 0 to disable + */ +void WiFiManager::setWiFiAPChannel(int32_t channel){ + _apChannel = channel; +} + +/** + * set the soft ap hidden + * @param bool wifi ap hidden, default is false + */ +void WiFiManager::setWiFiAPHidden(bool hidden){ + _apHidden = hidden; +} + + +/** + * toggle showing erase wifi config button on info page + * @param boolean enabled + */ +void WiFiManager::setShowInfoErase(boolean enabled){ + _showInfoErase = enabled; +} + +/** + * set menu items and order + * if param is present in menu , params will be removed from wifi page automatically + * eg. + * const char * menu[] = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); + * @since $dev + * @param uint8_t menu[] array of menu ids + */ +void WiFiManager::setMenu(const char * menu[], uint8_t size){ + // DEBUG_WM(DEBUG_VERBOSE,"setmenu array"); + _menuIds.clear(); + for(size_t i = 0; i < size; i++){ + for(size_t j = 0; j < _nummenutokens; j++){ + if(menu[i] == _menutokens[j]){ + if((String)menu[i] == "param") _paramsInWifi = false; // param auto flag + _menuIds.push_back(j); + } + } + } + // DEBUG_WM(getMenuOut()); +} + +/** + * setMenu with vector + * eg. + * std::vector menu = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); + * tokens can be found in _menutokens array in strings_en.h + * @shiftIncrement $dev + * @param {[type]} std::vector& menu [description] + */ +void WiFiManager::setMenu(std::vector& menu){ + // DEBUG_WM(DEBUG_VERBOSE,"setmenu vector"); + _menuIds.clear(); + for(auto menuitem : menu ){ + for(size_t j = 0; j < _nummenutokens; j++){ + if(menuitem == _menutokens[j]){ + if((String)menuitem == "param") _paramsInWifi = false; // param auto flag + _menuIds.push_back(j); + } + } + } + // DEBUG_WM(getMenuOut()); +} + + +/** + * set params as sperate page not in wifi + * NOT COMPATIBLE WITH setMenu! + * @todo scan menuids and insert param after wifi or something, same for ota + * @param bool enable + * @since $dev + */ +void WiFiManager::setParamsPage(bool enable){ + _paramsInWifi = !enable; + setMenu(enable ? _menuIdsParams : _menuIdsDefault); +} + +// GETTERS + +/** + * get config portal AP SSID + * @since 0.0.1 + * @access public + * @return String the configportal ap name + */ +String WiFiManager::getConfigPortalSSID() { + return _apName; +} + +/** + * return the last known connection result + * logged on autoconnect and wifisave, can be used to check why failed + * get as readable string with getWLStatusString(getLastConxResult); + * @since $dev + * @access public + * @return bool return wl_status codes + */ +uint8_t WiFiManager::getLastConxResult(){ + return _lastconxresult; +} + +/** + * check if wifi has a saved ap or not + * @since $dev + * @access public + * @return bool true if a saved ap config exists + */ +bool WiFiManager::getWiFiIsSaved(){ + return WiFi_hasAutoConnect(); +} + +String WiFiManager::getDefaultAPName(){ + String hostString = String(WIFI_getChipId(),HEX); + hostString.toUpperCase(); + // char hostString[16] = {0}; + // sprintf(hostString, "%06X", ESP.getChipId()); + return _wifissidprefix + "_" + hostString; +} + +/** + * setCountry + * @since $dev + * @param String cc country code, must be defined in WiFiSetCountry, US, JP, CN + */ +void WiFiManager::setCountry(String cc){ + _wificountry = cc; +} + +/** + * setClass + * @param String str body class string + */ +void WiFiManager::setClass(String str){ + _bodyClass = str; +} + +void WiFiManager::setHttpPort(uint16_t port){ + _httpPort = port; +} + +// HELPERS + +/** + * getWiFiSSID + * @since $dev + * @param bool persistent + * @return String + */ +String WiFiManager::getWiFiSSID(bool persistent){ + return WiFi_SSID(persistent); +} + +/** + * getWiFiPass + * @since $dev + * @param bool persistent + * @return String + */ +String WiFiManager::getWiFiPass(bool persistent){ + return WiFi_psk(persistent); +} + +// DEBUG +// @todo fix DEBUG_WM(0,0); +template +void WiFiManager::DEBUG_WM(Generic text) { + DEBUG_WM(DEBUG_NOTIFY,text,""); +} + +template +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text) { + if(_debugLevel >= level) DEBUG_WM(level,text,""); +} + +template +void WiFiManager::DEBUG_WM(Generic text,Genericb textb) { + DEBUG_WM(DEBUG_NOTIFY,text,textb); +} + +template +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { + if(!_debug || _debugLevel < level) return; + + if(_debugLevel >= DEBUG_MAX){ + uint32_t free; + uint16_t max; + uint8_t frag; + #ifdef ESP8266 + ESP.getHeapStats(&free, &max, &frag); + _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); + #elif defined ESP32 + // total_free_bytes; ///< Total free bytes in the heap. Equivalent to multi_free_heap_size(). + // total_allocated_bytes; ///< Total bytes allocated to data in the heap. + // largest_free_block; ///< Size of largest free block in the heap. This is the largest malloc-able size. + // minimum_free_bytes; ///< Lifetime minimum free heap size. Equivalent to multi_minimum_free_heap_size(). + // allocated_blocks; ///< Number of (variable size) blocks allocated in the heap. + // free_blocks; ///< Number of (variable size) free blocks in the heap. + // total_blocks; ///< Total number of (variable size) blocks in the heap. + multi_heap_info_t info; + heap_caps_get_info(&info, MALLOC_CAP_INTERNAL); + free = info.total_free_bytes; + max = info.largest_free_block; + frag = 100 - (max * 100) / free; + _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); + #endif + } + _debugPort.print("*WM: "); + if(_debugLevel == DEBUG_DEV) _debugPort.print("["+(String)level+"] "); + _debugPort.print(text); + if(textb){ + _debugPort.print(" "); + _debugPort.print(textb); + } + _debugPort.println(); +} + +/** + * [debugSoftAPConfig description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::debugSoftAPConfig(){ + wifi_country_t country; + + #ifdef ESP8266 + softap_config config; + wifi_softap_get_config(&config); + wifi_get_country(&country); + #elif defined(ESP32) + wifi_config_t conf_config; + esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK + wifi_ap_config_t config = conf_config.ap; + esp_wifi_get_country(&country); + #endif + + DEBUG_WM(F("SoftAP Configuration")); + DEBUG_WM(FPSTR(D_HR)); + DEBUG_WM(F("ssid: "),(char *) config.ssid); + DEBUG_WM(F("password: "),(char *) config.password); + DEBUG_WM(F("ssid_len: "),config.ssid_len); + DEBUG_WM(F("channel: "),config.channel); + DEBUG_WM(F("authmode: "),config.authmode); + DEBUG_WM(F("ssid_hidden: "),config.ssid_hidden); + DEBUG_WM(F("max_connection: "),config.max_connection); + DEBUG_WM(F("country: "),(String)country.cc); + DEBUG_WM(F("beacon_interval: "),(String)config.beacon_interval + "(ms)"); + DEBUG_WM(FPSTR(D_HR)); +} + +/** + * [debugPlatformInfo description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::debugPlatformInfo(){ + #ifdef ESP8266 + system_print_meminfo(); + DEBUG_WM(F("getCoreVersion(): "),ESP.getCoreVersion()); + DEBUG_WM(F("system_get_sdk_version(): "),system_get_sdk_version()); + DEBUG_WM(F("system_get_boot_version():"),system_get_boot_version()); + DEBUG_WM(F("getFreeHeap(): "),(String)ESP.getFreeHeap()); + #elif defined(ESP32) + size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); + DEBUG_WM("Free heap: ", ESP.getFreeHeap()); + DEBUG_WM("ESP SDK version: ", ESP.getSdkVersion()); + // esp_chip_info_t chipInfo; + // esp_chip_info(&chipInfo); + // DEBUG_WM("Chip Info: Model: ",chipInfo.model); + // DEBUG_WM("Chip Info: Cores: ",chipInfo.cores); + // DEBUG_WM("Chip Info: Rev: ",chipInfo.revision); + // DEBUG_WM(printf("Chip Info: Model: %d, cores: %d, revision: %d", chipInfo.model.c_str(), chipInfo.cores, chipInfo.revision)); + // DEBUG_WM("Chip Rev: ",(String)ESP.getChipRevision()); + // core version is not avail + #endif +} + +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) { + for (size_t i = 0; i < str.length(); i++) { + int c = str.charAt(i); + if (c != '.' && (c < '0' || c > '9')) { + return false; + } + } + return true; +} + +/** IP to String? */ +String WiFiManager::toStringIp(IPAddress ip) { + String res = ""; + for (int i = 0; i < 3; i++) { + res += String((ip >> (8 * i)) & 0xFF) + "."; + } + res += String(((ip >> 8 * 3)) & 0xFF); + return res; +} + +boolean WiFiManager::validApPassword(){ + // check that ap password is valid, return false + if (_apPassword == NULL) _apPassword = ""; + if (_apPassword != "") { + if (_apPassword.length() < 8 || _apPassword.length() > 63) { + DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); + _apPassword = ""; + return false; // @todo FATAL or fallback to empty ? + } + DEBUG_WM(DEBUG_VERBOSE,F("AccessPoint set password is VALID")); + DEBUG_WM(_apPassword); + } + return true; +} + +/** + * encode htmlentities + * @since $dev + * @param string str string to replace entities + * @return string encoded string + */ +String WiFiManager::htmlEntities(String str) { + str.replace("&","&"); + str.replace("<","<"); + str.replace(">",">"); + // str.replace("'","'"); + // str.replace("\"","""); + // str.replace("/": "/"); + // str.replace("`": "`"); + // str.replace("=": "="); +return str; +} + +/** + * [getWLStatusString description] + * @access public + * @param {[type]} uint8_t status [description] + * @return {[type]} [description] + */ +String WiFiManager::getWLStatusString(uint8_t status){ + if(status <= 7) return WIFI_STA_STATUS[status]; + return FPSTR(S_NA); +} + +String WiFiManager::encryptionTypeStr(uint8_t authmode) { + // DEBUG_WM("enc_tye: ",authmode); + return AUTH_MODE_NAMES[authmode]; +} + +String WiFiManager::getModeString(uint8_t mode){ + if(mode <= 3) return WIFI_MODES[mode]; + return FPSTR(S_NA); +} + +bool WiFiManager::WiFiSetCountry(){ + if(_wificountry == "") return false; // skip not set + bool ret = false; + #ifdef ESP32 + // @todo check if wifi is init, no idea how, doesnt seem to be exposed atm ( might be now! ) + if(WiFi.getMode() == WIFI_MODE_NULL); // exception if wifi not init! + else if(_wificountry == "US") ret = esp_wifi_set_country(&WM_COUNTRY_US) == ESP_OK; + else if(_wificountry == "JP") ret = esp_wifi_set_country(&WM_COUNTRY_JP) == ESP_OK; + else if(_wificountry == "CN") ret = esp_wifi_set_country(&WM_COUNTRY_CN) == ESP_OK; + else DEBUG_WM(DEBUG_ERROR,"[ERROR] country code not found"); + + #elif defined(ESP8266) + // if(WiFi.getMode() == WIFI_OFF); // exception if wifi not init! + if(_wificountry == "US") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_US); + else if(_wificountry == "JP") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_JP); + else if(_wificountry == "CN") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_CN); + else DEBUG_WM(DEBUG_ERROR,"[ERROR] country code not found"); + #endif + + if(ret) DEBUG_WM(DEBUG_VERBOSE,"esp_wifi_set_country: " + _wificountry); + else DEBUG_WM(DEBUG_ERROR,"[ERROR] esp_wifi_set_country failed"); + return ret; +} + +// set mode ignores WiFi.persistent +bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { + bool ret; + #ifdef ESP8266 + if((wifi_get_opmode() == (uint8) m ) && !persistent) { + return true; + } + ETS_UART_INTR_DISABLE(); + if(persistent) ret = wifi_set_opmode(m); + else ret = wifi_set_opmode_current(m); + ETS_UART_INTR_ENABLE(); + return ret; + #elif defined(ESP32) + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.mode(m); // @todo persistent check persistant mode , NI + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif +} +bool WiFiManager::WiFi_Mode(WiFiMode_t m) { + return WiFi_Mode(m,false); +} + +// sta disconnect without persistent +bool WiFiManager::WiFi_Disconnect() { + #ifdef ESP8266 + if((WiFi.getMode() & WIFI_STA) != 0) { + bool ret; + DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); + ETS_UART_INTR_DISABLE(); // @todo probably not needed + ret = wifi_station_disconnect(); + ETS_UART_INTR_ENABLE(); + return ret; + } + #elif defined(ESP32) + DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); + return WiFi.disconnect(); // not persistent atm + #endif + return false; +} + +// toggle STA without persistent +bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { + DEBUG_WM(DEBUG_DEV,F("WiFi station enable")); + #ifdef ESP8266 + WiFiMode_t newMode; + WiFiMode_t currentMode = WiFi.getMode(); + bool isEnabled = (currentMode & WIFI_STA) != 0; + if(enable) newMode = (WiFiMode_t)(currentMode | WIFI_STA); + else newMode = (WiFiMode_t)(currentMode & (~WIFI_STA)); + + if((isEnabled != enable) || persistent) { + if(enable) { + if(persistent) DEBUG_WM(DEBUG_DEV,F("enableSTA PERSISTENT ON")); + return WiFi_Mode(newMode,persistent); + } + else { + return WiFi_Mode(newMode,persistent); + } + } else { + return true; + } + #elif defined(ESP32) + bool ret; + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif +} +bool WiFiManager::WiFi_enableSTA(bool enable) { + return WiFi_enableSTA(enable,false); +} + +bool WiFiManager::WiFi_eraseConfig() { + #ifdef ESP8266 + #ifndef WM_FIXERASECONFIG + return ESP.eraseConfig(); + #else + // erase config BUG replacement + // https://github.com/esp8266/Arduino/pull/3635 + const size_t cfgSize = 0x4000; + size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; + + for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) { + if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) { + return false; + } + } + return true; + #endif + #elif defined(ESP32) + bool ret; + WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! + WiFi.persistent(true); + ret = WiFi.disconnect(true,true); + WiFi.persistent(false); + return ret; + #endif +} + +uint8_t WiFiManager::WiFi_softap_num_stations(){ + #ifdef ESP8266 + return wifi_softap_get_station_num(); + #elif defined(ESP32) + return WiFi.softAPgetStationNum(); + #endif +} + +bool WiFiManager::WiFi_hasAutoConnect(){ + return WiFi_SSID(true) != ""; +} + +String WiFiManager::WiFi_SSID(bool persistent) const{ + + #ifdef ESP8266 + struct station_config conf; + if(persistent) wifi_station_get_config_default(&conf); + else wifi_station_get_config(&conf); + + char tmp[33]; //ssid can be up to 32chars, => plus null term + memcpy(tmp, conf.ssid, sizeof(conf.ssid)); + tmp[32] = 0; //nullterm in case of 32 char ssid + return String(reinterpret_cast(tmp)); + + #elif defined(ESP32) + if(persistent){ + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.ssid)); + } + else { + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_ap_record_t info; + if(!esp_wifi_sta_get_ap_info(&info)) { + return String(reinterpret_cast(info.ssid)); + } + return String(); + } + #endif +} + +String WiFiManager::WiFi_psk(bool persistent) const { + #ifdef ESP8266 + struct station_config conf; + + if(persistent) wifi_station_get_config_default(&conf); + else wifi_station_get_config(&conf); + + char tmp[65]; //psk is 64 bytes hex => plus null term + memcpy(tmp, conf.password, sizeof(conf.password)); + tmp[64] = 0; //null term in case of 64 byte psk + return String(reinterpret_cast(tmp)); + + #elif defined(ESP32) + // only if wifi is init + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.password)); + #endif +} + +#ifdef ESP32 +void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ + if(!_hasBegun){ + // DEBUG_WM(DEBUG_VERBOSE,"[ERROR] WiFiEvent, not ready"); + Serial.println("[ERROR] wm not ready"); + return; + } + // DEBUG_WM(DEBUG_VERBOSE,"[EVENT]",event); + if(event == SYSTEM_EVENT_STA_DISCONNECTED){ + DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON:",info.disconnected.reason); + if(info.disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.disconnected.reason == WIFI_REASON_AUTH_FAIL){ + _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail + } else _lastconxresulttmp = WiFi.status(); + if(info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON: NO_AP_FOUND"); + #ifdef esp32autoreconnect + DEBUG_WM(DEBUG_VERBOSE,"[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); + WiFi.reconnect(); + #endif + } + else if(event == SYSTEM_EVENT_SCAN_DONE){ + uint16_t scans = WiFi.scanComplete(); + WiFi_scanComplete(scans); + } +} +#endif + +void WiFiManager::WiFi_autoReconnect(){ + #ifdef ESP8266 + WiFi.setAutoReconnect(_wifiAutoReconnect); + #elif defined(ESP32) + // if(_wifiAutoReconnect){ + // @todo move to seperate method, used for event listener now + DEBUG_WM(DEBUG_VERBOSE,"ESP32 event handler enabled"); + using namespace std::placeholders; + wm_event_id = WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); + // } + #endif +} + +#endif diff --git a/lib/WiFiManager-2.0.3-alpha/WiFiManager.h b/lib/WiFiManager-2.0.3-alpha/WiFiManager.h new file mode 100644 index 00000000..0834390a --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/WiFiManager.h @@ -0,0 +1,616 @@ +/** + * WiFiManager.h + * + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ + + +#ifndef WiFiManager_h +#define WiFiManager_h + +#if defined(ESP8266) || defined(ESP32) + +#ifdef ESP8266 +#include +#endif + +#include + +// #define WM_MDNS // includes MDNS, also set MDNS with sethostname +// #define WM_FIXERASECONFIG // use erase flash fix +// #define WM_ERASE_NVS // esp32 erase(true) will erase NVS +// #define WM_RTC // esp32 info page will include reset reasons + +// #define WM_JSTEST // build flag for enabling js xhr tests +// #define WIFI_MANAGER_OVERRIDE_STRINGS // build flag for using own strings include + +#ifdef ARDUINO_ESP8266_RELEASE_2_3_0 +#warning "ARDUINO_ESP8266_RELEASE_2_3_0, some WM features disabled" +#define WM_NOASYNC // esp8266 no async scan wifi +#endif + +// #include "soc/efuse_reg.h" // include to add efuse chip rev to info, getChipRevision() is almost always the same though, so not sure why it matters. + +// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge, @DEPRECATED +// autoreconnect is WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 + +#define WM_WEBSERVERSHIM // use webserver shim lib + +#ifdef ESP8266 + + extern "C" { + #include "user_interface.h" + } + #include + #include + + #ifdef WM_MDNS + #include + #endif + + #define WIFI_getChipId() ESP.getChipId() + #define WM_WIFIOPEN ENC_TYPE_NONE + +#elif defined(ESP32) + + #include + #include + + #define WIFI_getChipId() (uint32_t)ESP.getEfuseMac() + #define WM_WIFIOPEN WIFI_AUTH_OPEN + + #ifndef WEBSERVER_H + #ifdef WM_WEBSERVERSHIM + #include + #else + #include + // Forthcoming official ? probably never happening + // https://github.com/esp8266/ESPWebServer + #endif + #endif + + #ifdef WM_ERASE_NVS + #include + #include + #endif + + #ifdef WM_MDNS + #include + #endif + + #ifdef WM_RTC + #include + #endif + +#else +#endif + +#include +#include +#include "strings_en.h" + +#ifndef WIFI_MANAGER_MAX_PARAMS + #define WIFI_MANAGER_MAX_PARAMS 5 // params will autoincrement and realloc by this amount when max is reached +#endif + +#define WFM_LABEL_BEFORE 1 +#define WFM_LABEL_AFTER 2 +#define WFM_NO_LABEL 0 + +class WiFiManagerParameter { + public: + /** + Create custom parameters that can be added to the WiFiManager setup web page + @id is used for HTTP queries and must not contain spaces nor other special characters + */ + WiFiManagerParameter(); + WiFiManagerParameter(const char *custom); + WiFiManagerParameter(const char *id, const char *label); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); + ~WiFiManagerParameter(); + // WiFiManagerParameter& operator=(const WiFiManagerParameter& rhs); + + const char *getID(); + const char *getValue(); + const char *getLabel(); + const char *getPlaceholder(); // @deprecated, use getLabel + int getValueLength(); + int getLabelPlacement(); + const char *getCustomHTML(); + void setValue(const char *defaultValue, int length); + + protected: + void init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); + + private: + WiFiManagerParameter& operator=(const WiFiManagerParameter&); + const char *_id; + const char *_label; + char *_value; + int _length; + int _labelPlacement; + const char *_customHTML; + friend class WiFiManager; +}; + + +class WiFiManager +{ + public: + WiFiManager(Stream& consolePort); + WiFiManager(); + ~WiFiManager(); + void WiFiManagerInit(); + + // auto connect to saved wifi, or custom, and start config portal on failures + boolean autoConnect(); + boolean autoConnect(char const *apName, char const *apPassword = NULL); + + //manually start the config portal, autoconnect does this automatically on connect failure + boolean startConfigPortal(); // auto generates apname + boolean startConfigPortal(char const *apName, char const *apPassword = NULL); + + //manually stop the config portal if started manually, stop immediatly if non blocking, flag abort if blocking + bool stopConfigPortal(); + + //manually start the web portal, autoconnect does this automatically on connect failure + void startWebPortal(); + + //manually stop the web portal if started manually + void stopWebPortal(); + + // Run webserver processing, if setConfigPortalBlocking(false) + boolean process(); + + // get the AP name of the config portal, so it can be used in the callback + String getConfigPortalSSID(); + int getRSSIasQuality(int RSSI); + + // erase wifi credentials + void resetSettings(); + + // reboot esp + void reboot(); + + // disconnect wifi, without persistent saving or erasing + bool disconnect(); + + // erase esp + bool erase(); + bool erase(bool opt); + + //adds a custom parameter, returns false on failure + bool addParameter(WiFiManagerParameter *p); + + //returns the list of Parameters + WiFiManagerParameter** getParameters(); + + // returns the Parameters Count + int getParametersCount(); + + // SET CALLBACKS + + //called after AP mode and config portal has started + void setAPCallback( std::function func ); + + //called after webserver has started + void setWebServerCallback( std::function func ); + + //called when settings reset have been triggered + void setConfigResetCallback( std::function func ); + + //called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) + void setSaveConfigCallback( std::function func ); + + //called when settings have been changed and connection was successful + void setSaveParamsCallback( std::function func ); + + //called when settings before have been changed and connection was successful + void setPreSaveConfigCallback( std::function func ); + + + //sets timeout before AP,webserver loop ends and exits even if there has been no setup. + //useful for devices that failed to connect at some point and got stuck in a webserver loop + //in seconds setConfigPortalTimeout is a new name for setTimeout, ! not used if setConfigPortalBlocking + void setConfigPortalTimeout(unsigned long seconds); + void setTimeout(unsigned long seconds); // @deprecated, alias + + //sets timeout for which to attempt connecting, useful if you get a lot of failed connects + void setConnectTimeout(unsigned long seconds); + + //sets timeout for which to attempt connecting on saves, useful if there are bugs in esp waitforconnectloop + void setSaveConnectTimeout(unsigned long seconds); + + // toggle debug output + void setDebugOutput(boolean debug); + + //set min quality percentage to include in scan, defaults to 8% if not specified + void setMinimumSignalQuality(int quality = 8); + + //sets a custom ip /gateway /subnet configuration + void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + + //sets config for a static IP + void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + + //sets config for a static IP with DNS + void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns); + + //if this is set, it will exit after config, even if connection is unsuccessful. + void setBreakAfterConfig(boolean shouldBreak); + + // if this is set, portal will be blocking and wait until save or exit, + // is false user must manually `process()` to handle config portal, + // setConfigPortalTimeout is ignored in this mode, user is responsible for closing configportal + void setConfigPortalBlocking(boolean shouldBlock); + + //if this is set, customise style + void setCustomHeadElement(const char* element); + + //if this is true, remove duplicated Access Points - defaut true + void setRemoveDuplicateAPs(boolean removeDuplicates); + + //setter for ESP wifi.persistent so we can remember it and restore user preference, as WIFi._persistent is protected + void setRestorePersistent(boolean persistent); + + //if true, always show static net inputs, IP, subnet, gateway, else only show if set via setSTAStaticIPConfig + void setShowStaticFields(boolean alwaysShow); + + //if true, always show static dns, esle only show if set via setSTAStaticIPConfig + void setShowDnsFields(boolean alwaysShow); + + // toggle showing the saved wifi password in wifi form, could be a security issue. + void setShowPassword(boolean show); + + //if false, disable captive portal redirection + void setCaptivePortalEnable(boolean enabled); + + //if false, timeout captive portal even if a STA client connected to softAP (false), suggest disabling if captiveportal is open + void setAPClientCheck(boolean enabled); + + //if true, reset timeout when webclient connects (true), suggest disabling if captiveportal is open + void setWebPortalClientCheck(boolean enabled); + + // if true, enable autoreconnecting + void setWiFiAutoReconnect(boolean enabled); + + // if true, wifiscan will show percentage instead of quality icons, until we have better templating + void setScanDispPerc(boolean enabled); + + // if true (default) then start the config portal from autoConnect if connection failed + void setEnableConfigPortal(boolean enable); + + // set a custom hostname, sets sta and ap dhcp client id for esp32, and sta for esp8266 + bool setHostname(const char * hostname); + + // show erase wifi onfig button on info page, true + void setShowInfoErase(boolean enabled); + + // set ap channel + void setWiFiAPChannel(int32_t channel); + + // set ap hidden + void setWiFiAPHidden(bool hidden); // default false + + // clean connect, always disconnect before connecting + void setCleanConnect(bool enable); // default false + + // set custom menu items and order, vector or arr + // see _menutokens for ids + void setMenu(std::vector& menu); + void setMenu(const char* menu[], uint8_t size); + + // add params to its own menu page and remove from wifi, NOT TO BE COMBINED WITH setMenu! + void setParamsPage(bool enable); + + // get last connection result, includes autoconnect and wifisave + uint8_t getLastConxResult(); + + // get a status as string + String getWLStatusString(uint8_t status); + + // get wifi mode as string + String getModeString(uint8_t mode); + + // check if the module has a saved ap to connect to + bool getWiFiIsSaved(); + + // helper to get saved ssid, if persistent get stored, else get current if connected + String getWiFiPass(bool persistent = false); + + // helper to get saved password, if persistent get stored, else get current if connected + String getWiFiSSID(bool persistent = false); + + // debug output the softap config + void debugSoftAPConfig(); + + // debug output platform info and versioning + void debugPlatformInfo(); + + // helper for html + String htmlEntities(String str); + + // set the country code for wifi settings, CN + void setCountry(String cc); + + // set body class (invert), may be used for hacking in alt classes in the future + void setClass(String str); + + // get default ap esp uses , esp_chipid etc + String getDefaultAPName(); + + // set port of webserver, 80 + void setHttpPort(uint16_t port); + + std::unique_ptr dnsServer; + + #if defined(ESP32) && defined(WM_WEBSERVERSHIM) + using WM_WebServer = WebServer; + #else + using WM_WebServer = ESP8266WebServer; + #endif + + std::unique_ptr server; + + private: + std::vector _menuIds; + std::vector _menuIdsParams = {"wifi","param","info","exit"}; + std::vector _menuIdsDefault = {"wifi","info","exit"}; + + // ip configs @todo struct ? + IPAddress _ap_static_ip; + IPAddress _ap_static_gw; + IPAddress _ap_static_sn; + IPAddress _sta_static_ip; + IPAddress _sta_static_gw; + IPAddress _sta_static_sn; + IPAddress _sta_static_dns; + + // defaults + const byte DNS_PORT = 53; + const byte HTTP_PORT = 80; + String _apName = "no-net"; + String _apPassword = ""; + String _ssid = ""; + String _pass = ""; + + // options flags + unsigned long _configPortalTimeout = 0; // ms close config portal loop if set (depending on _cp/webClientCheck options) + unsigned long _connectTimeout = 0; // ms stop trying to connect to ap if set + unsigned long _saveTimeout = 0; // ms stop trying to connect to ap on saves, in case bugs in esp waitforconnectresult + unsigned long _configPortalStart = 0; // ms config portal start time (updated for timeouts) + unsigned long _webPortalAccessed = 0; // ms last web access time + WiFiMode_t _usermode = WIFI_STA; // Default user mode + String _wifissidprefix = FPSTR(S_ssidpre); // auto apname prefix prefix+chipid + uint8_t _lastconxresult = WL_IDLE_STATUS; // store last result when doing connect operations + int _numNetworks = 0; // init index for numnetworks wifiscans + unsigned long _lastscan = 0; // ms for timing wifi scans + unsigned long _startscan = 0; // ms for timing wifi scans + int _cpclosedelay = 2000; // delay before wifisave, prevents captive portal from closing to fast. + bool _cleanConnect = false; // disconnect before connect in connectwifi, increases stability on connects + + bool _disableSTA = false; // disable sta when starting ap, always + bool _disableSTAConn = true; // disable sta when starting ap, if sta is not connected ( stability ) + bool _channelSync = false; // use same wifi sta channel when starting ap + int32_t _apChannel = 0; // channel to use for ap + bool _apHidden = false; // store softap hidden value + uint16_t _httpPort = 80; // port for webserver + + #ifdef ESP32 + wifi_event_id_t wm_event_id; + static uint8_t _lastconxresulttmp; // tmp var for esp32 callback + #endif + + #ifndef WL_STATION_WRONG_PASSWORD + uint8_t WL_STATION_WRONG_PASSWORD = 7; // @kludge define a WL status for wrong password + #endif + + // parameter options + int _minimumQuality = -1; // filter wifiscan ap by this rssi + int _staShowStaticFields = 0; // ternary 1=always show static ip fields, 0=only if set, -1=never(cannot change ips via web!) + int _staShowDns = 0; // ternary 1=always show dns, 0=only if set, -1=never(cannot change dns via web!) + boolean _removeDuplicateAPs = true; // remove dup aps from wifiscan + boolean _showPassword = false; // show or hide saved password on wifi form, might be a security issue! + boolean _shouldBreakAfterConfig = false; // stop configportal on save failure + boolean _configPortalIsBlocking = true; // configportal enters blocking loop + boolean _enableCaptivePortal = true; // enable captive portal redirection + boolean _userpersistent = true; // users preffered persistence to restore + boolean _wifiAutoReconnect = true; // there is no platform getter for this, we must assume its true and make it so + boolean _apClientCheck = false; // keep cp alive if ap have station + boolean _webClientCheck = true; // keep cp alive if web have client + boolean _scanDispOptions = false; // show percentage in scans not icons + boolean _paramsInWifi = true; // show custom parameters on wifi page + boolean _showInfoErase = true; // info page erase button + boolean _showBack = false; // show back button + boolean _enableConfigPortal = true; // use config portal if autoconnect failed + const char * _hostname = ""; // hostname for esp8266 for dhcp, and or MDNS + + const char* _customHeadElement = ""; // store custom head element html from user + String _bodyClass = ""; // class to add to body + + // internal options + + // wifiscan notes + // The following are background wifi scanning optimizations + // experimental to make scans faster, preload scans after starting cp, and visiting home page, so when you click wifi its already has your list + // ideally we would add async and xhr here but I am holding off on js requirements atm + // might be slightly buggy since captive portals hammer the home page, @todo workaround this somehow. + // cache time helps throttle this + // async enables asyncronous scans, so they do not block anything + // the refresh button bypasses cache + boolean _preloadwifiscan = true; // preload wifiscan if true + boolean _asyncScan = false; // perform wifi network scan async + unsigned int _scancachetime = 30000; // ms cache time for background scans + + boolean _disableIpFields = false; // modify function of setShow_X_Fields(false), forces ip fields off instead of default show if set, eg. _staShowStaticFields=-1 + + String _wificountry = ""; // country code, @todo define in strings lang + + // wrapper functions for handling setting and unsetting persistent for now. + bool esp32persistent = false; + bool _hasBegun = false; // flag wm loaded,unloaded + void _begin(); + void _end(); + + void setupConfigPortal(); + bool shutdownConfigPortal(); + bool setupHostname(bool restart); + +#ifdef NO_EXTRA_4K_HEAP + boolean _tryWPS = false; // try WPS on save failure, unsupported + void startWPS(); +#endif + + bool startAP(); + + uint8_t connectWifi(String ssid, String pass); + bool setSTAConfig(); + bool wifiConnectDefault(); + bool wifiConnectNew(String ssid, String pass); + + uint8_t waitForConnectResult(); + uint8_t waitForConnectResult(uint16_t timeout); + void updateConxResult(uint8_t status); + + // webserver handlers + void handleRoot(); + void handleWifi(boolean scan); + void handleWifiSave(); + void handleInfo(); + void handleReset(); + void handleNotFound(); + void handleExit(); + void handleClose(); + // void handleErase(); + void handleErase(boolean opt); + void handleParam(); + void handleWiFiStatus(); + void handleRequest(); + void handleParamSave(); + void doParamSave(); + + boolean captivePortal(); + boolean configPortalHasTimeout(); + uint8_t processConfigPortal(); + void stopCaptivePortal(); + + // wifi platform abstractions + bool WiFi_Mode(WiFiMode_t m); + bool WiFi_Mode(WiFiMode_t m,bool persistent); + bool WiFi_Disconnect(); + bool WiFi_enableSTA(bool enable); + bool WiFi_enableSTA(bool enable,bool persistent); + bool WiFi_eraseConfig(); + uint8_t WiFi_softap_num_stations(); + bool WiFi_hasAutoConnect(); + void WiFi_autoReconnect(); + String WiFi_SSID(bool persistent = false) const; + String WiFi_psk(bool persistent = false) const; + bool WiFi_scanNetworks(); + bool WiFi_scanNetworks(bool force,bool async); + bool WiFi_scanNetworks(unsigned int cachetime,bool async); + bool WiFi_scanNetworks(unsigned int cachetime); + void WiFi_scanComplete(int networksFound); + bool WiFiSetCountry(); + + #ifdef ESP32 + void WiFiEvent(WiFiEvent_t event, system_event_info_t info); + #endif + + // output helpers + String getParamOut(); + String getIpForm(String id, String title, String value); + String getScanItemOut(); + String getStaticOut(); + String getHTTPHead(String title); + String getMenuOut(); + //helpers + boolean isIp(String str); + String toStringIp(IPAddress ip); + boolean validApPassword(); + String encryptionTypeStr(uint8_t authmode); + void reportStatus(String &page); + String getInfoData(String id); + + // flags + boolean connect; + boolean abort; + boolean reset = false; + boolean configPortalActive = false; + boolean webPortalActive = false; + boolean portalTimeoutResult = false; + boolean portalAbortResult = false; + boolean storeSTAmode = true; // option store persistent STA mode in connectwifi + int timer = 0; + + // WiFiManagerParameter + int _paramsCount = 0; + int _max_params; + WiFiManagerParameter** _params = NULL; + + // debugging + typedef enum { + DEBUG_ERROR = 0, + DEBUG_NOTIFY = 1, // default stable + DEBUG_VERBOSE = 2, + DEBUG_DEV = 3, // default dev + DEBUG_MAX = 4 + } wm_debuglevel_t; + + boolean _debug = true; + + // build debuglevel support + // @todo use DEBUG_ESP_x? + #ifdef WM_DEBUG_LEVEL + uint8_t _debugLevel = (uint8_t)WM_DEBUG_LEVEL; + #else + uint8_t _debugLevel = DEBUG_DEV; // default debug level + #endif + + // @todo use DEBUG_ESP_PORT ? + #ifdef WM_DEBUG_PORT + Stream& _debugPort = WM_DEBUG_PORT; + #else + Stream& _debugPort = Serial; // debug output stream ref + #endif + + template + void DEBUG_WM(Generic text); + + template + void DEBUG_WM(wm_debuglevel_t level,Generic text); + template + void DEBUG_WM(Generic text,Genericb textb); + template + void DEBUG_WM(wm_debuglevel_t level, Generic text,Genericb textb); + + // callbacks + // @todo use cb list (vector) maybe event ids, allow no return value + std::function _apcallback; + std::function _webservercallback; + std::function _savewificallback; + std::function _presavecallback; + std::function _saveparamscallback; + std::function _resetcallback; + + template + auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { + 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 + +#endif \ No newline at end of file diff --git a/lib/WiFiManager-2.0.3-alpha/examples/Advanced/Advanced.ino b/lib/WiFiManager-2.0.3-alpha/examples/Advanced/Advanced.ino new file mode 100644 index 00000000..6e4ff734 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/Advanced/Advanced.ino @@ -0,0 +1,134 @@ +/** + * WiFiManager advanced demo, contains advanced configurartion options + * Implements TRIGGEN_PIN button press, press for ondemand configportal, hold for 3 seconds for reset settings. + */ +#include // https://github.com/tzapu/WiFiManager + +#define TRIGGER_PIN 0 + +WiFiManager wm; // global wm instance +WiFiManagerParameter custom_field; // global param ( for non blocking w params ) + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + Serial.begin(115200); + Serial.setDebugOutput(true); + delay(3000); + Serial.println("\n Starting"); + + pinMode(TRIGGER_PIN, INPUT); + + // wm.resetSettings(); // wipe settings + + // add a custom input field + int customFieldLength = 40; + + + // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\""); + + // test custom html input type(checkbox) + // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\" type=\"checkbox\""); // custom html type + + // test custom html(radio) + const char* custom_radio_str = "
One
Two
Three"; + new (&custom_field) WiFiManagerParameter(custom_radio_str); // custom html input + + wm.addParameter(&custom_field); + wm.setSaveParamsCallback(saveParamCallback); + + // custom menu via array or vector + // + // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (sep is seperator) (if param is in menu, params will not show up in wifi page!) + // const char* menu[] = {"wifi","info","param","sep","restart","exit"}; + // wm.setMenu(menu,6); + std::vector menu = {"wifi","info","param","sep","restart","exit"}; + wm.setMenu(menu); + + // set dark theme + wm.setClass("invert"); + + + //set static ip + // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn + // wm.setShowStaticFields(true); // force show static ip fields + // wm.setShowDnsFields(true); // force show dns field always + + // wm.setConnectTimeout(20); // how long to try to connect for before continuing + wm.setConfigPortalTimeout(30); // auto close configportal after n seconds + // wm.setCaptivePortalEnable(false); // disable captive portal redirection + // wm.setAPClientCheck(true); // avoid timeout if client connected to softap + + // wifi scan settings + // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) + // wm.setMinimumSignalQuality(20); // set min RSSI (percentage) to show in scans, null = 8% + // wm.setShowInfoErase(false); // do not show erase button on info page + // wm.setScanDispPerc(true); // show RSSI as percentage not graph icons + + // wm.setBreakAfterConfig(true); // always exit configportal even if wifi save fails + + bool res; + // res = wm.autoConnect(); // auto generated AP name from chipid + // res = wm.autoConnect("AutoConnectAP"); // anonymous ap + res = wm.autoConnect("AutoConnectAP","password"); // password protected ap + + if(!res) { + Serial.println("Failed to connect or hit timeout"); + // ESP.restart(); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } +} + +void checkButton(){ + // check for button press + if ( digitalRead(TRIGGER_PIN) == LOW ) { + // poor mans debounce/press-hold, code not ideal for production + delay(50); + if( digitalRead(TRIGGER_PIN) == LOW ){ + Serial.println("Button Pressed"); + // still holding button for 3000 ms, reset settings, code not ideaa for production + delay(3000); // reset delay hold + if( digitalRead(TRIGGER_PIN) == LOW ){ + Serial.println("Button Held"); + Serial.println("Erasing Config, restarting"); + wm.resetSettings(); + ESP.restart(); + } + + // start portal w delay + Serial.println("Starting config portal"); + wm.setConfigPortalTimeout(120); + + if (!wm.startConfigPortal("OnDemandAP","password")) { + Serial.println("failed to connect or hit timeout"); + delay(3000); + // ESP.restart(); + } else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + } + } +} + + +String getParam(String name){ + //read parameter from server, for customhmtl input + String value; + if(wm.server->hasArg(name)) { + value = wm.server->arg(name); + } + return value; +} + +void saveParamCallback(){ + Serial.println("[CALLBACK] saveParamCallback fired"); + Serial.println("PARAM customfieldid = " + getParam("customfieldid")); +} + +void loop() { + checkButton(); + // put your main code here, to run repeatedly: +} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino new file mode 100644 index 00000000..fea3287a --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -0,0 +1,175 @@ +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager +#include // https://github.com/bblanchon/ArduinoJson + +#ifdef ESP32 + #include +#endif + +//define your default values here, if there are different values in config.json, they are overwritten. +char mqtt_server[40]; +char mqtt_port[6] = "8080"; +char api_token[32] = "YOUR_API_TOKEN"; + +//default custom static IP +char static_ip[16] = "10.0.1.56"; +char static_gw[16] = "10.0.1.1"; +char static_sn[16] = "255.255.255.0"; + +//flag for saving data +bool shouldSaveConfig = false; + +//callback notifying us of the need to save config +void saveConfigCallback () { + Serial.println("Should save config"); + shouldSaveConfig = true; +} + +void setupSpiffs(){ + //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); + DynamicJsonBuffer 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(api_token, json["api_token"]); + + // if(json["ip"]) { + // Serial.println("setting custom ip from config"); + // strcpy(static_ip, json["ip"]); + // strcpy(static_gw, json["gateway"]); + // strcpy(static_sn, json["subnet"]); + // Serial.println(static_ip); + // } else { + // Serial.println("no custom ip in config"); + // } + + } else { + Serial.println("failed to load json config"); + } + } + } + } else { + Serial.println("failed to mount FS"); + } + //end read +} + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + + setupSpiffs(); + + // WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + //set config save notify callback + wm.setSaveConfigCallback(saveConfigCallback); + + // setup custom parameters + // + // The extra parameters to be configured (can be either global or just in the setup) + // After connecting, parameter.getValue() will get you the configured value + // id/name placeholder/prompt default length + WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); + WiFiManagerParameter custom_api_token("api", "api token", "", 32); + + //add all your parameters here + wm.addParameter(&custom_mqtt_server); + wm.addParameter(&custom_mqtt_port); + wm.addParameter(&custom_api_token); + + // set static ip + // IPAddress _ip,_gw,_sn; + // _ip.fromString(static_ip); + // _gw.fromString(static_gw); + // _sn.fromString(static_sn); + // wm.setSTAStaticIPConfig(_ip, _gw, _sn); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + //here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous + //and goes into a blocking loop awaiting configuration + if (!wm.autoConnect("AutoConnectAP", "password")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + // if we still have not connected restart and try all over again + ESP.restart(); + delay(5000); + } + + // always start configportal for a little while + // wm.setConfigPortalTimeout(60); + // wm.startConfigPortal("AutoConnectAP","password"); + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + + //read updated parameters + strcpy(mqtt_server, custom_mqtt_server.getValue()); + strcpy(mqtt_port, custom_mqtt_port.getValue()); + strcpy(api_token, custom_api_token.getValue()); + + //save the custom parameters to FS + if (shouldSaveConfig) { + Serial.println("saving config"); + DynamicJsonBuffer jsonBuffer; + JsonObject& json = jsonBuffer.createObject(); + json["mqtt_server"] = mqtt_server; + json["mqtt_port"] = mqtt_port; + json["api_token"] = api_token; + + // json["ip"] = WiFi.localIP().toString(); + // json["gateway"] = WiFi.gatewayIP().toString(); + // json["subnet"] = WiFi.subnetMask().toString(); + + File configFile = SPIFFS.open("/config.json", "w"); + if (!configFile) { + Serial.println("failed to open config file for writing"); + } + + json.prettyPrintTo(Serial); + json.printTo(configFile); + configFile.close(); + //end save + shouldSaveConfig = false; + } + + Serial.println("local ip"); + Serial.println(WiFi.localIP()); + Serial.println(WiFi.gatewayIP()); + Serial.println(WiFi.subnetMask()); +} + +void loop() { + // put your main code here, to run repeatedly: + + +} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino b/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino new file mode 100644 index 00000000..6b1a7af7 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino @@ -0,0 +1,172 @@ +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager +#include // https://github.com/bblanchon/ArduinoJson + +#ifdef ESP32 + #include +#endif + +//define your default values here, if there are different values in config.json, they are overwritten. +char mqtt_server[40]; +char mqtt_port[6] = "8080"; +char api_token[32] = "YOUR_API_TOKEN"; + +//default custom static IP +char static_ip[16] = "10.0.1.56"; +char static_gw[16] = "10.0.1.1"; +char static_sn[16] = "255.255.255.0"; + +//flag for saving data +bool shouldSaveConfig = false; + +//callback notifying us of the need to save config +void saveConfigCallback () { + Serial.println("Should save config"); + shouldSaveConfig = true; +} + +void setupSpiffs(){ + //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); + DynamicJsonBuffer 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(api_token, json["api_token"]); + + if(json["ip"]) { + Serial.println("setting custom ip from config"); + strcpy(static_ip, json["ip"]); + strcpy(static_gw, json["gateway"]); + strcpy(static_sn, json["subnet"]); + Serial.println(static_ip); + } else { + Serial.println("no custom ip in config"); + } + + } else { + Serial.println("failed to load json config"); + } + } + } + } else { + Serial.println("failed to mount FS"); + } + //end read +} + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println(); + + setupSpiffs(); + + // WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + //set config save notify callback + wm.setSaveConfigCallback(saveConfigCallback); + + // setup custom parameters + // + // The extra parameters to be configured (can be either global or just in the setup) + // After connecting, parameter.getValue() will get you the configured value + // id/name placeholder/prompt default length + WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); + WiFiManagerParameter custom_api_token("api", "api token", "", 32); + + //add all your parameters here + wm.addParameter(&custom_mqtt_server); + wm.addParameter(&custom_mqtt_port); + wm.addParameter(&custom_api_token); + + // set static ip + IPAddress _ip,_gw,_sn; + _ip.fromString(static_ip); + _gw.fromString(static_gw); + _sn.fromString(static_sn); + wm.setSTAStaticIPConfig(_ip, _gw, _sn); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + //here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous + //and goes into a blocking loop awaiting configuration + if (!wm.autoConnect("AutoConnectAP", "password")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + // if we still have not connected restart and try all over again + ESP.restart(); + 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(api_token, custom_api_token.getValue()); + + //save the custom parameters to FS + if (shouldSaveConfig) { + Serial.println("saving config"); + DynamicJsonBuffer jsonBuffer; + JsonObject& json = jsonBuffer.createObject(); + json["mqtt_server"] = mqtt_server; + json["mqtt_port"] = mqtt_port; + json["api_token"] = api_token; + + json["ip"] = WiFi.localIP().toString(); + json["gateway"] = WiFi.gatewayIP().toString(); + json["subnet"] = WiFi.subnetMask().toString(); + + File configFile = SPIFFS.open("/config.json", "w"); + if (!configFile) { + Serial.println("failed to open config file for writing"); + } + + json.prettyPrintTo(Serial); + json.printTo(configFile); + configFile.close(); + //end save + shouldSaveConfig = false; + } + + Serial.println("local ip"); + Serial.println(WiFi.localIP()); + Serial.println(WiFi.gatewayIP()); + Serial.println(WiFi.subnetMask()); +} + +void loop() { + // put your main code here, to run repeatedly: + + +} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino b/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino new file mode 100644 index 00000000..ba468435 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino @@ -0,0 +1,71 @@ +// LED will blink when in config mode + +#include // https://github.com/tzapu/WiFiManager + +//for LED status +#include +Ticker ticker; + +#ifndef LED_BUILTIN +#define LED_BUILTIN 13 // ESP32 DOES NOT DEFINE LED_BUILTIN +#endif + +int LED = LED_BUILTIN; + +void tick() +{ + //toggle state + digitalWrite(LED, !digitalRead(LED)); // 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() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + Serial.begin(115200); + + //set led pin as output + pinMode(LED, OUTPUT); + // start ticker with 0.5 because we start in AP mode and try to connect + ticker.attach(0.6, tick); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + //reset settings - for testing + // wm.resetSettings(); + + //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode + wm.setAPCallback(configModeCallback); + + //fetches ssid and pass and tries to connect + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + if (!wm.autoConnect()) { + Serial.println("failed to connect and hit timeout"); + //reset and try again, or maybe put it to deep sleep + ESP.restart(); + delay(1000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + ticker.detach(); + //keep LED on + digitalWrite(LED, LOW); +} + +void loop() { + // put your main code here, to run repeatedly: + +} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/Basic/Basic.ino b/lib/WiFiManager-2.0.3-alpha/examples/Basic/Basic.ino new file mode 100644 index 00000000..daaee37f --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/Basic/Basic.ino @@ -0,0 +1,41 @@ +#include // https://github.com/tzapu/WiFiManager + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + + // put your setup code here, to run once: + Serial.begin(115200); + + // WiFi.mode(WiFi_STA); // it is a good practice to make sure your code sets wifi mode how you want it. + + //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + + // Automatically connect using saved credentials, + // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"), + // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect()) + // then goes into a blocking loop awaiting configuration and will return success result + + bool res; + // res = wm.autoConnect(); // auto generated AP name from chipid + // res = wm.autoConnect("AutoConnectAP"); // anonymous ap + res = wm.autoConnect("AutoConnectAP","password"); // password protected ap + + if(!res) { + Serial.println("Failed to connect"); + // ESP.restart(); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + +} + +void loop() { + // put your main code here, to run repeatedly: + +} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/lib/WiFiManager-2.0.3-alpha/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino new file mode 100644 index 00000000..28d14472 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -0,0 +1,347 @@ +/** + * This is a kind of unit test for DEV for now + * It contains many of the public methods + * + */ +#include // https://github.com/tzapu/WiFiManager +#include +#include + +#define USEOTA +// enable OTA +#ifdef USEOTA +#include +#include +#endif + +const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; + +unsigned long mtime = 0; + + + +WiFiManager wm; + +// TEST OPTION FLAGS +bool TEST_CP = true; // always start the configportal, even if ap found +int TESP_CP_TIMEOUT = 90; // test cp timeout + +bool TEST_NET = true; // do a network test after connect, (gets ntp time) +bool ALLOWONDEMAND = true; // enable on demand +int ONDDEMANDPIN = 0; // gpio for button + + +// char ssid[] = "*************"; // your network SSID (name) +// char pass[] = "********"; // your network password + +// OLED TEST , ssd1306 +// #define WM_OLED +#ifdef WM_OLED +#include +#include +#include +#define SCREEN_WIDTH 128 // OLED display width, in pixels +#define SCREEN_HEIGHT 32 // OLED display height, in pixels + +// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) +#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) +Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); +#endif + +void saveWifiCallback(){ + Serial.println("[CALLBACK] saveCallback fired"); +} + +//gets called when WiFiManager enters configuration mode +void configModeCallback (WiFiManager *myWiFiManager) { + Serial.println("[CALLBACK] configModeCallback fired"); + #ifdef ESP8266 + print_oled("WiFiManager Waiting\nIP: " + WiFi.softAPIP().toString() + "\nSSID: " + WiFi.softAPSSID(),1); + #endif + // myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // Serial.println(WiFi.softAPIP()); + //if you used auto generated SSID, print it + // Serial.println(myWiFiManager->getConfigPortalSSID()); +} + +void saveParamCallback(){ + Serial.println("[CALLBACK] saveParamCallback fired"); + // wm.stopConfigPortal(); +} + +void bindServerCallback(){ + wm.server->on("/custom",handleRoute); + // wm.server->on("/info",handleRoute); // you can override wm! +} + +void handleRoute(){ + Serial.println("[HTTP] handle route"); + wm.server->send(200, "text/plain", "hello from user code"); +} + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + + // put your setup code here, to run once: + Serial.begin(115200); + // Serial1.begin(115200); + + // Serial.setDebugOutput(true); + delay(1000); + + Serial.println("\n Starting"); + // WiFi.setSleepMode(WIFI_NONE_SLEEP); // disable sleep, can improve ap stability + + #ifdef WM_OLED + init_oled(); + #endif + + print_oled(F("Starting..."),2); + wm.debugPlatformInfo(); + + //reset settings - for testing + // wm.resetSettings(); + // wm.erase(); + + // invert theme, dark + wm.setClass("invert"); + + // setup some parameters + WiFiManagerParameter custom_html("

This Is Custom HTML

"); // only custom html + WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); + WiFiManagerParameter custom_token("api_token", "api token", "", 16); + WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces + WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // custom input attrs (ip mask) + + const char _customHtml_checkbox[] = "type=\"checkbox\""; + WiFiManagerParameter custom_checkbox("checkbox", "my checkbox", "T", 2, _customHtml_checkbox, WFM_LABEL_AFTER); + + // callbacks + wm.setAPCallback(configModeCallback); + wm.setWebServerCallback(bindServerCallback); + wm.setSaveConfigCallback(saveWifiCallback); + wm.setSaveParamsCallback(saveParamCallback); + + // add all your parameters here + wm.addParameter(&custom_html); + wm.addParameter(&custom_mqtt_server); + wm.addParameter(&custom_mqtt_port); + wm.addParameter(&custom_token); + wm.addParameter(&custom_tokenb); + wm.addParameter(&custom_ipaddress); + wm.addParameter(&custom_checkbox); + + // set values later if you want + custom_html.setValue("test",4); + custom_token.setValue("test",4); + +/* + Set cutom menu via menu[] or vector + const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; + wm.setMenu(menu,9); // custom menu array must provide length +*/ + + std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; + // wm.setMenu(menu); // custom menu, pass vector + + // wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu! + + // set STA static ip + // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // wm.setShowStaticFields(false); + // wm.setShowDnsFields(false); + + // set AP static ip + // wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // wm.setAPStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + + // set country + // setting wifi country seems to improve OSX soft ap connectivity, + // may help others as well, default is CN which has different channels + wm.setCountry("US"); + + // set Hostname + wm.setHostname("WIFIMANAGERTESTING"); + + // set custom channel + // wm.setWiFiAPChannel(13); + + // set AP hidden + // wm.setAPHidden(true); + + // show password publicly in form + // wm.setShowPassword(true); + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep in seconds + wm.setConfigPortalTimeout(120); + + // set connection timeout + // wm.setConnectTimeout(20); + + // show static ip fields + // wm.setShowStaticFields(true); + + // wm.startConfigPortal("AutoConnectAP", "password"); + + // This is sometimes necessary, it is still unknown when and why this is needed but it may solve some race condition or bug in esp SDK/lib + // wm.setCleanConnect(true); // disconnect before connect, clean connect + + // + wm.setBreakAfterConfig(true); + + // set custom webserver port, automatic captive portal does not work with custom ports! + // wm.setHttpPort(8080); + + //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 + + wifiInfo(); + + print_oled(F("Connecting..."),2); + if(!wm.autoConnect("WM_AutoConnectAP","12345678")) { + Serial.println("failed to connect and hit timeout"); + print_oled("Not Connected",2); + } + else if(TEST_CP) { + // start configportal always + delay(1000); + Serial.println("TEST_CP ENABLED"); + wm.setConfigPortalTimeout(TESP_CP_TIMEOUT); + wm.startConfigPortal("WM_ConnectAP"); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + print_oled("Connected\nIP: " + WiFi.localIP().toString() + "\nSSID: " + WiFi.SSID(),1); + } + + wifiInfo(); + pinMode(ONDDEMANDPIN, INPUT_PULLUP); + + #ifdef USEOTA + ArduinoOTA.begin(); + #endif +} + +void wifiInfo(){ + WiFi.printDiag(Serial); + Serial.println("SAVED: " + (String)wm.getWiFiIsSaved() ? "YES" : "NO"); + Serial.println("SSID: " + (String)wm.getWiFiSSID()); + Serial.println("PASS: " + (String)wm.getWiFiPass()); +} + +void loop() { + + #ifdef USEOTA + ArduinoOTA.handle(); + #endif + // is configuration portal requested? + if (ALLOWONDEMAND && digitalRead(ONDDEMANDPIN) == LOW ) { + delay(100); + if ( digitalRead(ONDDEMANDPIN) == LOW ){ + Serial.println("BUTTON PRESSED"); + wm.setConfigPortalTimeout(140); + wm.setParamsPage(false); // move params to seperate page, not wifi, do not combine with setmenu! + + // disable captive portal redirection + // wm.setCaptivePortalEnable(false); + + if (!wm.startConfigPortal("OnDemandAP","12345678")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + } + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + print_oled("Connected\nIP: " + WiFi.localIP().toString() + "\nSSID: " + WiFi.SSID(),1); + getTime(); + } + } + + if(WiFi.status() == WL_CONNECTED && millis()-mtime > 10000 ){ + getTime(); + mtime = millis(); + } + // put your main code here, to run repeatedly: + delay(100); +} + +void getTime() { + int tz = -5; + int dst = 0; + time_t now = time(nullptr); + unsigned timeout = 5000; + unsigned start = millis(); + configTime(tz * 3600, dst * 3600, "pool.ntp.org", "time.nist.gov"); + Serial.print("Waiting for NTP time sync: "); + while (now < 8 * 3600 * 2 ) { + delay(100); + Serial.print("."); + now = time(nullptr); + if((millis() - start) > timeout){ + Serial.println("\n[ERROR] Failed to get NTP time."); + return; + } + } + Serial.println(""); + struct tm timeinfo; + gmtime_r(&now, &timeinfo); + Serial.print("Current time: "); + Serial.print(asctime(&timeinfo)); +} + +void debugchipid(){ + // WiFi.mode(WIFI_STA); + // WiFi.printDiag(Serial); + // Serial.println(modes[WiFi.getMode()]); + + // ESP.eraseConfig(); + // wm.resetSettings(); + // wm.erase(true); + WiFi.mode(WIFI_AP); + // WiFi.softAP(); + WiFi.enableAP(true); + delay(500); + // esp_wifi_start(); + delay(1000); + WiFi.printDiag(Serial); + delay(60000); + ESP.restart(); + + // AP esp_267751 + // 507726A4AE30 + // ESP32 Chip ID = 507726A4AE30 +} + +#ifdef WM_OLED +void init_oled(){ + if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 + Serial.println(F("SSD1306 allocation failed")); + } + + display.clearDisplay(); + display.setTextSize(1); // Normal 1:1 pixepl scale + display.setTextColor(WHITE); // Draw white text + display.setCursor(0,0); // Start at top-left corner + display.display(); +} + +void print_oled(String str,uint8_t size){ + display.clearDisplay(); + display.setTextSize(size); + display.setTextColor(WHITE); + display.setCursor(0,0); + display.println(str); + display.display(); +} +#else + void print_oled(String str,uint8_t size){ + (void)str; + (void)size; + } +#endif diff --git a/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino b/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino new file mode 100644 index 00000000..fa04d917 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino @@ -0,0 +1,27 @@ +#include // https://github.com/tzapu/WiFiManager +WiFiManager wm; + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + Serial.begin(115200); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + + wm.setConfigPortalBlocking(false); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + if(wm.autoConnect("AutoConnectAP")){ + Serial.println("connected...yeey :)"); + } + else { + Serial.println("Configportal running"); + } +} + +void loop() { + wm.process(); + // put your main code here, to run repeatedly: +} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino b/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino new file mode 100644 index 00000000..3af79f01 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino @@ -0,0 +1,36 @@ +#include // https://github.com/tzapu/WiFiManager +WiFiManager wm; +WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + Serial.begin(115200); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + wm.addParameter(&custom_mqtt_server); + wm.setConfigPortalBlocking(false); + wm.setSaveParamsCallback(saveParamsCallback); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + if(wm.autoConnect("AutoConnectAP")){ + Serial.println("connected...yeey :)"); + } + else { + Serial.println("Configportal running"); + } +} + +void loop() { + wm.process(); + // put your main code here, to run repeatedly: +} + +void saveParamsCallback () { + Serial.println("Get Params:"); + Serial.print(custom_mqtt_server.getID()); + Serial.print(" : "); + Serial.println(custom_mqtt_server.getValue()); +} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino b/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino new file mode 100644 index 00000000..3813356e --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino @@ -0,0 +1,83 @@ +/** + * OnDemandNonBlocking.ino + * example of running the webportal or configportal manually and non blocking + * trigger pin will start a webportal for 120 seconds then turn it off. + * startCP = true will start both the configportal AP and webportal + */ +#include // https://github.com/tzapu/WiFiManager + +// include MDNS +#ifdef ESP8266 +#include +#elif defined(ESP32) +#include +#endif + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +WiFiManager wm; + +unsigned int timeout = 120; // seconds to run for +unsigned int startTime = millis(); +bool portalRunning = false; +bool startAP = false; // start AP and webserver if true, else start only webserver + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once + Serial.begin(115200); + Serial.setDebugOutput(true); + delay(1000); + Serial.println("\n Starting"); + + pinMode(TRIGGER_PIN, INPUT_PULLUP); + + // wm.resetSettings(); + wm.setHostname("MDNSEXAMPLE"); + // wm.setEnableConfigPortal(false); + // wm.setConfigPortalBlocking(false); + wm.autoConnect(); +} + +void loop() { + #ifdef ESP8266 + MDNS.update(); + #endif + doWiFiManager(); + // put your main code here, to run repeatedly: +} + +void doWiFiManager(){ + // is auto timeout portal running + if(portalRunning){ + wm.process(); + if((millis()-startTime) > (timeout*1000)){ + Serial.println("portaltimeout"); + portalRunning = false; + if(startAP){ + wm.stopConfigPortal(); + } + else{ + wm.stopWebPortal(); + } + } + } + + // is configuration portal requested? + if(digitalRead(TRIGGER_PIN) == LOW && (!portalRunning)) { + if(startAP){ + Serial.println("Button Pressed, Starting Config Portal"); + wm.setConfigPortalBlocking(false); + wm.startConfigPortal(); + } + else{ + Serial.println("Button Pressed, Starting Web Portal"); + wm.startWebPortal(); + } + portalRunning = true; + startTime = millis(); + } +} + + diff --git a/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino new file mode 100644 index 00000000..d3c4ed8b --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino @@ -0,0 +1,42 @@ +#include // https://github.com/tzapu/WiFiManager + +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()); +} + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wifiManager; + //reset 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.restart(); + delay(1000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + +} + +void loop() { + // put your main code here, to run repeatedly: + +} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino new file mode 100644 index 00000000..53a0d138 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino @@ -0,0 +1,43 @@ +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager + +void setup() { + // put your setup code here, to run once: + 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.restart(); + 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/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino new file mode 100644 index 00000000..9f88e470 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino @@ -0,0 +1,71 @@ +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager + +/************************************************************************************** + * this example shows how to set a static IP configuration for the ESP + * 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 + //block1 should be used for ESP8266 core 2.1.0 or newer, otherwise use block2 + + //start-block1 + //IPAddress _ip,_gw,_sn; + //_ip.fromString(static_ip); + //_gw.fromString(static_gw); + //_sn.fromString(static_sn); + //end-block1 + + //start-block2 + IPAddress _ip = IPAddress(10, 0, 1, 78); + IPAddress _gw = IPAddress(10, 0, 1, 1); + IPAddress _sn = IPAddress(255, 255, 255, 0); + //end-block2 + + 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.restart(); + 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/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino new file mode 100644 index 00000000..9df428d4 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino @@ -0,0 +1,38 @@ +#include // https://github.com/tzapu/WiFiManager + +void setup() { + // put your setup code here, to run once: + Serial.begin(115200); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wifiManager; + //reset settings - for testing + //wifiManager.resetSettings(); + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep + //in seconds + wifiManager.setConfigPortalTimeout(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.restart(); + 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: + +} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino b/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino new file mode 100644 index 00000000..a352b389 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -0,0 +1,47 @@ +/** + * OnDemandConfigPortal.ino + * example of running the configPortal AP manually, independantly from the captiveportal + * trigger pin will start a configPortal AP for 120 seconds then turn it off. + * + */ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +int timeout = 120; // seconds to run for + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); +} + +void loop() { + // is configuration portal requested? + if ( digitalRead(TRIGGER_PIN) == LOW) { + WiFiManager wm; + + //reset settings - for testing + //wifiManager.resetSettings(); + + // set configportal timeout + wm.setConfigPortalTimeout(timeout); + + if (!wm.startConfigPortal("OnDemandAP")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + //reset and try again, or maybe put it to deep sleep + ESP.restart(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + + } + + // put your main code here, to run repeatedly: +} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino b/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino new file mode 100644 index 00000000..7b6676a0 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino @@ -0,0 +1,51 @@ +/** + * OnDemandWebPortal.ino + * example of running the webportal (always NON blocking) + */ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +WiFiManager wm; + +bool portalRunning = false; + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once + Serial.begin(115200); + Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); +} + +void loop() { + checkButton(); + // put your main code here, to run repeatedly: +} + +void checkButton(){ + // is auto timeout portal running + if(portalRunning){ + wm.process(); + } + + // is configuration portal requested? + if(digitalRead(TRIGGER_PIN) == LOW) { + delay(50); + if(digitalRead(TRIGGER_PIN) == LOW) { + if(!portalRunning){ + Serial.println("Button Pressed, Starting Portal"); + wm.startWebPortal(); + portalRunning = true; + } + else{ + Serial.println("Button Pressed, Stopping Portal"); + wm.startWebPortal(); + portalRunning = false; + } + } + } +} + + diff --git a/lib/WiFiManager-2.0.3-alpha/examples/ParamsChildClass/ParamsChildClass.ino b/lib/WiFiManager-2.0.3-alpha/examples/ParamsChildClass/ParamsChildClass.ino new file mode 100644 index 00000000..0117d773 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/ParamsChildClass/ParamsChildClass.ino @@ -0,0 +1,141 @@ +/** + * WiFiManagerParameter child class example + */ +#include // https://github.com/tzapu/WiFiManager +#include +#include + +#define SETUP_PIN 0 + +class IPAddressParameter : public WiFiManagerParameter { +public: + IPAddressParameter(const char *id, const char *placeholder, IPAddress address) + : WiFiManagerParameter("") { + init(id, placeholder, address.toString().c_str(), 16, "", WFM_LABEL_BEFORE); + } + + bool getValue(IPAddress &ip) { + return ip.fromString(WiFiManagerParameter::getValue()); + } +}; + +class IntParameter : public WiFiManagerParameter { +public: + IntParameter(const char *id, const char *placeholder, long value, const uint8_t length = 10) + : WiFiManagerParameter("") { + init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); + } + + long getValue() { + return String(WiFiManagerParameter::getValue()).toInt(); + } +}; + +class FloatParameter : public WiFiManagerParameter { +public: + FloatParameter(const char *id, const char *placeholder, float value, const uint8_t length = 10) + : WiFiManagerParameter("") { + init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); + } + + float getValue() { + return String(WiFiManagerParameter::getValue()).toFloat(); + } +}; + +struct Settings { + float f; + int i; + char s[20]; + uint32_t ip; +} sett; + + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + pinMode(SETUP_PIN, INPUT_PULLUP); + Serial.begin(115200); + + //Delay to push SETUP button + Serial.println("Press setup button"); + for (int sec = 3; sec > 0; sec--) { + Serial.print(sec); + Serial.print(".."); + delay(1000); + } + + EEPROM.begin( 512 ); + EEPROM.get(0, sett); + Serial.println("Settings loaded"); + + if (digitalRead(SETUP_PIN) == LOW) { + // Button pressed + Serial.println("SETUP"); + + WiFiManager wm; + + sett.s[19] = '\0'; //add null terminator at the end cause overflow + WiFiManagerParameter param_str( "str", "param_string", sett.s, 20); + FloatParameter param_float( "float", "param_float", sett.f); + IntParameter param_int( "int", "param_int", sett.i); + + IPAddress ip(sett.ip); + IPAddressParameter param_ip("ip", "param_ip", ip); + + wm.addParameter( ¶m_str ); + wm.addParameter( ¶m_float ); + wm.addParameter( ¶m_int ); + wm.addParameter( ¶m_ip ); + + //SSID & password parameters already included + wm.startConfigPortal(); + + strncpy(sett.s, param_str.getValue(), 20); + sett.s[19] = '\0'; + sett.f = param_float.getValue(); + sett.i = param_int.getValue(); + + Serial.print("String param: "); + Serial.println(sett.s); + Serial.print("Float param: "); + Serial.println(sett.f); + Serial.print("Int param: "); + Serial.println(sett.i, DEC); + + if (param_ip.getValue(ip)) { + sett.ip = ip; + + Serial.print("IP param: "); + Serial.println(ip); + } else { + Serial.println("Incorrect IP"); + } + + EEPROM.put(0, sett); + if (EEPROM.commit()) { + Serial.println("Settings saved"); + } else { + Serial.println("EEPROM error"); + } + } + else { + Serial.println("WORK"); + + //connect to saved SSID + WiFi.begin(); + + //do smth + Serial.print("String param: "); + Serial.println(sett.s); + Serial.print("Float param: "); + Serial.println(sett.f); + Serial.print("Int param: "); + Serial.println(sett.i, DEC); + Serial.print("IP param: "); + IPAddress ip(sett.ip); + Serial.println(ip); + } +} + +void loop() { +} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/Tests/AnonymousCB.ino b/lib/WiFiManager-2.0.3-alpha/examples/Tests/AnonymousCB.ino new file mode 100644 index 00000000..f34d80f7 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/examples/Tests/AnonymousCB.ino @@ -0,0 +1,26 @@ +#include // https://github.com/tzapu/WiFiManager + +bool _enteredConfigMode = false; + +void setup(){ + Serial.begin(115200); + WiFiManager wifiManager; + + // wifiManager.setAPCallback([this](WiFiManager* wifiManager) { + wifiManager.setAPCallback([&](WiFiManager* wifiManager) { + Serial.printf("Entered config mode:ip=%s, ssid='%s'\n", + WiFi.softAPIP().toString().c_str(), + wifiManager->getConfigPortalSSID().c_str()); + _enteredConfigMode = true; + }); + wifiManager.resetSettings(); + if (!wifiManager.autoConnect()) { + Serial.printf("*** Failed to connect and hit timeout\n"); + ESP.restart(); + delay(1000); + } +} + +void loop(){ + +} diff --git a/lib/WiFiManager-2.0.3-alpha/extras/WiFiManager.template.html b/lib/WiFiManager-2.0.3-alpha/extras/WiFiManager.template.html new file mode 100644 index 00000000..d2c2c398 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/extras/WiFiManager.template.html @@ -0,0 +1,324 @@ + + + + + + {v} + + + + + + + + + + +
+ + + +

/


+ + + + +

+

+

+

+

+

+

+

+

+

+ + +

/wifi


+ + + + + + + + + + + + + + + + + + + + +



+ + +

custom parameter


+
+
+ + +
+ + +
+ + +
+ + +
+ + +

Saving Credentials

Trying to connect ESP to network.
If it fails reconnect to AP to try again
+ + +
Connected to {v}
with IP {i}
+ + +
Not Connected to {v}{r}
+ + +
Not Connected to apname + + +
Authentication Failure + + +
AP not found + + +
Could not Connect + +
+ +
No AP set
+ + +

H4 Color Header P

content
+ + +

H4 Color Header S

content
+ + +

/info


+
+
Chip ID
123456
+
Flash Chip ID
1234556
+
IDE Flash Size
4194304 bytes
+
Real Flash Size
4194304 bytes
+
Empty
+
Soft AP IP
192.168.4.1
+
Soft AP MAC
00:00:00:00:00:00
+
Station MAC
00:00:00:00:00:00
+
+ + +

Available Pages


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

More information about WiFiManager at https://github.com/tzapu/WiFiManager + + +

Form UPLOAD

+ + + +
+ + + diff --git a/lib/WiFiManager-2.0.3-alpha/extras/parse.js b/lib/WiFiManager-2.0.3-alpha/extras/parse.js new file mode 100644 index 00000000..97a3e384 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/extras/parse.js @@ -0,0 +1,60 @@ +'use strict'; + +const fs = require('fs'); + +console.log('starting'); + +const inFile = 'WiFiManager.template.html'; +const outFile = 'template.h'; + +const defineRegEx = //gm; +console.log('parsing', inFile); + +fs.readFile(inFile, 'utf8', function (err,data) { + if (err) { + return console.log(err); + } + //console.log(data); + + let defines = data.match(defineRegEx); + + //console.log(defines); + var stream = fs.createWriteStream(outFile); + stream.once('open', function(fd) { + for (const i in defines) { + + const start = defines[i]; + const end = start.replace(' + + + + diff --git a/lib/WiFiManager-2.0.3-alpha/keywords.txt b/lib/WiFiManager-2.0.3-alpha/keywords.txt new file mode 100644 index 00000000..7159e740 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/keywords.txt @@ -0,0 +1,39 @@ +####################################### +# Syntax Coloring Map For WifiManager +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +WiFiManager KEYWORD1 +WiFiManagerParameter KEYWORD1 + + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +autoConnect KEYWORD2 +getSSID KEYWORD2 +getPassword KEYWORD2 +getConfigPortalSSID KEYWORD2 +resetSettings KEYWORD2 +setConfigPortalTimeout KEYWORD2 +setConnectTimeout KEYWORD2 +setDebugOutput KEYWORD2 +setMinimumSignalQuality KEYWORD2 +setAPStaticIPConfig KEYWORD2 +setSTAStaticIPConfig KEYWORD2 +setAPCallback KEYWORD2 +setSaveConfigCallback KEYWORD2 +addParameter KEYWORD2 +getID KEYWORD2 +getValue KEYWORD2 +getPlaceholder KEYWORD2 +getValueLength KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + +# LITERAL1 diff --git a/lib/WiFiManager-2.0.3-alpha/library.json b/lib/WiFiManager-2.0.3-alpha/library.json new file mode 100644 index 00000000..96c4164d --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/library.json @@ -0,0 +1,29 @@ +{ + "name": "WifiManager", + "keywords": "wifi,wi-fi,esp,esp8266,esp32,espressif8266,espressif32,nodemcu,wemos,arduino", + "description": "WiFi Configuration manager with web configuration portal for ESP boards", +"authors": +[ + { + "name": "tzapu", + "url": "https://github.com/tzapu" + }, + { + "name": "tablatronix", + "url": "https://github.com/tablatronix", + "maintainer": true + } +], +"repository": + { + "type": "git", + "url": "https://github.com/tzapu/WiFiManager.git" + }, + "frameworks": "arduino", + "platforms": + [ + "espressif8266", + "espressif32" + ], + "version": "2.0.3-alpha" +} diff --git a/lib/WiFiManager-2.0.3-alpha/library.properties b/lib/WiFiManager-2.0.3-alpha/library.properties new file mode 100644 index 00000000..9ac084b7 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/library.properties @@ -0,0 +1,9 @@ +name=WiFiManager +version=2.0.3-alpha +author=tzapu,tablatronix +maintainer=tablatronix +sentence=WiFi Configuration manager with web configuration portal for ESP boards +paragraph=Library for configuring ESP8266/ESP32 modules WiFi credentials and custom parameters at runtime. +category=Communication +url=https://github.com/tzapu/WiFiManager.git +architectures=esp8266,esp32 diff --git a/lib/WiFiManager-2.0.3-alpha/strings_en.h b/lib/WiFiManager-2.0.3-alpha/strings_en.h new file mode 100644 index 00000000..d56d0b12 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/strings_en.h @@ -0,0 +1,363 @@ +/** + * strings_en.h + * engligh strings for + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ + +#ifndef _WM_STRINGS_H_ +#define _WM_STRINGS_H_ + +#ifndef WIFI_MANAGER_OVERRIDE_STRINGS +// !!! THIS DOES NOT WORK, you cannot define in a sketch, if anyone one knows how to order includes to be able to do this help! + +const char HTTP_HEAD_START[] PROGMEM = "{v}"; +const char HTTP_SCRIPT[] PROGMEM = ""; + +const char HTTP_HEAD_END[] PROGMEM = "
"; +// example of embedded logo, base64 encoded inline, No styling here +// const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

"; +const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

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

\n", // MENU_WIFI +"

\n", // MENU_WIFINOSCAN +"

\n", // MENU_INFO +"

\n",//MENU_PARAM +"

\n", // MENU_CLOSE +"

\n",// MENU_RESTART +"

\n", // MENU_EXIT +"

\n", // MENU_ERASE +"

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

"; +const char HTTP_FORM_END[] PROGMEM = "

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

"; +const char HTTP_FORM_PARAM[] PROGMEM = "
"; + +const char HTTP_SCAN_LINK[] PROGMEM = "
"; +const char HTTP_SAVED[] PROGMEM = "
Saving Credentials
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; +const char HTTP_PARAMSAVED[] PROGMEM = "
Saved
"; +const char HTTP_END[] PROGMEM = "
"; +const char HTTP_ERASEBTN[] PROGMEM = "
"; +const char HTTP_BACKBTN[] PROGMEM = "

"; + +const char HTTP_STATUS_ON[] PROGMEM = "
Connected to {v}
with IP {i}
"; +const char HTTP_STATUS_OFF[] PROGMEM = "
Not Connected to {v}{r}
"; +const char HTTP_STATUS_OFFPW[] PROGMEM = "
Authentication Failure"; // STATION_WRONG_PASSWORD, no eps32 +const char HTTP_STATUS_OFFNOAP[] PROGMEM = "
AP not found"; // WL_NO_SSID_AVAIL +const char HTTP_STATUS_OFFFAIL[] PROGMEM = "
Could not Connect"; // WL_CONNECT_FAILED +const char HTTP_STATUS_NONE[] PROGMEM = "
No AP set
"; +const char HTTP_BR[] PROGMEM = "
"; + +const char HTTP_STYLE[] PROGMEM = ""; + +const char HTTP_HELP[] PROGMEM = + "

Available Pages


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

More information about WiFiManager at https://github.com/tzapu/WiFiManager."; + +#ifdef WM_JSTEST +const char HTTP_JS[] PROGMEM = +""; +#endif + +// Info html +#ifdef ESP32 + const char HTTP_INFO_esphead[] PROGMEM = "

esp32


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

esp8266


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

WiFi


"; +const char HTTP_INFO_uptime[] PROGMEM = "
Uptime
{1} Mins {2} Secs
"; +const char HTTP_INFO_chipid[] PROGMEM = "
Chip ID
{1}
"; +const char HTTP_INFO_idesize[] PROGMEM = "
Flash Size
{1} bytes
"; +const char HTTP_INFO_sdkver[] PROGMEM = "
SDK Version
{1}
"; +const char HTTP_INFO_cpufreq[] PROGMEM = "
CPU Frequency
{1}MHz
"; +const char HTTP_INFO_apip[] PROGMEM = "
Access Point IP
{1}
"; +const char HTTP_INFO_apmac[] PROGMEM = "
Access Point MAC
{1}
"; +const char HTTP_INFO_apssid[] PROGMEM = "
SSID
{1}
"; +const char HTTP_INFO_apbssid[] PROGMEM = "
BSSID
{1}
"; +const char HTTP_INFO_staip[] PROGMEM = "
Station IP
{1}
"; +const char HTTP_INFO_stagw[] PROGMEM = "
Station Gateway
{1}
"; +const char HTTP_INFO_stasub[] PROGMEM = "
Station Subnet
{1}
"; +const char HTTP_INFO_dnss[] PROGMEM = "
DNS Server
{1}
"; +const char HTTP_INFO_host[] PROGMEM = "
Hostname
{1}
"; +const char HTTP_INFO_stamac[] PROGMEM = "
Station MAC
{1}
"; +const char HTTP_INFO_conx[] PROGMEM = "
Connected
{1}
"; +const char HTTP_INFO_autoconx[] PROGMEM = "
Autoconnect
{1}
"; +const char HTTP_INFO_temp[] PROGMEM = "
Temperature
{1} C° / {2} F°
"; + +// Strings +const char S_y[] PROGMEM = "Yes"; +const char S_n[] PROGMEM = "No"; +const char S_enable[] PROGMEM = "Enabled"; +const char S_disable[] PROGMEM = "Disabled"; +const char S_GET[] PROGMEM = "GET"; +const char S_POST[] PROGMEM = "POST"; +const char S_NA[] PROGMEM = "Unknown"; +const char S_passph[] PROGMEM = "********"; +const char S_titlewifisaved[] PROGMEM = "Credentials Saved"; +const char S_titlewifisettings[] PROGMEM = "Settings Saved"; +const char S_titlewifi[] PROGMEM = "Config ESP"; +const char S_titleinfo[] PROGMEM = "Info"; +const char S_titleparam[] PROGMEM = "Setup"; +const char S_titleparamsaved[] PROGMEM = "Setup Saved"; +const char S_titleexit[] PROGMEM = "Exit"; +const char S_titlereset[] PROGMEM = "Reset"; +const char S_titleerase[] PROGMEM = "Erase"; +const char S_titleclose[] PROGMEM = "Close"; +const char S_options[] PROGMEM = "options"; +const char S_nonetworks[] PROGMEM = "No networks found. Refresh to scan again."; +const char S_staticip[] PROGMEM = "Static IP"; +const char S_staticgw[] PROGMEM = "Static Gateway"; +const char S_staticdns[] PROGMEM = "Static DNS"; +const char S_subnet[] PROGMEM = "Subnet"; +const char S_exiting[] PROGMEM = "Exiting"; +const char S_resetting[] PROGMEM = "Module will reset in a few seconds."; +const char S_closing[] PROGMEM = "You can close the page, portal will continue to run"; +const char S_error[] PROGMEM = "An Error Occured"; +const char S_notfound[] PROGMEM = "File Not Found\n\n"; +const char S_uri[] PROGMEM = "URI: "; +const char S_method[] PROGMEM = "\nMethod: "; +const char S_args[] PROGMEM = "\nArguments: "; +const char S_parampre[] PROGMEM = "param_"; + +// debug strings +const char D_HR[] PROGMEM = "--------------------"; + +// END WIFI_MANAGER_OVERRIDE_STRINGS +#endif + +// ----------------------------------------------------------------------------------------------- +// DO NOT EDIT BELOW THIS LINE + +const uint8_t _nummenutokens = 9; +const char * const _menutokens[9] PROGMEM = { + "wifi", + "wifinoscan", + "info", + "param", + "close", + "restart", + "exit", + "erase", + "sep" +}; + +const char R_root[] PROGMEM = "/"; +const char R_wifi[] PROGMEM = "/wifi"; +const char R_wifinoscan[] PROGMEM = "/0wifi"; +const char R_wifisave[] PROGMEM = "/wifisave"; +const char R_info[] PROGMEM = "/info"; +const char R_param[] PROGMEM = "/param"; +const char R_paramsave[] PROGMEM = "/paramsave"; +const char R_restart[] PROGMEM = "/restart"; +const char R_exit[] PROGMEM = "/exit"; +const char R_close[] PROGMEM = "/close"; +const char R_erase[] PROGMEM = "/erase"; +const char R_status[] PROGMEM = "/status"; + + +//Strings +const char S_ip[] PROGMEM = "ip"; +const char S_gw[] PROGMEM = "gw"; +const char S_sn[] PROGMEM = "sn"; +const char S_dns[] PROGMEM = "dns"; + +// softap ssid default prefix +#ifdef ESP8266 + const char S_ssidpre[] PROGMEM = "ESP"; +#elif defined(ESP32) + const char S_ssidpre[] PROGMEM = "ESP32"; +#else + const char S_ssidpre[] PROGMEM = "WM"; +#endif + +//Tokens +//@todo consolidate and reduce +const char T_ss[] PROGMEM = "{"; // token start sentinel +const char T_es[] PROGMEM = "}"; // token end sentinel +const char T_1[] PROGMEM = "{1}"; // @token 1 +const char T_2[] PROGMEM = "{2}"; // @token 2 +const char T_v[] PROGMEM = "{v}"; // @token v +const char T_I[] PROGMEM = "{I}"; // @token I +const char T_i[] PROGMEM = "{i}"; // @token i +const char T_n[] PROGMEM = "{n}"; // @token n +const char T_p[] PROGMEM = "{p}"; // @token p +const char T_t[] PROGMEM = "{t}"; // @token t +const char T_l[] PROGMEM = "{l}"; // @token l +const char T_c[] PROGMEM = "{c}"; // @token c +const char T_e[] PROGMEM = "{e}"; // @token e +const char T_q[] PROGMEM = "{q}"; // @token q +const char T_r[] PROGMEM = "{r}"; // @token r +const char T_R[] PROGMEM = "{R}"; // @token R +const char T_h[] PROGMEM = "{h}"; // @token h + +// http +const char HTTP_HEAD_CL[] PROGMEM = "Content-Length"; +const char HTTP_HEAD_CT[] PROGMEM = "text/html"; +const char HTTP_HEAD_CT2[] PROGMEM = "text/plain"; +const char HTTP_HEAD_CORS[] PROGMEM = "Access-Control-Allow-Origin"; +const char HTTP_HEAD_CORS_ALLOW_ALL[] PROGMEM = "*"; + +const char * const WIFI_STA_STATUS[] PROGMEM +{ + "WL_IDLE_STATUS", // 0 STATION_IDLE + "WL_NO_SSID_AVAIL", // 1 STATION_NO_AP_FOUND + "WL_SCAN_COMPLETED", // 2 + "WL_CONNECTED", // 3 STATION_GOT_IP + "WL_CONNECT_FAILED", // 4 STATION_CONNECT_FAIL, STATION_WRONG_PASSWORD(NI) + "WL_CONNECTION_LOST", // 5 + "WL_DISCONNECTED", // 6 + "WL_STATION_WRONG_PASSWORD" // 7 KLUDGE +}; + +#ifdef ESP32 +const char * const AUTH_MODE_NAMES[] PROGMEM +{ + "OPEN", + "WEP", + "WPA_PSK", + "WPA2_PSK", + "WPA_WPA2_PSK", + "WPA2_ENTERPRISE", + "MAX" +}; +#elif defined(ESP8266) +const char * const AUTH_MODE_NAMES[] PROGMEM +{ + "", + "", + "WPA_PSK", // 2 ENC_TYPE_TKIP + "", + "WPA2_PSK", // 4 ENC_TYPE_CCMP + "WEP", // 5 ENC_TYPE_WEP + "", + "OPEN", //7 ENC_TYPE_NONE + "WPA_WPA2_PSK", // 8 ENC_TYPE_AUTO +}; +#endif + +const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; + + +#ifdef ESP32 +// as 2.5.2 +// typedef struct { +// char cc[3]; /**< country code string */ +// uint8_t schan; /**< start channel */ +// uint8_t nchan; /**< total channel number */ +// int8_t max_tx_power; /**< This field is used for getting WiFi maximum transmitting power, call esp_wifi_set_max_tx_power to set the maximum transmitting power. */ +// wifi_country_policy_t policy; /**< country policy */ +// } wifi_country_t; +const wifi_country_t WM_COUNTRY_US{"US",1,11,CONFIG_ESP32_PHY_MAX_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_CN{"CN",1,13,CONFIG_ESP32_PHY_MAX_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_JP{"JP",1,14,CONFIG_ESP32_PHY_MAX_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +#elif defined(ESP8266) +// typedef struct { +// char cc[3]; /**< country code string */ +// uint8_t schan; /**< start channel */ +// uint8_t nchan; /**< total channel number */ +// uint8_t policy; /**< country policy */ +// } wifi_country_t; +const wifi_country_t WM_COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; +#endif + +#endif \ No newline at end of file diff --git a/lib/WiFiManager-2.0.3-alpha/travis/common.sh b/lib/WiFiManager-2.0.3-alpha/travis/common.sh new file mode 100644 index 00000000..4b3e6556 --- /dev/null +++ b/lib/WiFiManager-2.0.3-alpha/travis/common.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +function build_examples() +{ + excludes=("$@") + # track the exit code for this platform + local exit_code=0 + # loop through results and add them to the array + examples=($(find $PWD/examples/ -name "*.pde" -o -name "*.ino")) + + # get the last example in the array + local last="${examples[@]:(-1)}" + + # loop through example sketches + for example in "${examples[@]}"; do + + # store the full path to the example's sketch directory + local example_dir=$(dirname $example) + + # store the filename for the example without the path + local example_file=$(basename $example) + + # skip files listed as excludes + for exclude in "${excludes[@]}"; do + if [ "${example_file}" == "${exclude}" ] ; then + echo ">>>>>>>>>>>>>>>>>>>>>>>> Skipping ${example_file} <<<<<<<<<<<<<<<<<<<<<<<<<<" + continue 2 + fi + done + + echo "$example_file: " + local sketch="$example_dir/$example_file" + echo "$sketch" + #arduino -v --verbose-build --verify $sketch + + # verify the example, and save stdout & stderr to a variable + # we have to avoid reading the exit code of local: + # "when declaring a local variable in a function, the local acts as a command in its own right" + local build_stdout + build_stdout=$(arduino --verify $sketch 2>&1) + + # echo output if the build failed + if [ $? -ne 0 ]; then + # heavy X + echo -e "\xe2\x9c\x96" + echo -e "----------------------------- DEBUG OUTPUT -----------------------------\n" + echo "$build_stdout" + echo -e "\n------------------------------------------------------------------------\n" + + # mark as fail + exit_code=1 + + else + # heavy checkmark + echo -e "\xe2\x9c\x93" + fi + done + + return $exit_code +} diff --git a/platformio.ini b/platformio.ini index a99ee3d8..0646fc40 100644 --- a/platformio.ini +++ b/platformio.ini @@ -8,14 +8,17 @@ ; Please visit documentation for the other options and examples ; http://docs.platformio.org/page/projectconf.html +[platformio] +default_envs = lolin_d32_pro + [common] framework = arduino platform = espressif8266@~1.8 board_f_cpu = 160000000L lib_deps_builtin = SPI + SPIFFS lib_deps_external = - sidoh/WiFiManager#cmidgley RF24@~1.3.2 ArduinoJson@~6.10.1 PubSubClient@~2.7 @@ -111,6 +114,18 @@ upload_speed = ${common.upload_speed} board = d1_mini_pro build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D FIRMWARE_VARIANT=d1_mini_PRO extra_scripts = ${common.extra_scripts} +lib_deps = + ${common.lib_deps_builtin} + ${common.lib_deps_external} +test_ignore = ${common.test_ignore} + +[env:lolin_d32_pro] +platform = espressif32 +framework = ${common.framework} +upload_speed = ${common.upload_speed} +board = lolin_d32_pro +build_flags = ${common.build_flags} -Wl, -D ESP32 -D FIRMWARE_VARIANT=lolin_d32_pro +extra_scripts = ${common.extra_scripts} lib_deps = ${common.lib_deps_builtin} ${common.lib_deps_external} diff --git a/src/main.cpp b/src/main.cpp index 1c76567d..69b9c6f9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -16,8 +17,9 @@ #include #include #include -#include -#include +// #include +#include +//#include #include #include #include @@ -199,6 +201,8 @@ void onUpdateEnd() { * Apply what's in the Settings object. */ void applySettings() { + Serial.println("Applying settings..."); + if (milightClient) { delete milightClient; } @@ -219,19 +223,25 @@ void applySettings() { delete radios; } + Serial.println("Applying transitions.setDefaultPeriod..."); transitions.setDefaultPeriod(settings.defaultTransitionPeriod); + Serial.println("Applying MiLightRadioFactory..."); radioFactory = MiLightRadioFactory::fromSettings(settings); if (radioFactory == NULL) { Serial.println(F("ERROR: unable to construct radio factory")); } + Serial.println("Applying GroupStateStore..."); stateStore = new GroupStateStore(MILIGHT_MAX_STATE_ITEMS, settings.stateFlushInterval); + Serial.println("Applying RadioSwitchboard..."); radios = new RadioSwitchboard(radioFactory, stateStore, settings); + Serial.println("Applying PacketSender..."); packetSender = new PacketSender(*radios, settings, onPacketSentHandler); + Serial.println("Applying MiLightClient..."); milightClient = new MiLightClient( *radios, *packetSender, @@ -242,6 +252,7 @@ void applySettings() { milightClient->onUpdateBegin(onUpdateBegin); milightClient->onUpdateEnd(onUpdateEnd); + Serial.println("Applying MqttClient..."); if (settings.mqttServer().length() > 0) { mqttClient = new MqttClient(settings, milightClient); mqttClient->begin(); @@ -258,39 +269,51 @@ void applySettings() { bulbStateUpdater = new BulbStateUpdater(settings, *mqttClient, *stateStore); } + Serial.println("Applying initMilightUdpServers..."); initMilightUdpServers(); + Serial.println("Applying discoveryServer..."); if (discoveryServer) { + Serial.println("Applying discoveryServer... deleting"); delete discoveryServer; discoveryServer = NULL; } if (settings.discoveryPort != 0) { + Serial.println("Applying discoveryServer... cretae with port " + String(settings.discoveryPort)); discoveryServer = new MiLightDiscoveryServer(settings); - discoveryServer->begin(); + // Serial.println("Applying discoveryServer... beginning..."); + + Serial.println("Applying discoveryServer... TODO!"); + // ESP32: wifi needs to be connected? + // discoveryServer->begin(); + // Serial.println("Applying discoveryServer... begon"); } + Serial.println("Applying ledStatus..."); // update LED pin and operating mode if (ledStatus) { ledStatus->changePin(settings.ledPin); ledStatus->continuous(settings.ledModeOperating); } - WiFi.hostname(settings.hostname); - - WiFiPhyMode_t wifiMode; - switch (settings.wifiMode) { - case WifiMode::B: - wifiMode = WIFI_PHY_MODE_11B; - break; - case WifiMode::G: - wifiMode = WIFI_PHY_MODE_11G; - break; - default: - case WifiMode::N: - wifiMode = WIFI_PHY_MODE_11N; - break; - } - WiFi.setPhyMode(wifiMode); + // WiFi.hostname(settings.hostname); + + // WiFiPhyMode_t wifiMode; + // switch (settings.wifiMode) { + // case WifiMode::B: + // wifiMode = WIFI_PHY_MODE_11B; + // break; + // case WifiMode::G: + // wifiMode = WIFI_PHY_MODE_11G; + // break; + // default: + // case WifiMode::N: + // wifiMode = WIFI_PHY_MODE_11N; + // break; + // } + // WiFi.setPhyMode(wifiMode); + + Serial.println("Settings applied"); } /** @@ -331,17 +354,29 @@ void onGroupDeleted(const BulbId& id) { void setup() { Serial.begin(9600); - String ssid = "ESP" + String(ESP.getChipId()); + + Serial.println("Initializing..."); + + // String ssid = "ESP" + String(ESP.getChipId()); + String ssid = "ESP" + String((uint32_t)ESP.getEfuseMac()); // lower 4 bytes (6 in total) + Serial.println("ssid=" + ssid); + + Serial.println("Initializing SPIFFS..."); // load up our persistent settings from the file system - SPIFFS.begin(); + if(!SPIFFS.begin(true)){ + Serial.println("An Error has occurred while mounting SPIFFS"); + } + Serial.println("Initializing settings..."); Settings::load(settings); applySettings(); + Serial.println("Initializing ledstatus..."); // set up the LED status for wifi configuration ledStatus = new LEDStatus(settings.ledPin); ledStatus->continuous(settings.ledModeWifiConfig); + Serial.println("Initializing MDNS..."); // start up the wifi manager if (! MDNS.begin("milight-hub")) { Serial.println(F("Error setting up MDNS responder")); @@ -351,7 +386,9 @@ void setup() { // allows the "autoConnect" method to be non-blocking which can implement this same functionality. However, // that change is only on the development branch so we are going to continue to use this fork until // that is merged and ready. - wifiManager.setSetupLoopCallback(handleLED); + // wifiManager.setSetupLoopCallback(handleLED); + Serial.println("Initializing WiFiManager..."); + wifiManager.setConfigResetCallback(handleLED); // Allows us to have static IP config in the captive portal. Yucky pointers to pointers, just to have the settings carry through wifiManager.setSaveConfigCallback(wifiExtraSettingsChange); @@ -401,6 +438,11 @@ void setup() { // if the config portal was started, make sure to turn off the config AP WiFi.mode(WIFI_STA); + + // TODO ESP32: udp socket begin needs wifi? + if (discoveryServer) { + discoveryServer->begin(); + } } else { // set LED mode for Wifi failed ledStatus->continuous(settings.ledModeWifiFailed); @@ -410,21 +452,22 @@ void setup() { ESP.restart(); } + Serial.println("Initializing webserver..."); MDNS.addService("http", "tcp", 80); - SSDP.setSchemaURL("description.xml"); - SSDP.setHTTPPort(80); - SSDP.setName("ESP8266 MiLight Gateway"); - SSDP.setSerialNumber(ESP.getChipId()); - SSDP.setURL("/"); - SSDP.setDeviceType("upnp:rootdevice"); - SSDP.begin(); + // SSDP.setSchemaURL("description.xml"); + // SSDP.setHTTPPort(80); + // SSDP.setName("ESP8266 MiLight Gateway"); + // SSDP.setSerialNumber(ESP.getChipId()); + // SSDP.setURL("/"); + // SSDP.setDeviceType("upnp:rootdevice"); + // SSDP.begin(); httpServer = new MiLightHttpServer(settings, milightClient, stateStore, packetSender, radios, transitions); httpServer->onSettingsSaved(applySettings); httpServer->onGroupDeleted(onGroupDeleted); - httpServer->on("/description.xml", HTTP_GET, []() { SSDP.schema(httpServer->client()); }); + // httpServer->on("/description.xml", HTTP_GET, []() { SSDP.schema(httpServer->client()); }); httpServer->begin(); transitions.addListener( @@ -443,6 +486,9 @@ void setup() { } void loop() { + + Serial.println("Loop start"); + httpServer->handleClient(); if (mqttClient) { @@ -472,6 +518,8 @@ void loop() { Serial.println(F("Auto-restart triggered. Restarting...")); ESP.restart(); } + + Serial.println("Loop end"); } #endif \ No newline at end of file From 6190aa568add128aa4a24d0851e193d21816028b Mon Sep 17 00:00:00 2001 From: Maarten Claes Date: Sat, 15 Aug 2020 15:01:42 +0200 Subject: [PATCH 2/5] Compile working again for all envs --- README.md | 11 + lib/ESP/ESPId.cpp | 17 + lib/ESP/ESPId.h | 8 + lib/MQTT/HomeAssistantDiscoveryClient.cpp | 7 +- lib/MQTT/HomeAssistantDiscoveryClient.h | 1 + lib/MQTT/MqttClient.cpp | 2 +- lib/MQTT/MqttClient.h | 1 + lib/MiLightState/GroupStatePersistence.cpp | 5 +- lib/Settings/AboutHelper.cpp | 20 +- lib/Settings/Settings.cpp | 35 +- lib/Udp/MiLightDiscoveryServer.cpp | 14 +- lib/Udp/MiLightUdpServer.cpp | 8 +- lib/Udp/V6MiLightUdpServer.cpp | 8 +- lib/WebServer/MiLightHttpServer.cpp | 91 +- .../.github/CONTRIBUTING.md | 12 - .../.github/ISSUE_TEMPLATE.md | 56 - lib/WiFiManager-2.0.3-alpha/.gitignore | 1 - lib/WiFiManager-2.0.3-alpha/.travis.yml | 53 - lib/WiFiManager-2.0.3-alpha/LICENSE | 22 - lib/WiFiManager-2.0.3-alpha/README.md | 558 ---- lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp | 2966 ----------------- lib/WiFiManager-2.0.3-alpha/WiFiManager.h | 616 ---- .../examples/Advanced/Advanced.ino | 134 - .../AutoConnectWithFSParameters.ino | 175 - ...AutoConnectWithFSParametersAndCustomIP.ino | 172 - .../AutoConnectWithFeedbackLED.ino | 71 - .../examples/Basic/Basic.ino | 41 - .../OnDemandConfigPortal.ino | 347 -- .../AutoConnectNonBlocking.ino | 27 - .../AutoConnectNonBlockingwParams.ino | 36 - .../onDemandNonBlocking.ino | 83 - .../AutoConnectWithFeedback.ino | 42 - .../AutoConnectWithReset.ino | 43 - .../AutoConnectWithStaticIP.ino | 71 - .../AutoConnectWithTimeout.ino | 38 - .../OnDemandConfigPortal.ino | 47 - .../OnDemandWebPortal/onDemandWebPortal.ino | 51 - .../ParamsChildClass/ParamsChildClass.ino | 141 - .../examples/Tests/AnonymousCB.ino | 26 - .../extras/WiFiManager.template.html | 324 -- lib/WiFiManager-2.0.3-alpha/extras/parse.js | 60 - .../extras/png_signal_strength_master.png | Bin 59671 -> 0 bytes lib/WiFiManager-2.0.3-alpha/extras/template.h | 12 - lib/WiFiManager-2.0.3-alpha/extras/test.html | 182 - lib/WiFiManager-2.0.3-alpha/keywords.txt | 39 - lib/WiFiManager-2.0.3-alpha/library.json | 29 - .../library.properties | 9 - lib/WiFiManager-2.0.3-alpha/strings_en.h | 363 -- lib/WiFiManager-2.0.3-alpha/travis/common.sh | 60 - platformio.ini | 51 +- src/main.cpp | 100 +- 51 files changed, 218 insertions(+), 7068 deletions(-) create mode 100644 lib/ESP/ESPId.cpp create mode 100644 lib/ESP/ESPId.h delete mode 100644 lib/WiFiManager-2.0.3-alpha/.github/CONTRIBUTING.md delete mode 100644 lib/WiFiManager-2.0.3-alpha/.github/ISSUE_TEMPLATE.md delete mode 100644 lib/WiFiManager-2.0.3-alpha/.gitignore delete mode 100644 lib/WiFiManager-2.0.3-alpha/.travis.yml delete mode 100644 lib/WiFiManager-2.0.3-alpha/LICENSE delete mode 100644 lib/WiFiManager-2.0.3-alpha/README.md delete mode 100644 lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp delete mode 100644 lib/WiFiManager-2.0.3-alpha/WiFiManager.h delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Advanced/Advanced.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Basic/Basic.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/ParamsChildClass/ParamsChildClass.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/examples/Tests/AnonymousCB.ino delete mode 100644 lib/WiFiManager-2.0.3-alpha/extras/WiFiManager.template.html delete mode 100644 lib/WiFiManager-2.0.3-alpha/extras/parse.js delete mode 100644 lib/WiFiManager-2.0.3-alpha/extras/png_signal_strength_master.png delete mode 100644 lib/WiFiManager-2.0.3-alpha/extras/template.h delete mode 100644 lib/WiFiManager-2.0.3-alpha/extras/test.html delete mode 100644 lib/WiFiManager-2.0.3-alpha/keywords.txt delete mode 100644 lib/WiFiManager-2.0.3-alpha/library.json delete mode 100644 lib/WiFiManager-2.0.3-alpha/library.properties delete mode 100644 lib/WiFiManager-2.0.3-alpha/strings_en.h delete mode 100644 lib/WiFiManager-2.0.3-alpha/travis/common.sh diff --git a/README.md b/README.md index 13ec977a..abf3bcd4 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,14 @@ +# TODO's for ESP32 + +- Implement handleFirmwarePost() and handleFirmwareUpload() in MiLightHttpServer.cpp +- Erase config in MiLightHttpServer.cpp +- Wifi set hostname in main.cpp +- Set Wifi physical (setPhyMode) in main.cpp +- SSDP (Service discovery) support in main.cpp +- LED callback in WiFiManager loop in main.cpp +- Implement other TODO's in main.cpp +- Reset reason in AboutHelper.cpp + # esp8266_milight_hub [![Build Status](https://travis-ci.org/sidoh/esp8266_milight_hub.svg?branch=master)](https://travis-ci.org/sidoh/esp8266_milight_hub) [![License][shield-license]][info-license] This is a replacement for a Milight/LimitlessLED remote/gateway hosted on an ESP8266. Leverages [Henryk Plötz's awesome reverse-engineering work](https://hackaday.io/project/5888-reverse-engineering-the-milight-on-air-protocol). diff --git a/lib/ESP/ESPId.cpp b/lib/ESP/ESPId.cpp new file mode 100644 index 00000000..51ff0bf2 --- /dev/null +++ b/lib/ESP/ESPId.cpp @@ -0,0 +1,17 @@ +#include + +#ifdef ESP8266 +uint32_t getESPId() +{ + return ESP.getChipId(); +} +#elif ESP32 +uint32_t getESPId() +{ + uint32_t id = 0; + for(int i=0; i<17; i=i+8) { + id |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i; + } + return id; +} +#endif \ No newline at end of file diff --git a/lib/ESP/ESPId.h b/lib/ESP/ESPId.h new file mode 100644 index 00000000..96e8c149 --- /dev/null +++ b/lib/ESP/ESPId.h @@ -0,0 +1,8 @@ +#ifndef _ESPID_H +#define _ESPID_H + +#include + +uint32_t getESPId(); + +#endif \ No newline at end of file diff --git a/lib/MQTT/HomeAssistantDiscoveryClient.cpp b/lib/MQTT/HomeAssistantDiscoveryClient.cpp index 23d0f0ae..8e99a570 100644 --- a/lib/MQTT/HomeAssistantDiscoveryClient.cpp +++ b/lib/MQTT/HomeAssistantDiscoveryClient.cpp @@ -46,8 +46,7 @@ void HomeAssistantDiscoveryClient::addConfig(const char* alias, const BulbId& bu deviceMetadata[F("sw_version")] = QUOTE(MILIGHT_HUB_VERSION); JsonArray identifiers = deviceMetadata.createNestedArray(F("identifiers")); - // identifiers.add(ESP.getChipId()); - identifiers.add(ESP.getEfuseMac()); + identifiers.add(getESPId()); bulbId.serialize(identifiers); @@ -140,9 +139,7 @@ String HomeAssistantDiscoveryClient::buildTopic(const BulbId& bulbId) { topic += "light/"; // Use a static ID that doesn't depend on configuration. - // topic += "milight_hub_" + String(ESP.getChipId()); - topic += "milight_hub_" + String((uint32_t)ESP.getEfuseMac()); // lower 4 bytes (6 in total) - + topic += "milight_hub_" + String(getESPId()); // make the object ID based on the actual parameters rather than the alias. topic += "/"; diff --git a/lib/MQTT/HomeAssistantDiscoveryClient.h b/lib/MQTT/HomeAssistantDiscoveryClient.h index ee6fc798..17fef90e 100644 --- a/lib/MQTT/HomeAssistantDiscoveryClient.h +++ b/lib/MQTT/HomeAssistantDiscoveryClient.h @@ -2,6 +2,7 @@ #include #include +#include #include class HomeAssistantDiscoveryClient { diff --git a/lib/MQTT/MqttClient.cpp b/lib/MQTT/MqttClient.cpp index 8c87db62..8cf3c116 100644 --- a/lib/MQTT/MqttClient.cpp +++ b/lib/MQTT/MqttClient.cpp @@ -56,7 +56,7 @@ void MqttClient::begin() { bool MqttClient::connect() { char nameBuffer[30]; - sprintf_P(nameBuffer, PSTR("milight-hub-%u"), ESP.getEfuseMac()); + sprintf_P(nameBuffer, PSTR("milight-hub-%u"), getESPId()); #ifdef MQTT_DEBUG diff --git a/lib/MQTT/MqttClient.h b/lib/MQTT/MqttClient.h index dc601c4b..b5a2bf20 100644 --- a/lib/MQTT/MqttClient.h +++ b/lib/MQTT/MqttClient.h @@ -3,6 +3,7 @@ #include #include #include +#include #ifndef MQTT_CONNECTION_ATTEMPT_FREQUENCY #define MQTT_CONNECTION_ATTEMPT_FREQUENCY 5000 diff --git a/lib/MiLightState/GroupStatePersistence.cpp b/lib/MiLightState/GroupStatePersistence.cpp index df8b3657..75572ad1 100644 --- a/lib/MiLightState/GroupStatePersistence.cpp +++ b/lib/MiLightState/GroupStatePersistence.cpp @@ -1,6 +1,9 @@ #include #include -#include + +#ifdef ESP32 + #include +#endif static const char FILE_PREFIX[] = "group_states/"; diff --git a/lib/Settings/AboutHelper.cpp b/lib/Settings/AboutHelper.cpp index f6b49ccc..72e098a9 100644 --- a/lib/Settings/AboutHelper.cpp +++ b/lib/Settings/AboutHelper.cpp @@ -1,8 +1,12 @@ #include #include #include -// #include -#include + +#ifdef ESP8266 + #include +#elif ESP32 + #include +#endif String AboutHelper::generateAboutString(bool abbreviated) { DynamicJsonDocument buffer(1024); @@ -19,11 +23,19 @@ void AboutHelper::generateAboutObject(JsonDocument& obj, bool abbreviated) { obj["firmware"] = QUOTE(FIRMWARE_NAME); obj["version"] = QUOTE(MILIGHT_HUB_VERSION); obj["ip_address"] = WiFi.localIP().toString(); -// obj["reset_reason"] = ESP.getResetReason(); +#ifdef ESP8266 + obj["reset_reason"] = ESP.getResetReason(); +#elif ESP32 + // TODO get reset reason +#endif if (! abbreviated) { obj["variant"] = QUOTE(FIRMWARE_VARIANT); obj["free_heap"] = ESP.getFreeHeap(); -// obj["arduino_version"] = ESP.getCoreVersion(); +#ifdef ESP8266 + obj["arduino_version"] = ESP.getCoreVersion(); +#elif ESP32 + obj["arduino_version"] = ESP.getSdkVersion(); +#endif } } \ No newline at end of file diff --git a/lib/Settings/Settings.cpp b/lib/Settings/Settings.cpp index 9df80f0b..f838e448 100644 --- a/lib/Settings/Settings.cpp +++ b/lib/Settings/Settings.cpp @@ -1,11 +1,14 @@ #include #include #include -#include #include #include #include +#ifdef ESP32 + #include +#endif + #define PORT_POSITION(s) ( s.indexOf(':') ) GatewayConfig::GatewayConfig(uint16_t deviceId, uint16_t port, uint8_t protocolVersion) @@ -62,14 +65,12 @@ void Settings::updateGatewayConfigs(JsonArray arr) { } } -void Settings::patch(JsonObject parsedSettings) { +void Settings::patch(JsonObject parsedSettings) { if (parsedSettings.isNull()) { Serial.println(F("Skipping patching loaded settings. Parsed settings was null.")); return; } - Serial.println("Patching settings..."); - this->setIfPresent(parsedSettings, "admin_username", adminUsername); this->setIfPresent(parsedSettings, "admin_password", adminPassword); this->setIfPresent(parsedSettings, "ce_pin", cePin); @@ -105,76 +106,59 @@ void Settings::patch(JsonObject parsedSettings) { this->setIfPresent(parsedSettings, "home_assistant_discovery_prefix", homeAssistantDiscoveryPrefix); this->setIfPresent(parsedSettings, "default_transition_period", defaultTransitionPeriod); - if (parsedSettings.containsKey("wifi_mode")) { - Serial.println("Patching wifi_mode"); this->wifiMode = wifiModeFromString(parsedSettings["wifi_mode"]); } - if (parsedSettings.containsKey("rf24_channels")) { - Serial.println("Patching rf24_channels"); JsonArray arr = parsedSettings["rf24_channels"]; rf24Channels = JsonHelpers::jsonArrToVector(arr, RF24ChannelHelpers::valueFromName); } if (parsedSettings.containsKey("rf24_listen_channel")) { - Serial.println("Patching rf24_listen_channel"); this->rf24ListenChannel = RF24ChannelHelpers::valueFromName(parsedSettings["rf24_listen_channel"]); } if (parsedSettings.containsKey("rf24_power_level")) { - Serial.println("Patching rf24_power_level"); this->rf24PowerLevel = RF24PowerLevelHelpers::valueFromName(parsedSettings["rf24_power_level"]); } if (parsedSettings.containsKey("led_mode_wifi_config")) { - Serial.println("Patching led_mode_wifi_config"); this->ledModeWifiConfig = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_config"]); } if (parsedSettings.containsKey("led_mode_wifi_failed")) { - Serial.println("Patching led_mode_wifi_failed"); this->ledModeWifiFailed = LEDStatus::stringToLEDMode(parsedSettings["led_mode_wifi_failed"]); } if (parsedSettings.containsKey("led_mode_operating")) { - Serial.println("Patching led_mode_operating"); this->ledModeOperating = LEDStatus::stringToLEDMode(parsedSettings["led_mode_operating"]); } if (parsedSettings.containsKey("led_mode_packet")) { - Serial.println("Patching led_mode_packet"); this->ledModePacket = LEDStatus::stringToLEDMode(parsedSettings["led_mode_packet"]); } if (parsedSettings.containsKey("radio_interface_type")) { - Serial.println("Patching radio_interface_type"); this->radioInterfaceType = Settings::typeFromString(parsedSettings["radio_interface_type"]); } if (parsedSettings.containsKey("device_ids")) { - Serial.println("Patching device_ids"); JsonArray arr = parsedSettings["device_ids"]; updateDeviceIds(arr); } if (parsedSettings.containsKey("gateway_configs")) { - Serial.println("Patching gateway_configs"); JsonArray arr = parsedSettings["gateway_configs"]; updateGatewayConfigs(arr); } if (parsedSettings.containsKey("group_state_fields")) { - Serial.println("Patching group_state_fields"); JsonArray arr = parsedSettings["group_state_fields"]; groupStateFields = JsonHelpers::jsonArrToVector(arr, GroupStateFieldHelpers::getFieldByName); } if (parsedSettings.containsKey("group_id_aliases")) { - Serial.println("Patching group_id_aliases"); parseGroupIdAliases(parsedSettings); } - - Serial.println("Patched settings"); } std::map::const_iterator Settings::findAlias(MiLightRemoteType deviceType, uint16_t deviceId, uint8_t groupId) { @@ -228,21 +212,14 @@ void Settings::dumpGroupIdAliases(JsonObject json) { void Settings::load(Settings& settings) { - Serial.println("Settings loading..."); - if (SPIFFS.exists(SETTINGS_FILE)) { // Clear in-memory settings settings = Settings(); - Serial.println("Settings loading from file " + String(SETTINGS_FILE)); - File f = SPIFFS.open(SETTINGS_FILE, "r"); - Serial.println("Settings loading... file opened"); - DynamicJsonDocument json(MILIGHT_HUB_SETTINGS_BUFFER_SIZE); auto error = deserializeJson(json, f); - Serial.println("Settings loading... json deserialized"); f.close(); if (! error) { @@ -253,8 +230,6 @@ void Settings::load(Settings& settings) { Serial.println(error.c_str()); } } else { - Serial.println("Settings loading... no existing file found. Loadingd defaults."); - settings.save(); } } diff --git a/lib/Udp/MiLightDiscoveryServer.cpp b/lib/Udp/MiLightDiscoveryServer.cpp index a5af70f9..9f869c5d 100644 --- a/lib/Udp/MiLightDiscoveryServer.cpp +++ b/lib/Udp/MiLightDiscoveryServer.cpp @@ -1,7 +1,11 @@ #include #include -// #include -#include + +#ifdef ESP8266 + #include +#elif ESP32 + #include +#endif const char V3_SEARCH_STRING[] = "Link_Wi-Fi"; const char V6_SEARCH_STRING[] = "HF-A11ASSISTHREAD"; @@ -25,9 +29,7 @@ MiLightDiscoveryServer::~MiLightDiscoveryServer() { } void MiLightDiscoveryServer::begin() { - Serial.println("MiLightDiscoveryServer::begin beginning..."); socket.begin(settings.discoveryPort); - Serial.println("MiLightDiscoveryServer::begin begon"); } void MiLightDiscoveryServer::handleClient() { @@ -88,6 +90,10 @@ void MiLightDiscoveryServer::sendResponse(char* buffer) { #endif socket.beginPacket(socket.remoteIP(), socket.remotePort()); +#ifdef ESP8266 + socket.write(buffer); +#elif ESP32 socket.write(*buffer); +#endif socket.endPacket(); } diff --git a/lib/Udp/MiLightUdpServer.cpp b/lib/Udp/MiLightUdpServer.cpp index 8354e0d3..8a51bc96 100644 --- a/lib/Udp/MiLightUdpServer.cpp +++ b/lib/Udp/MiLightUdpServer.cpp @@ -1,8 +1,12 @@ #include #include #include -// #include -#include + +#ifdef ESP8266 + #include +#elif ESP32 + #include +#endif MiLightUdpServer::MiLightUdpServer(MiLightClient*& client, uint16_t port, uint16_t deviceId) : client(client), diff --git a/lib/Udp/V6MiLightUdpServer.cpp b/lib/Udp/V6MiLightUdpServer.cpp index 3af23c5d..b4d7403a 100644 --- a/lib/Udp/V6MiLightUdpServer.cpp +++ b/lib/Udp/V6MiLightUdpServer.cpp @@ -1,10 +1,14 @@ #include -#include -// #include #include #include #include +#ifdef ESP8266 + #include +#elif ESP32 + #include +#endif + #define MATCHES_PACKET(packet1) ( \ matchesPacket(packet1, size(packet1), packet, packetSize) \ ) diff --git a/lib/WebServer/MiLightHttpServer.cpp b/lib/WebServer/MiLightHttpServer.cpp index 9fe6204c..f07eecb2 100644 --- a/lib/WebServer/MiLightHttpServer.cpp +++ b/lib/WebServer/MiLightHttpServer.cpp @@ -1,5 +1,4 @@ #include -#include #include #include #include @@ -10,6 +9,10 @@ #include #include +#ifdef ESP32 + #include +#endif + using namespace std::placeholders; void MiLightHttpServer::begin() { @@ -126,7 +129,11 @@ void MiLightHttpServer::handleSystemPost(RequestContext& request) { server.send_P(200, TEXT_PLAIN, PSTR("true")); delay(100); - // ESP.eraseConfig(); +#ifdef ESP8266 + ESP.eraseConfig(); +#elif ESP32 + // TODO erase config +#endif delay(100); ESP.restart(); @@ -226,47 +233,55 @@ void MiLightHttpServer::handleUpdateSettingsPost(RequestContext& request) { } void MiLightHttpServer::handleFirmwarePost() { - // server.sendHeader("Connection", "close"); - // server.sendHeader("Access-Control-Allow-Origin", "*"); - - // if (Update.hasError()) { - // server.send_P( - // 500, - // TEXT_PLAIN, - // PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.") - // ); - // } else { - // server.send_P( - // 200, - // TEXT_PLAIN, - // PSTR("Success. Device will now reboot.") - // ); - // } +#ifdef ESP8266 + server.sendHeader("Connection", "close"); + server.sendHeader("Access-Control-Allow-Origin", "*"); + + if (Update.hasError()) { + server.send_P( + 500, + TEXT_PLAIN, + PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.") + ); + } else { + server.send_P( + 200, + TEXT_PLAIN, + PSTR("Success. Device will now reboot.") + ); + } - // delay(1000); + delay(1000); - // ESP.restart(); + ESP.restart(); +#elif ESP32 + // TODO implement firmware post +#endif } void MiLightHttpServer::handleFirmwareUpload() { - // HTTPUpload& upload = server.upload(); - // if(upload.status == UPLOAD_FILE_START){ - // WiFiUDP::stopAll(); - // uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; - // if(!Update.begin(maxSketchSpace)){//start with max available size - // Update.printError(Serial); - // } - // } else if(upload.status == UPLOAD_FILE_WRITE){ - // if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){ - // Update.printError(Serial); - // } - // } else if(upload.status == UPLOAD_FILE_END){ - // if(Update.end(true)){ //true to set the size to the current progress - // } else { - // Update.printError(Serial); - // } - // } - // yield(); +#ifdef ESP8266 + HTTPUpload& upload = server.upload(); + if(upload.status == UPLOAD_FILE_START){ + WiFiUDP::stopAll(); + uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; + if(!Update.begin(maxSketchSpace)){//start with max available size + Update.printError(Serial); + } + } else if(upload.status == UPLOAD_FILE_WRITE){ + if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){ + Update.printError(Serial); + } + } else if(upload.status == UPLOAD_FILE_END){ + if(Update.end(true)){ //true to set the size to the current progress + } else { + Update.printError(Serial); + } + } + yield(); +#elif ESP32 + // TODO implement firmware upload +#endif } diff --git a/lib/WiFiManager-2.0.3-alpha/.github/CONTRIBUTING.md b/lib/WiFiManager-2.0.3-alpha/.github/CONTRIBUTING.md deleted file mode 100644 index 6760b62f..00000000 --- a/lib/WiFiManager-2.0.3-alpha/.github/CONTRIBUTING.md +++ /dev/null @@ -1,12 +0,0 @@ -## Contributing PRs and ISSUES - -The development branch is the active branch, no features or bugs will be fixed against master ( hotfixes may be considered ). - -Please test against development branch before submitting issues, issues against master will be closed, - -PRs against master may be kept open if provides something useful to other members. - -Please open issues before sumbitting PRs against development, as commits might be occuring very frequently. - -### Documentation is in progress -https://github.com/tzapu/WiFiManager/issues/500 diff --git a/lib/WiFiManager-2.0.3-alpha/.github/ISSUE_TEMPLATE.md b/lib/WiFiManager-2.0.3-alpha/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 2deb9427..00000000 --- a/lib/WiFiManager-2.0.3-alpha/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,56 +0,0 @@ -## PLEASE TRY DEVELOPMENT BRANCH before submitting bugs on release or master, in case they were already fixed. ## - -Issues without basic info will be ignored or closed! - -Please fill the info fields, it helps to get you faster support ;) - -if you have a stack dump decode it: -https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/stack_dump.rst - -for better debug messages: -https://github.com/esp8266/Arduino/blob/master/doc/Troubleshooting/debugging.rst - ------------------------------ Remove above ----------------------------- - -### Basic Infos - -#### Hardware -WiFimanager Branch/Release: Development - -Esp8266/Esp32: - -Hardware: ESP-12e, esp01, esp25 - -Core Version: 2.4.0, staging - -### Description - -Problem description - -### Settings in IDE - -Module: NodeMcu, Wemos D1 - -Additional libraries: - -### Sketch - -```cpp - -#include - -void setup() { - -} - -void loop() { - -} -``` - -### Debug Messages - -``` -messages here -``` - diff --git a/lib/WiFiManager-2.0.3-alpha/.gitignore b/lib/WiFiManager-2.0.3-alpha/.gitignore deleted file mode 100644 index d837572a..00000000 --- a/lib/WiFiManager-2.0.3-alpha/.gitignore +++ /dev/null @@ -1 +0,0 @@ -platformio.ini diff --git a/lib/WiFiManager-2.0.3-alpha/.travis.yml b/lib/WiFiManager-2.0.3-alpha/.travis.yml deleted file mode 100644 index cc63c554..00000000 --- a/lib/WiFiManager-2.0.3-alpha/.travis.yml +++ /dev/null @@ -1,53 +0,0 @@ -language: c -sudo: false - -before_install: - - "/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16" - - sleep 3 - - export DISPLAY=:1.0 - - wget http://downloads.arduino.cc/arduino-1.8.10-linux64.tar.xz - - tar xf arduino-1.8.10-linux64.tar.xz - - sudo mv arduino-1.8.10 /usr/local/share/arduino - - sudo ln -s /usr/local/share/arduino/arduino /usr/local/bin/arduino - -install: - - ln -s $PWD /usr/local/share/arduino/libraries/WiFiManager - - arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json,http://dl.espressif.com/dl/package_esp32_index.json" --save-prefs - - arduino --install-library "ArduinoJson:5.13.2" - - arduino --install-boards esp8266:esp8266 - - arduino --pref "compiler.warning_level=all" --save-prefs -# install esp32 - - arduino --install-boards esp32:esp32 - # - pushd . - # - mkdir -p ~/Arduino/hardware/espressif - # - cd ~/Arduino/hardware/espressif - # - git clone https://github.com/espressif/arduino-esp32.git esp32 - # - cd esp32 - # - git submodule update --init --recursive - # - cd tools - # - python2 get.py - # - popd -# esp32 needs WebServer_tng for now - # - git clone https://github.com/bbx10/WebServer_tng.git /usr/local/share/arduino/libraries/WebServer_tng - -script: - - "echo $PWD" - - "echo $HOME" - - "ls $PWD" - - source $TRAVIS_BUILD_DIR/travis/common.sh - - arduino --board esp8266:esp8266:generic:xtal=80,eesz=4M1M,FlashMode=qio,FlashFreq=80,dbg=Serial,lvl=CORE --save-prefs - - build_examples - - arduino --board esp32:esp32:esp32:FlashFreq=80,FlashSize=4M,DebugLevel=info --save-prefs -# some examples fail (SPIFFS defines differ esp32 vs esp8266) so we exclude them - - build_examples -# - arduino -v --verbose-build --verify $PWD/examples/AutoConnect/AutoConnect.ino - -# no coverage generated, no need to run -# -#after_success: -# - bash <(curl -s https://codecov.io/bash) - -notifications: - email: - on_success: change - on_failure: change diff --git a/lib/WiFiManager-2.0.3-alpha/LICENSE b/lib/WiFiManager-2.0.3-alpha/LICENSE deleted file mode 100644 index 1dabff57..00000000 --- a/lib/WiFiManager-2.0.3-alpha/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 tzapu - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/lib/WiFiManager-2.0.3-alpha/README.md b/lib/WiFiManager-2.0.3-alpha/README.md deleted file mode 100644 index 9405479f..00000000 --- a/lib/WiFiManager-2.0.3-alpha/README.md +++ /dev/null @@ -1,558 +0,0 @@ - -# WiFiManager -## DEVELOPMENT BRANCH - -ESP8266 WiFi Connection manager with fallback web configuration portal - -:warning: This Documentation is out of date for this branch, see notes below - -[![Build Status](https://travis-ci.org/tzapu/WiFiManager.svg?branch=development)](https://travis-ci.org/tzapu/WiFiManager) - -![ESP8266](https://img.shields.io/badge/ESP-8266-000000.svg?longCache=true&style=flat&colorA=CC101F) -![ESP32](https://img.shields.io/badge/ESP-32-000000.svg?longCache=true&style=flat&colorA=CC101F) - -The configuration portal is of the captive variety, so on various devices it will present the configuration dialogue as soon as you connect to the created access point. - -First attempt at a library. Lots more changes and fixes to do. Contributions are welcome. - -**This works with the ESP8266 Arduino platform** - -[https://github.com/esp8266/Arduino](https://github.com/esp8266/Arduino) - -**This works with the ESP32 Arduino platform** - -[https://github.com/espressif/arduino-esp32](https://github.com/espressif/arduino-esp32) - -### Known Issues -* Documentation needs to be updated, see [https://github.com/tzapu/WiFiManager/issues/500](https://github.com/tzapu/WiFiManager/issues/500) - -## Contents - - [How it works](#how-it-works) - - [Wishlist](#wishlist) - - [Quick start](#quick-start) - - Installing - - [Arduino - Through Library Manager](#install-through-library-manager) - - [Arduino - From Github](#checkout-from-github) - - [PlatformIO](#install-using-platformio) - - [Using](#using) - - [Documentation](#documentation) - - [Access Point Password](#password-protect-the-configuration-access-point) - - [Callbacks](#callbacks) - - [Configuration Portal Timeout](#configuration-portal-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) - - [Troubleshooting](#troubleshooting) - - [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 -- because of the Captive Portal and the DNS server you will either get a 'Join to network' type of popup or get any domain you try to access redirected to the configuration portal -- choose one of the access points scanned, enter password, click save -- ESP will try to connect. If successful, it relinquishes control back to your app. If not, reconnect to AP and reconfigure. -- There are options to change this behavior or manually start the configportal and webportal independantly as well as run them in non blocking mode. - -## How It Looks -![ESP8266 WiFi Captive Portal Homepage](http://i.imgur.com/YPvW9eql.png) ![ESP8266 WiFi Captive Portal Configuration](http://i.imgur.com/oicWJ4gl.png) - -## Wishlist -- [x] remove dependency on EEPROM library -- [x] move HTML Strings to PROGMEM -- [x] cleanup and streamline code (although this is ongoing) -- [x] if timeout is set, extend it when a page is fetched in AP mode -- [x] add ability to configure more parameters than ssid/password -- [x] maybe allow setting ip of ESP after reboot -- [x] add to Arduino Library Manager -- [x] add to PlatformIO -- [ ] add multiple sets of network credentials -- [x] allow users to customize CSS -- [ ] rewrite documentation for simplicity, based on scenarios/goals - -### Development -- [x] ESP32 support -- [x] rely on the SDK's built in auto connect more than forcing a connect -- [x] add non blocking mode -- [x] easy customization of strings -- [x] hostname support -- [x] fix various bugs and workarounds for esp SDK issues -- [x] additional info page items -- [x] last status display / faiilure reason -- [x] customizeable menu -- [x] seperate custom params page -- [x] ondemand webportal -- [x] complete refactor of code to segment functions -- [x] wiif scan icons or percentage display -- [x] invert class for dark mode -- [x] more template tokens -- [x] progmem for all strings -- [ ] new callbacks -- [ ] new callouts / filters -- [ ] shared web server instance -- [x] latest esp idf/sdk support -- [x] wm is now non persistent, will not erase or change stored esp config on esp8266 -- [x] tons of debugging output / levels -- [ ] disable captiveportal -- [ ] preload wiifscans, faster page loads -- [ ] softap stability fixes when sta is not connected - - -## Quick Start - -### Installing -You can either install through the Arduino Library Manager or checkout the latest changes or a release from github - -#### Install through Library Manager -__Currently version 0.8+ works with release 2.4.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ - - in Arduino IDE got to Sketch/Include Library/Manage Libraries - ![Manage Libraries](http://i.imgur.com/9BkEBkR.png) - - - search for WiFiManager - ![WiFiManager package](http://i.imgur.com/18yIai8.png) - - - click Install and start [using it](#using) - -#### Checkout from github -__Github version works with release 2.4.0 or newer of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino)__ -- Checkout library to your Arduino libraries folder - -### Using -- Include in your sketch -```cpp -#include //https://github.com/tzapu/WiFiManager WiFi Configuration Magic -``` - -- Initialize library, in your setup function add, NOTEif you are using non blocking you will make sure you create this in global scope or handle appropriatly , it will not work if in setup and using non blocking mode. -```cpp -WiFiManager wifiManager; -``` - -- Also in the setup function add -```cpp -//first parameter is name of access point, second is the password -wifiManager.autoConnect("AP-NAME", "AP-PASSWORD"); -``` -if you just want an unsecured access point -```cpp -wifiManager.autoConnect("AP-NAME"); -``` -or if you want to use and auto generated name from 'ESP' and the esp's Chip ID use -```cpp -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](https://github.com/tzapu/WiFiManager/tree/master/examples). - -#### Install Using PlatformIO - -[PlatformIO](https://platformio.org/) is an emerging ecosystem for IoT development, and -is an alternative to using the Arduino IDE. Install `WiFiManager` -using the platformio [library manager](https://docs.platformio.org/en/latest/librarymanager/index.htm) in your editor, -or using the [PlatformIO Core CLI](https://docs.platformio.org/en/latest/userguide/demo.html#library-manager), -or by adding it to your `platformio.ini` as shown below (recommended approach). - -The simplest way is to open the `platformio.ini` file at the root of your project, and `WifiManager` to the common top-level env -`lib_deps` key like so: - -``` -[env] -lib_deps = - WiFiManager -``` - -If you want to install the development branch, then you'll need to use the `repository#tag` format instead: - -``` -[env] -lib_deps = - https://github.com/tzapu/WiFiManager.git#development -``` - -## 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) -```cpp -wifiManager.autoConnect("AutoConnectAP", "password") -``` - -#### 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()` -```cpp -wifiManager.setAPCallback(configModeCallback); -``` -`configModeCallback` declaration and example -```cpp -void configModeCallback (WiFiManager *myWiFiManager) { - Serial.println("Entered config mode"); - Serial.println(WiFi.softAPIP()); - - Serial.println(myWiFiManager->getConfigPortalSSID()); -} -``` - -##### 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; -} -``` - -#### 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.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) - -#### 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()`. __Do not use BOTH.__ - -Example usage -```cpp -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) - -#### Exiting from the Configuration Portal -Normally, once entered, the configuration portal will continue to loop until WiFi credentials have been successfully entered or a timeout is reached. -If you'd prefer to exit without joining a WiFi network, say becuase you're going to put the ESP into AP mode, then press the "Exit" button -on the main webpage. -If started via `autoConnect` or `startConfigPortal` then it will return `false (portalAbortResult)` - -#### Custom Parameters -You can use WiFiManager to collect more parameters than just SSID and password. -This could be helpful for configuring stuff like MQTT host and port, [blynk](http://www.blynk.cc) or [emoncms](http://emoncms.org) tokens, just to name a few. -**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. -You should also take a look at adding custom HTML to your form. - -- 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 -You can set a custom IP for both AP (access point, config mode) and STA (station mode, client mode, normal project state) - -##### 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.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); -``` - -##### 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)); // optional DNS 4th argument -``` -There are a couple of examples in the examples folder that show you how to set a static IP and even how to configure it through the web configuration portal. - -NOTE: You should fill DNS server if you have HTTP requests with hostnames or syncronize time (NTP). It's the same as gateway ip or a popular (Google DNS: 8.8.8.8). - -#### Custom HTML, CSS, Javascript -There are various ways in which you can inject custom HTML, CSS or Javascript into the configuration portal. -The options are: -- inject custom head element -You can use this to any html bit to the head of the configuration portal. If you add a `"); -``` -- inject a custom bit of html in the configuration/param form -```cpp -WiFiManagerParameter custom_text("

This is just a text paragraph

"); -wifiManager.addParameter(&custom_text); -``` -- inject a custom bit of html in a configuration form element -Just add the bit you want added as the last parameter to the custom parameter constructor. -```cpp -WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "iot.eclipse", 40, " readonly"); -wifiManager.addParameter(&custom_mqtt_server); -``` - -#### Theming -You can customize certain elements of the default template with some builtin classes -```CPP -wifiManager.setClass("invert"); // dark theme -wifiManager.setScanDispPerc(true); // display percentages instead of graphs for RSSI -``` -There are additional classes in the css you can use in your custom html , see the example template. - -#### Filter Networks -You can filter networks based on signal quality and show/hide duplicate networks. - -- 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%; - -- You can also remove or show duplicate networks (default is remove). -Use this function to show (or hide) all networks. -```cpp -wifiManager.setRemoveDuplicateAPs(false); -``` - -#### Debug -Debug is enabled by default on `Serial` in non-stable releases. To disable add before autoConnect/startConfigPortal -```cpp -wifiManager.setDebugOutput(false); -``` - -You can pass in a custom stream via constructor -```CPP -WiFiManager wifiManager(Serial1); -``` - -You can customize the debug level by changing `_debugLevel` in source -options are: -* DEBUG_ERROR -* DEBUG_NOTIFY -* DEBUG_VERBOSE -* DEBUG_DEV -* DEBUG_MAX - -## Troubleshooting -If you get compilation errors, more often than not, you may need to install a newer version of the ESP8266 core for Arduino. - -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. - -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`. - -If trying to connect ends up in an endless loop, try to add `setConnectTimeout(60)` before `autoConnect();`. The parameter is timeout to try connecting in seconds. - -I get stuck in ap mode when the power goes out or modem resets, try a setConfigPortalTimeout(seconds). This will cause the configportal to close after no activity, and you can reboot or attempt reconnection in your code. - -## Releases -### 1.0.1 - -### Development Overview - -#### Added Public Methods -`setConfigPortalBlocking` - -`setShowStaticFields` - -`setCaptivePortalEnable` - -`setRestorePersistent` - -`setCaptivePortalClientCheck` - -`setWebPortalClientCheck` - -`startWebPortal` - -`stopWebPortal` - -`process` - -`disconnect` - -`erase` - -` debugSoftAPConfig` - -` debugPlatformInfo` - -`setScanDispPerc` - -`setHostname` - -`setMenu(menu_page_t[])` - -`setWiFiAutoReconnect` - -` setSTAStaticIPConfig(..,dns)` - -`setShowDnsFields` - -`getLastConxResult` - -`getWLStatusString` - -`getModeString` - -`getWiFiIsSaved` - -`setShowInfoErase` - -`setEnableConfigPortal` - -`setCountry` - -`setClass` - -`htmleEtities` - - -#### WiFiManagerParameter -`WiFiManagerParameter(id,label)` - -`WiFiManagerParameter.setValue(value,length)` - -`getParameters` - -`getParametersCount` - - -#### Constructors -`WiFiManager(Stream& consolePort)` - -#### define flags -❗️ **Defines cannot be set in user sketches** -`#define WM_MDNS // use MDNS` - -`#define WM_FIXERASECONFIG // use erase flash fix, esp8266 2.4.0` - -`#define WM_ERASE_NVS // esp32 erase(true) will erase NVS` - -`#include // esp32 info page will show last reset reasons if this file is included` - -#### Changes Overview -- ESP32 support ( fairly stable ) -- complete refactor of strings `strings_en.h` -- adds new tokens for wifiscan, and some classes (left , invert icons, MSG color) -- adds status callout panel default, primary, special colors -- adds tons of info on info page, and erase capability -- adds signal icons, replaces percentage ( has hover titles ) -- adds labels to all inputs (replaces placeholders) -- all html ( and eventually all strings except debug) moved to `strings_en.h` -- added additional debugging, compressed debug lines, debuglevels -- persistent disabled, and restored via de/con-stuctor (uses `setRestorePersistent`) -- should retain all user modes including AP, should not overwrite or persist user modes or configs,even STA (`storeSTAmode`) (BUGGY) -- ⚠️ return values may have changed depending on portal abort, or timeout ( `portalTimeoutResult`,`portalAbortResult`) -- params memory is auto allocated by increment of `WIFI_MANAGER_MAX_PARAMS(5)` when exceeded, user no longer needs to specify this at all. -- addparameter now returns bool, and it returns false if param ID is not alphanum [0-9,A-Z,a-z,_] -- param field ids allow {I} token to use param_n instead of string in case someones wants to change this due to i18n or character issues -- provides `#DEFINE FIXERASECONFIG` to help deal with https://github.com/esp8266/Arduino/pull/3635 -- failure reason reporting on portal -- set esp8266 sta hostname, esp32 sta+ap hostname ( DHCP client id) -- pass in debug stream in constructor WiFiManager(Stream& consolePort) -- you can force ip fields off with showxfields(false) if you set _disableIpFields=true -- param menu/page (setup) added to separate params from wifi page, handled automatically by setMenu -- set custom root menu -- disable configportal on autoconnect -- wm parameters init is now protected, allowing child classes, example included -- wifiscans are precached and async for faster page loads, refresh forces rescan -- adds esp32 gettemperature ( currently commented out, useful for relative measurement only ) - -#### 0.12 -- removed 204 header response -- fixed incompatibility with other libs using isnan and other std:: functions without namespace - -##### 0.11 -- a lot more reliable reconnecting to networks -- custom html in custom parameters (for read only params) -- custom html in custom parameter form (like labels) -- custom head element (like custom css) -- sort networks based on signal quality -- remove duplicate networks - -##### 0.10 -- some css changes -- bug fixes and speed improvements -- added an alternative to waitForConnectResult() for debugging -- changed `setTimeout(seconds)` to `setConfigPortalTimeout(seconds)` - -### 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__ - -The esp8266 and esp32 arduino and idf maintainers! - -[Shawn A aka tablatronix](https://github.com/tablatronix) - -[liebman](https://github.com/liebman) - -[Evgeny Dontsov](https://github.com/dontsovcmc) - -[Chris Marrin](https://github.com/cmarrin) - -[bbx10](https://github.com/bbx10) - -[kentaylor](https://github.com/kentaylor) - -[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) - -[jonathanendersby](https://github.com/jonathanendersby) - -[walthercarsten](https://github.com/walthercarsten) - -And countless others - -#### Inspiration - * http://www.esp8266.com/viewtopic.php?f=29&t=2520 - * https://github.com/chriscook8/esp-arduino-apboot - * https://github.com/esp8266/Arduino/tree/master/libraries/DNSServer/examples/CaptivePortalAdvanced - * Built by AlexT https://github.com/tzapu - diff --git a/lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp b/lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp deleted file mode 100644 index 1686a3e2..00000000 --- a/lib/WiFiManager-2.0.3-alpha/WiFiManager.cpp +++ /dev/null @@ -1,2966 +0,0 @@ -/** - * WiFiManager.cpp - * - * WiFiManager, a library for the ESP8266/Arduino platform - * for configuration of WiFi credentials using a Captive Portal - * - * @author Creator tzapu - * @author tablatronix - * @version 0.0.0 - * @license MIT - */ - -#include "WiFiManager.h" - -#if defined(ESP8266) || defined(ESP32) - -#ifdef ESP32 -uint8_t WiFiManager::_lastconxresulttmp = WL_IDLE_STATUS; -#endif - -/** - * -------------------------------------------------------------------------------- - * WiFiManagerParameter - * -------------------------------------------------------------------------------- -**/ - -WiFiManagerParameter::WiFiManagerParameter() { - WiFiManagerParameter(""); -} - -WiFiManagerParameter::WiFiManagerParameter(const char *custom) { - _id = NULL; - _label = NULL; - _length = 1; - _value = NULL; - _labelPlacement = WFM_LABEL_BEFORE; - _customHTML = custom; -} - -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label) { - init(id, label, "", 0, "", WFM_LABEL_BEFORE); -} - -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length) { - init(id, label, defaultValue, length, "", WFM_LABEL_BEFORE); -} - -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom) { - init(id, label, defaultValue, length, custom, WFM_LABEL_BEFORE); -} - -WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { - init(id, label, defaultValue, length, custom, labelPlacement); -} - -void WiFiManagerParameter::init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement) { - _id = id; - _label = label; - _labelPlacement = labelPlacement; - _customHTML = custom; - setValue(defaultValue,length); -} - -WiFiManagerParameter::~WiFiManagerParameter() { - if (_value != NULL) { - delete[] _value; - } - _length=0; // setting length 0, ideally the entire parameter should be removed, or added to wifimanager scope so it follows -} - -// WiFiManagerParameter& WiFiManagerParameter::operator=(const WiFiManagerParameter& rhs){ -// Serial.println("copy assignment op called"); -// (*this->_value) = (*rhs._value); -// return *this; -// } - -// @note debug is not available in wmparameter class -void WiFiManagerParameter::setValue(const char *defaultValue, int length) { - if(!_id){ - // Serial.println("cannot set value of this parameter"); - return; - } - - // if(strlen(defaultValue) > length){ - // // Serial.println("defaultValue length mismatch"); - // // return false; //@todo bail - // } - - _length = length; - _value = new char[_length + 1]; - memset(_value, 0, _length + 1); // explicit null - - if (defaultValue != NULL) { - strncpy(_value, defaultValue, _length); - } -} -const char* WiFiManagerParameter::getValue() { - // Serial.println(printf("Address of _value is %p\n", (void *)_value)); - return _value; -} -const char* WiFiManagerParameter::getID() { - return _id; -} -const char* WiFiManagerParameter::getPlaceholder() { - return _label; -} -const char* WiFiManagerParameter::getLabel() { - return _label; -} -int WiFiManagerParameter::getValueLength() { - return _length; -} -int WiFiManagerParameter::getLabelPlacement() { - return _labelPlacement; -} -const char* WiFiManagerParameter::getCustomHTML() { - return _customHTML; -} - -/** - * [addParameter description] - * @access public - * @param {[type]} WiFiManagerParameter *p [description] - */ -bool WiFiManager::addParameter(WiFiManagerParameter *p) { - - // check param id is valid, unless null - if(p->getID()){ - for (size_t i = 0; i < strlen(p->getID()); i++){ - if(!(isAlphaNumeric(p->getID()[i])) && !(p->getID()[i]=='_')){ - DEBUG_WM(DEBUG_ERROR,"[ERROR] parameter IDs can only contain alpha numeric chars"); - return false; - } - } - } - - // init params if never malloc - if(_params == NULL){ - DEBUG_WM(DEBUG_DEV,"allocating params bytes:",_max_params * sizeof(WiFiManagerParameter*)); - _params = (WiFiManagerParameter**)malloc(_max_params * sizeof(WiFiManagerParameter*)); - } - - // resize the params array by increment of WIFI_MANAGER_MAX_PARAMS - if(_paramsCount == _max_params){ - _max_params += WIFI_MANAGER_MAX_PARAMS; - DEBUG_WM(DEBUG_DEV,F("Updated _max_params:"),_max_params); - DEBUG_WM(DEBUG_DEV,"re-allocating params bytes:",_max_params * sizeof(WiFiManagerParameter*)); - WiFiManagerParameter** new_params = (WiFiManagerParameter**)realloc(_params, _max_params * sizeof(WiFiManagerParameter*)); - // DEBUG_WM(WIFI_MANAGER_MAX_PARAMS); - // DEBUG_WM(_paramsCount); - // DEBUG_WM(_max_params); - if (new_params != NULL) { - _params = new_params; - } else { - DEBUG_WM(DEBUG_ERROR,"[ERROR] failed to realloc params, size not increased!"); - return false; - } - } - - _params[_paramsCount] = p; - _paramsCount++; - - DEBUG_WM(DEBUG_VERBOSE,"Added Parameter:",p->getID()); - return true; -} - -/** - * [getParameters description] - * @access public - */ -WiFiManagerParameter** WiFiManager::getParameters() { - return _params; -} - -/** - * [getParametersCount description] - * @access public - */ -int WiFiManager::getParametersCount() { - return _paramsCount; -} - -/** - * -------------------------------------------------------------------------------- - * WiFiManager - * -------------------------------------------------------------------------------- -**/ - -// constructors -WiFiManager::WiFiManager(Stream& consolePort):_debugPort(consolePort){ - WiFiManagerInit(); -} - -WiFiManager::WiFiManager() { - WiFiManagerInit(); -} - -void WiFiManager::WiFiManagerInit(){ - setMenu(_menuIdsDefault); - if(_debug && _debugLevel > DEBUG_DEV) debugPlatformInfo(); - _max_params = WIFI_MANAGER_MAX_PARAMS; -} - -// destructor -WiFiManager::~WiFiManager() { - _end(); - // parameters - // @todo below belongs to wifimanagerparameter - if (_params != NULL){ - DEBUG_WM(DEBUG_DEV,F("freeing allocated params!")); - free(_params); - _params = NULL; - } - - // @todo remove event - // WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); - #ifdef ESP32 - WiFi.removeEvent(wm_event_id); - #endif - - DEBUG_WM(DEBUG_DEV,F("unloading")); -} - -void WiFiManager::_begin(){ - if(_hasBegun) return; - _hasBegun = true; - // _usermode = WiFi.getMode(); - - #ifndef ESP32 - WiFi.persistent(false); // disable persistent so scannetworks and mode switching do not cause overwrites - #endif -} - -void WiFiManager::_end(){ - _hasBegun = false; - if(_userpersistent) WiFi.persistent(true); // reenable persistent, there is no getter we rely on _userpersistent - // if(_usermode != WIFI_OFF) WiFi.mode(_usermode); -} - -// AUTOCONNECT - -boolean WiFiManager::autoConnect() { - String ssid = getDefaultAPName(); - return autoConnect(ssid.c_str(), NULL); -} - -/** - * [autoConnect description] - * @access public - * @param {[type]} char const *apName [description] - * @param {[type]} char const *apPassword [description] - * @return {[type]} [description] - */ -boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { - DEBUG_WM(F("AutoConnect")); - if(getWiFiIsSaved()){ - - _begin(); - - // attempt to connect using saved settings, on fail fallback to AP config portal - if(!WiFi.enableSTA(true)){ - // handle failure mode Brownout detector etc. - DEBUG_WM(DEBUG_ERROR,"[FATAL] Unable to enable wifi!"); - return false; - } - - WiFiSetCountry(); - - #ifdef ESP32 - if(esp32persistent) WiFi.persistent(false); // disable persistent for esp32 after esp_wifi_start or else saves wont work - #endif - - _usermode = WIFI_STA; // When using autoconnect , assume the user wants sta mode on permanently. - - // no getter for autoreconnectpolicy before this - // https://github.com/esp8266/Arduino/pull/4359 - // so we must force it on else, if not connectimeout then waitforconnectionresult gets stuck endless loop - WiFi_autoReconnect(); - - // set hostname before stating - if((String)_hostname != ""){ - setupHostname(true); - } - - // if already connected, or try stored connect - // @note @todo ESP32 has no autoconnect, so connectwifi will always be called unless user called begin etc before - // @todo check if correct ssid == saved ssid when already connected - bool connected = false; - if (WiFi.status() == WL_CONNECTED){ - connected = true; - DEBUG_WM(F("AutoConnect: ESP Already Connected")); - setSTAConfig(); - // @todo not sure if this check makes sense, causes dup setSTAConfig in connectwifi, - // and we have no idea WHAT we are connected to - } - - if(connected || connectWifi("", "") == WL_CONNECTED){ - //connected - DEBUG_WM(F("AutoConnect: SUCCESS")); - DEBUG_WM(F("STA IP Address:"),WiFi.localIP()); - _lastconxresult = WL_CONNECTED; - - if((String)_hostname != ""){ - #ifdef ESP8266 - DEBUG_WM(DEBUG_DEV,"hostname: STA: ",WiFi.hostname()); - #elif defined(ESP32) - DEBUG_WM(DEBUG_DEV,"hostname: STA: ",WiFi.getHostname()); - #endif - } - - return true; // connected success - } - - // possibly skip the config portal - if (!_enableConfigPortal) { - return false; // not connected and not cp - } - - DEBUG_WM(F("AutoConnect: FAILED")); - } - else DEBUG_WM(F("No Credentials are Saved, skipping connect")); - - // not connected start configportal - bool res = startConfigPortal(apName, apPassword); - return res; -} - -bool WiFiManager::setupHostname(bool restart){ - if((String)_hostname == "") { - DEBUG_WM(DEBUG_DEV,"No Hostname to set"); - return false; - } else DEBUG_WM(DEBUG_DEV,"setupHostname: ",_hostname); - bool res = true; - #ifdef ESP8266 - DEBUG_WM(DEBUG_VERBOSE,"Setting WiFi hostname"); - res = WiFi.hostname(_hostname); - // #ifdef ESP8266MDNS_H - #ifdef WM_MDNS - DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname, tcp 80"); - if(MDNS.begin(_hostname)){ - MDNS.addService("http", "tcp", 80); - } - #endif - #elif defined(ESP32) - // @note hostname must be set after STA_START - delay(200); // do not remove, give time for STA_START - res = WiFi.setHostname(_hostname); - // #ifdef ESP32MDNS_H - #ifdef WM_MDNS - DEBUG_WM(DEBUG_VERBOSE,"Setting MDNS hostname, tcp 80"); - if(MDNS.begin(_hostname)){ - MDNS.addService("http", "tcp", 80); - } - #endif - #endif - - if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: set failed!")); - - // in sta mode restart , not sure about softap - if(restart && (WiFi.status() == WL_CONNECTED)){ - DEBUG_WM(DEBUG_VERBOSE,F("reconnecting to set new hostname")); - // WiFi.reconnect(); // This does not reset dhcp - WiFi_Disconnect(); - delay(200); // do not remove, need a delay for disconnect to change status() - } - - return res; -} - -// CONFIG PORTAL -bool WiFiManager::startAP(){ - bool ret = true; - DEBUG_WM(F("StartAP with SSID: "),_apName); - - #ifdef ESP8266 - // @bug workaround for bug #4372 https://github.com/esp8266/Arduino/issues/4372 - if(!WiFi.enableAP(true)) { - DEBUG_WM(DEBUG_ERROR,"[ERROR] enableAP failed!"); - return false; - } - delay(500); // workaround delay - #endif - - // setup optional soft AP static ip config - if (_ap_static_ip) { - DEBUG_WM(F("Custom AP IP/GW/Subnet:")); - if(!WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn)){ - DEBUG_WM(DEBUG_ERROR,"[ERROR] softAPConfig failed!"); - } - } - - //@todo add callback here if needed to modify ap but cannot use setAPStaticIPConfig - //@todo rework wifi channelsync as it will work unpredictably when not connected in sta - - int32_t channel = 0; - if(_channelSync) channel = WiFi.channel(); - else channel = _apChannel; - - if(channel>0){ - DEBUG_WM(DEBUG_VERBOSE,"Starting AP on channel:",channel); - } - - // start soft AP with password or anonymous - // default channel is 1 here and in esplib, @todo just change to default remove conditionals - if (_apPassword != "") { - if(channel>0){ - ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),channel,_apHidden); - } - else{ - ret = WiFi.softAP(_apName.c_str(), _apPassword.c_str(),1,_apHidden);//password option - } - } else { - DEBUG_WM(DEBUG_VERBOSE,F("AP has anonymous access!")); - if(channel>0){ - ret = WiFi.softAP(_apName.c_str(),"",channel,_apHidden); - } - else{ - ret = WiFi.softAP(_apName.c_str(),"",1,_apHidden); - } - } - - if(_debugLevel >= DEBUG_DEV) debugSoftAPConfig(); - - if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] There was a problem starting the AP"); - // @todo add softAP retry here - - delay(500); // slight delay to make sure we get an AP IP - DEBUG_WM(F("AP IP address:"),WiFi.softAPIP()); - - // set ap hostname - #ifdef ESP32 - if(ret && (String)_hostname != ""){ - DEBUG_WM(DEBUG_VERBOSE,"setting softAP Hostname:",_hostname); - bool res = WiFi.softAPsetHostname(_hostname); - if(!res)DEBUG_WM(DEBUG_ERROR,F("[ERROR] hostname: AP set failed!")); - DEBUG_WM(DEBUG_DEV,F("hostname: AP: "),WiFi.softAPgetHostname()); - } - #endif - - return ret; -} - -/** - * [startWebPortal description] - * @access public - * @return {[type]} [description] - */ -void WiFiManager::startWebPortal() { - if(configPortalActive || webPortalActive) return; - setupConfigPortal(); - webPortalActive = true; -} - -/** - * [stopWebPortal description] - * @access public - * @return {[type]} [description] - */ -void WiFiManager::stopWebPortal() { - if(!configPortalActive && !webPortalActive) return; - DEBUG_WM(DEBUG_VERBOSE,F("Stopping Web Portal")); - webPortalActive = false; - shutdownConfigPortal(); -} - -boolean WiFiManager::configPortalHasTimeout(){ - - if(_configPortalTimeout == 0 || (_apClientCheck && (WiFi_softap_num_stations() > 0))){ - if(millis() - timer > 30000){ - timer = millis(); - DEBUG_WM(DEBUG_VERBOSE,"NUM CLIENTS: " + (String)WiFi_softap_num_stations()); - } - _configPortalStart = millis(); // kludge, bump configportal start time to skew timeouts - return false; - } - // handle timeout - if(_webClientCheck && (_webPortalAccessed>_configPortalStart)>0) _configPortalStart = _webPortalAccessed; - - if(millis() > _configPortalStart + _configPortalTimeout){ - DEBUG_WM(F("config portal has timed out")); - return true; - } else if(_debugLevel > 0) { - // log timeout - if(_debug){ - uint16_t logintvl = 30000; // how often to emit timeing out counter logging - if((millis() - timer) > logintvl){ - timer = millis(); - DEBUG_WM(DEBUG_VERBOSE,F("Portal Timeout In"),(String)((_configPortalStart + _configPortalTimeout-millis())/1000) + (String)F(" seconds")); - } - } - } - - return false; -} - -void WiFiManager::setupConfigPortal() { - - DEBUG_WM(F("Starting Web Portal")); - - // setup dns and web servers - dnsServer.reset(new DNSServer()); - server.reset(new WM_WebServer(_httpPort)); - - if(_httpPort != 80) DEBUG_WM(DEBUG_VERBOSE,"http server started with custom port: ",_httpPort); // @todo not showing ip - - /* Setup the DNS server redirecting all the domains to the apIP */ - dnsServer->setErrorReplyCode(DNSReplyCode::NoError); - // DEBUG_WM("dns server started port: ",DNS_PORT); - DEBUG_WM(DEBUG_DEV,"dns server started with ip: ",WiFi.softAPIP()); // @todo not showing ip - dnsServer->start(DNS_PORT, F("*"), WiFi.softAPIP()); - - // @todo new callback, webserver started, callback cannot override handlers, but can grab them first - - if ( _webservercallback != NULL) { - _webservercallback(); - } - - /* Setup httpd callbacks, web pages: root, wifi config pages, SO captive portal detectors and not found. */ - server->on(String(FPSTR(R_root)).c_str(), std::bind(&WiFiManager::handleRoot, this)); - server->on(String(FPSTR(R_wifi)).c_str(), std::bind(&WiFiManager::handleWifi, this, true)); - server->on(String(FPSTR(R_wifinoscan)).c_str(), std::bind(&WiFiManager::handleWifi, this, false)); - server->on(String(FPSTR(R_wifisave)).c_str(), std::bind(&WiFiManager::handleWifiSave, this)); - server->on(String(FPSTR(R_info)).c_str(), std::bind(&WiFiManager::handleInfo, this)); - server->on(String(FPSTR(R_param)).c_str(), std::bind(&WiFiManager::handleParam, this)); - server->on(String(FPSTR(R_paramsave)).c_str(), std::bind(&WiFiManager::handleParamSave, this)); - server->on(String(FPSTR(R_restart)).c_str(), std::bind(&WiFiManager::handleReset, this)); - server->on(String(FPSTR(R_exit)).c_str(), std::bind(&WiFiManager::handleExit, this)); - server->on(String(FPSTR(R_close)).c_str(), std::bind(&WiFiManager::handleClose, this)); - server->on(String(FPSTR(R_erase)).c_str(), std::bind(&WiFiManager::handleErase, this, false)); - server->on(String(FPSTR(R_status)).c_str(), std::bind(&WiFiManager::handleWiFiStatus, this)); - server->onNotFound (std::bind(&WiFiManager::handleNotFound, this)); - - server->begin(); // Web server start - DEBUG_WM(DEBUG_VERBOSE,F("HTTP server started")); - - if(_preloadwifiscan) WiFi_scanNetworks(true,true); // preload wifiscan , async -} - -boolean WiFiManager::startConfigPortal() { - String ssid = getDefaultAPName(); - return startConfigPortal(ssid.c_str(), NULL); -} - -/** - * [startConfigPortal description] - * @access public - * @param {[type]} char const *apName [description] - * @param {[type]} char const *apPassword [description] - * @return {[type]} [description] - */ -boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { - _begin(); - - //setup AP - _apName = apName; // @todo check valid apname ? - _apPassword = apPassword; - - DEBUG_WM(DEBUG_VERBOSE,F("Starting Config Portal")); - - if(_apName == "") _apName = getDefaultAPName(); - - if(!validApPassword()) return false; - - // HANDLE issues with STA connections, shutdown sta if not connected, or else this will hang channel scanning and softap will not respond - // @todo sometimes still cannot connect to AP for no known reason, no events in log either - if(_disableSTA || (!WiFi.isConnected() && _disableSTAConn)){ - // this fixes most ap problems, however, simply doing mode(WIFI_AP) does not work if sta connection is hanging, must `wifi_station_disconnect` - WiFi_Disconnect(); - WiFi_enableSTA(false); - DEBUG_WM(DEBUG_VERBOSE,F("Disabling STA")); - } - else { - // @todo even if sta is connected, it is possible that softap connections will fail, IOS says "invalid password", windows says "cannot connect to this network" researching - WiFi_enableSTA(true); - } - - // init configportal globals to known states - configPortalActive = true; - bool result = connect = abort = false; // loop flags, connect true success, abort true break - uint8_t state; - - _configPortalStart = millis(); - - // start access point - DEBUG_WM(DEBUG_VERBOSE,F("Enabling AP")); - startAP(); - WiFiSetCountry(); - - // do AP callback if set - if ( _apcallback != NULL) { - _apcallback(this); - } - - // init configportal - DEBUG_WM(DEBUG_DEV,F("setupConfigPortal")); - setupConfigPortal(); - - if(!_configPortalIsBlocking){ - DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, non blocking/processing")); - return result; - } - - DEBUG_WM(DEBUG_VERBOSE,F("Config Portal Running, blocking, waiting for clients...")); - // blocking loop waiting for config - while(1){ - - // if timed out or abort, break - if(configPortalHasTimeout() || abort){ - DEBUG_WM(DEBUG_DEV,F("configportal abort")); - shutdownConfigPortal(); - result = abort ? portalAbortResult : portalTimeoutResult; // false, false - break; - } - - state = processConfigPortal(); - - // status change, break - if(state != WL_IDLE_STATUS){ - result = (state == WL_CONNECTED); // true if connected - break; - } - - yield(); // watchdog - } - - DEBUG_WM(DEBUG_NOTIFY,F("config portal exiting")); - return result; -} - -/** - * [process description] - * @access public - * @return {[type]} [description] - */ -boolean WiFiManager::process(){ - // process mdns, esp32 not required - #if defined(WM_MDNS) && defined(ESP8266) - MDNS.update(); - #endif - - if(webPortalActive || (configPortalActive && !_configPortalIsBlocking)){ - uint8_t state = processConfigPortal(); - return state == WL_CONNECTED; - } - return false; -} - -//using esp enums returns for now, should be fine -uint8_t WiFiManager::processConfigPortal(){ - //DNS handler - dnsServer->processNextRequest(); - //HTTP handler - server->handleClient(); - - // Waiting for save... - if(connect) { - connect = false; - DEBUG_WM(DEBUG_VERBOSE,F("processing save")); - if(_enableCaptivePortal) delay(_cpclosedelay); // keeps the captiveportal from closing to fast. - - // skip wifi if no ssid - if(_ssid == ""){ - DEBUG_WM(DEBUG_VERBOSE,F("No ssid, skipping wifi save")); - } - else{ - // attempt sta connection to submitted _ssid, _pass - if (connectWifi(_ssid, _pass) == WL_CONNECTED) { - - DEBUG_WM(F("Connect to new AP [SUCCESS]")); - DEBUG_WM(F("Got IP Address:")); - DEBUG_WM(WiFi.localIP()); - - if ( _savewificallback != NULL) { - _savewificallback(); - } - shutdownConfigPortal(); - return WL_CONNECTED; // CONNECT SUCCESS - } - DEBUG_WM(DEBUG_ERROR,F("[ERROR] Connect to new AP Failed")); - } - - if (_shouldBreakAfterConfig) { - - // do save callback - // @todo this is more of an exiting callback than a save, clarify when this should actually occur - // confirm or verify data was saved to make this more accurate callback - if ( _savewificallback != NULL) { - DEBUG_WM(DEBUG_VERBOSE,F("WiFi/Param save callback")); - _savewificallback(); - } - shutdownConfigPortal(); - return WL_CONNECT_FAILED; // CONNECT FAIL - } - else{ - // clear save strings - _ssid = ""; - _pass = ""; - // if connect fails, turn sta off to stabilize AP - WiFi_Disconnect(); - WiFi_enableSTA(false); - DEBUG_WM(DEBUG_VERBOSE,F("Disabling STA")); - } - } - - return WL_IDLE_STATUS; -} - -/** - * [shutdownConfigPortal description] - * @access public - * @return bool success (softapdisconnect) - */ -bool WiFiManager::shutdownConfigPortal(){ - if(webPortalActive) return false; - - //DNS handler - dnsServer->processNextRequest(); - //HTTP handler - server->handleClient(); - - // @todo what is the proper way to shutdown and free the server up - server->stop(); - server.reset(); - dnsServer->stop(); // free heap ? - dnsServer.reset(); - - WiFi.scanDelete(); // free wifi scan results - - if(!configPortalActive) return false; - - // turn off AP - // @todo bug workaround - // https://github.com/esp8266/Arduino/issues/3793 - // [APdisconnect] set_config failed! *WM: disconnect configportal - softAPdisconnect failed - // still no way to reproduce reliably - DEBUG_WM(DEBUG_VERBOSE,F("disconnect configportal")); - bool ret = false; - ret = WiFi.softAPdisconnect(false); - if(!ret)DEBUG_WM(DEBUG_ERROR,F("[ERROR] disconnect configportal - softAPdisconnect FAILED")); - delay(1000); - DEBUG_WM(DEBUG_VERBOSE,"restoring usermode",getModeString(_usermode)); - WiFi_Mode(_usermode); // restore users wifi mode, BUG https://github.com/esp8266/Arduino/issues/4372 - if(WiFi.status()==WL_IDLE_STATUS){ - WiFi.reconnect(); // restart wifi since we disconnected it in startconfigportal - DEBUG_WM(DEBUG_VERBOSE,"WiFi Reconnect, was idle"); - } - DEBUG_WM(DEBUG_VERBOSE,"wifi status:",getWLStatusString(WiFi.status())); - DEBUG_WM(DEBUG_VERBOSE,"wifi mode:",getModeString(WiFi.getMode())); - configPortalActive = false; - _end(); - return ret; -} - -// @todo refactor this up into seperate functions -// one for connecting to flash , one for new client -// clean up, flow is convoluted, and causes bugs -uint8_t WiFiManager::connectWifi(String ssid, String pass) { - DEBUG_WM(DEBUG_VERBOSE,F("Connecting as wifi client...")); - - uint8_t connRes = (uint8_t)WL_NO_SSID_AVAIL; - - setSTAConfig(); - //@todo catch failures in set_config - - // make sure sta is on before `begin` so it does not call enablesta->mode while persistent is ON ( which would save WM AP state to eeprom !) - - if(_cleanConnect) WiFi_Disconnect(); // disconnect before begin, in case anything is hung, this causes a 2 seconds delay for connect - // @todo find out what status is when this is needed, can we detect it and handle it, say in between states or idle_status - - // if ssid argument provided connect to that - if (ssid != "") { - wifiConnectNew(ssid,pass); - if(_saveTimeout > 0){ - connRes = waitForConnectResult(_saveTimeout); // use default save timeout for saves to prevent bugs in esp->waitforconnectresult loop - } - else { - connRes = waitForConnectResult(0); - } - } - else { - // connect using saved ssid if there is one - if (WiFi_hasAutoConnect()) { - wifiConnectDefault(); - connRes = waitForConnectResult(); - } - else { - DEBUG_WM(F("No wifi save required, skipping")); - } - } - - DEBUG_WM(DEBUG_VERBOSE,F("Connection result:"),getWLStatusString(connRes)); - -// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 -#ifdef NO_EXTRA_4K_HEAP - // do WPS, if WPS options enabled and not connected and no password was supplied - // @todo this seems like wrong place for this, is it a fallback or option? - if (_tryWPS && connRes != WL_CONNECTED && pass == "") { - startWPS(); - // should be connected at the end of WPS - connRes = waitForConnectResult(); - } -#endif - - if(connRes != WL_SCAN_COMPLETED){ - updateConxResult(connRes); - } - - return connRes; -} - -/** - * connect to a new wifi ap - * @since $dev - * @param String ssid - * @param String pass - * @return bool success - */ -bool WiFiManager::wifiConnectNew(String ssid, String pass){ - bool ret = false; - DEBUG_WM(F("CONNECTED:"),WiFi.status() == WL_CONNECTED); - DEBUG_WM(F("Connecting to NEW AP:"),ssid); - DEBUG_WM(DEBUG_DEV,F("Using Password:"),pass); - WiFi_enableSTA(true,storeSTAmode); // storeSTAmode will also toggle STA on in default opmode (persistent) if true (default) - WiFi.persistent(true); - ret = WiFi.begin(ssid.c_str(), pass.c_str()); - WiFi.persistent(false); - if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed"); - return ret; -} - -/** - * connect to stored wifi - * @since dev - * @return bool success - */ -bool WiFiManager::wifiConnectDefault(){ - bool ret = false; - DEBUG_WM(F("Connecting to SAVED AP:"),WiFi_SSID(true)); - DEBUG_WM(DEBUG_DEV,F("Using Password:"),WiFi_psk(true)); - ret = WiFi_enableSTA(true,storeSTAmode); - if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi enableSta failed"); - ret = WiFi.begin(); - if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi begin failed"); - return ret; -} - - -/** - * set sta config if set - * @since $dev - * @return bool success - */ -bool WiFiManager::setSTAConfig(){ - DEBUG_WM(DEBUG_DEV,F("STA static IP:"),_sta_static_ip); - bool ret = true; - if (_sta_static_ip) { - DEBUG_WM(DEBUG_VERBOSE,F("Custom static IP/GW/Subnet/DNS")); - if(_sta_static_dns) { - DEBUG_WM(DEBUG_VERBOSE,F("Custom static DNS")); - ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn, _sta_static_dns); - } - else { - DEBUG_WM(DEBUG_VERBOSE,F("Custom STA IP/GW/Subnet")); - ret = WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn); - } - - if(!ret) DEBUG_WM(DEBUG_ERROR,"[ERROR] wifi config failed"); - else DEBUG_WM(F("STA IP set:"),WiFi.localIP()); - } else { - DEBUG_WM(DEBUG_VERBOSE,F("setSTAConfig static ip not set, skipping")); - } - return ret; -} - -// @todo change to getLastFailureReason and do not touch conxresult -void WiFiManager::updateConxResult(uint8_t status){ - // hack in wrong password detection - _lastconxresult = status; - #ifdef ESP8266 - if(_lastconxresult == WL_CONNECT_FAILED){ - if(wifi_station_get_connect_status() == STATION_WRONG_PASSWORD){ - _lastconxresult = WL_STATION_WRONG_PASSWORD; - } - } - #elif defined(ESP32) - // if(_lastconxresult == WL_CONNECT_FAILED){ - if(_lastconxresult == WL_CONNECT_FAILED || _lastconxresult == WL_DISCONNECTED){ - DEBUG_WM(DEBUG_DEV,"lastconxresulttmp:",getWLStatusString(_lastconxresulttmp)); - if(_lastconxresulttmp != WL_IDLE_STATUS){ - _lastconxresult = _lastconxresulttmp; - // _lastconxresulttmp = WL_IDLE_STATUS; - } - } - #endif - DEBUG_WM(DEBUG_DEV,"lastconxresult:",getWLStatusString(_lastconxresult)); -} - - -uint8_t WiFiManager::waitForConnectResult() { - if(_connectTimeout > 0) DEBUG_WM(DEBUG_VERBOSE,_connectTimeout,F("ms connectTimeout set")); - return waitForConnectResult(_connectTimeout); -} - -/** - * waitForConnectResult - * @param uint16_t timeout in seconds - * @return uint8_t WL Status - */ -uint8_t WiFiManager::waitForConnectResult(uint16_t timeout) { - if (timeout == 0){ - DEBUG_WM(F("connectTimeout not set, ESP waitForConnectResult...")); - return WiFi.waitForConnectResult(); - } - - unsigned long timeoutmillis = millis() + timeout; - DEBUG_WM(DEBUG_VERBOSE,timeout,F("ms timeout, waiting for connect...")); - uint8_t status = WiFi.status(); - - while(millis() < timeoutmillis) { - status = WiFi.status(); - // @todo detect additional states, connect happens, then dhcp then get ip, there is some delay here, make sure not to timeout if waiting on IP - if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) { - return status; - } - DEBUG_WM (DEBUG_VERBOSE,F(".")); - delay(100); - } - return status; -} - -// WPS enabled? https://github.com/esp8266/Arduino/pull/4889 -#ifdef NO_EXTRA_4K_HEAP -void WiFiManager::startWPS() { - DEBUG_WM(F("START WPS")); - #ifdef ESP8266 - WiFi.beginWPSConfig(); - #else - // @todo - #endif - DEBUG_WM(F("END WPS")); -} -#endif - -String WiFiManager::getHTTPHead(String title){ - String page; - page += FPSTR(HTTP_HEAD_START); - page.replace(FPSTR(T_v), title); - page += FPSTR(HTTP_SCRIPT); - page += FPSTR(HTTP_STYLE); - page += _customHeadElement; - - if(_bodyClass != ""){ - String p = FPSTR(HTTP_HEAD_END); - p.replace(FPSTR(T_c), _bodyClass); // add class str - page += p; - } - else { - page += FPSTR(HTTP_HEAD_END); - } - - return page; -} - -/** - * HTTPD handler for page requests - */ -void WiFiManager::handleRequest() { - _webPortalAccessed = millis(); -} - -/** - * HTTPD CALLBACK root or redirect to captive portal - */ -void WiFiManager::handleRoot() { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Root")); - if (captivePortal()) return; // If captive portal redirect instead of displaying the page - handleRequest(); - String page = getHTTPHead(FPSTR(S_options)); // @token options @todo replace options with title - String str = FPSTR(HTTP_ROOT_MAIN); - str.replace(FPSTR(T_v),configPortalActive ? _apName : WiFi.localIP().toString()); // use ip if ap is not active for heading - page += str; - page += FPSTR(HTTP_PORTAL_OPTIONS); - page += getMenuOut(); - reportStatus(page); - page += FPSTR(HTTP_END); - - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); - // server->close(); // testing reliability fix for content length mismatches during mutiple flood hits WiFi_scanNetworks(); // preload wifiscan - if(_preloadwifiscan) WiFi_scanNetworks(_scancachetime,true); // preload wifiscan throttled, async - // @todo buggy, captive portals make a query on every page load, causing this to run every time in addition to the real page load - // I dont understand why, when you are already in the captive portal, I guess they want to know that its still up and not done or gone - // if we can detect these and ignore them that would be great, since they come from the captive portal redirect maybe there is a refferer -} - -/** - * HTTPD CALLBACK Wifi config page handler - */ -void WiFiManager::handleWifi(boolean scan) { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Wifi")); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titlewifi)); // @token titlewifi - if (scan) { - // DEBUG_WM(DEBUG_DEV,"refresh flag:",server->hasArg(F("refresh"))); - WiFi_scanNetworks(server->hasArg(F("refresh")),false); //wifiscan, force if arg refresh - page += getScanItemOut(); - } - String pitem = ""; - - pitem = FPSTR(HTTP_FORM_START); - pitem.replace(FPSTR(T_v), F("wifisave")); // set form action - page += pitem; - - pitem = FPSTR(HTTP_FORM_WIFI); - pitem.replace(FPSTR(T_v), WiFi_SSID()); - - if(_showPassword){ - pitem.replace(FPSTR(T_p), WiFi_psk()); - } - else { - pitem.replace(FPSTR(T_p),FPSTR(S_passph)); - } - page += pitem; - - page += getStaticOut(); - page += FPSTR(HTTP_FORM_WIFI_END); - if(_paramsInWifi && _paramsCount>0){ - page += FPSTR(HTTP_FORM_PARAM_HEAD); - page += getParamOut(); - } - page += FPSTR(HTTP_FORM_END); - page += FPSTR(HTTP_SCAN_LINK); - if(_showBack) page += FPSTR(HTTP_BACKBTN); - reportStatus(page); - page += FPSTR(HTTP_END); - - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); - // server->close(); // testing reliability fix for content length mismatches during mutiple flood hits - - DEBUG_WM(DEBUG_DEV,F("Sent config page")); -} - -/** - * HTTPD CALLBACK Wifi param page handler - */ -void WiFiManager::handleParam(){ - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Param")); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titleparam)); // @token titlewifi - - String pitem = ""; - - pitem = FPSTR(HTTP_FORM_START); - pitem.replace(FPSTR(T_v), F("paramsave")); - page += pitem; - - page += getParamOut(); - page += FPSTR(HTTP_FORM_END); - if(_showBack) page += FPSTR(HTTP_BACKBTN); - reportStatus(page); - page += FPSTR(HTTP_END); - - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); - - DEBUG_WM(DEBUG_DEV,F("Sent param page")); -} - - -String WiFiManager::getMenuOut(){ - String page; - - for(auto menuId :_menuIds ){ - if(((String)menuId == "param") && (_paramsCount == 0)) continue; // no params set, omit params from menu, @todo this may be undesired by someone - page += HTTP_PORTAL_MENU[menuId]; - } - - return page; -} - -// // is it possible in softap mode to detect aps without scanning -// bool WiFiManager::WiFi_scanNetworksForAP(bool force){ -// WiFi_scanNetworks(force); -// } - -void WiFiManager::WiFi_scanComplete(int networksFound){ - _lastscan = millis(); - _numNetworks = networksFound; - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC completed"), "in "+(String)(_lastscan - _startscan)+" ms"); - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC found:"),_numNetworks); -} - -bool WiFiManager::WiFi_scanNetworks(){ - return WiFi_scanNetworks(false,false); -} - -bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime,bool async){ - return WiFi_scanNetworks(millis()-_lastscan > cachetime,async); -} -bool WiFiManager::WiFi_scanNetworks(unsigned int cachetime){ - return WiFi_scanNetworks(millis()-_lastscan > cachetime,false); -} -bool WiFiManager::WiFi_scanNetworks(bool force,bool async){ - // DEBUG_WM(DEBUG_DEV,"scanNetworks async:",async == true); - // DEBUG_WM(DEBUG_DEV,_numNetworks,(millis()-_lastscan )); - // DEBUG_WM(DEBUG_DEV,"scanNetworks force:",force == true); - if(force || _numNetworks == 0 || (millis()-_lastscan > 60000)){ - int8_t res; - _startscan = millis(); - if(async && _asyncScan){ - #ifdef ESP8266 - #ifndef WM_NOASYNC // no async available < 2.4.0 - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); - using namespace std::placeholders; // for `_1` - WiFi.scanNetworksAsync(std::bind(&WiFiManager::WiFi_scanComplete,this,_1)); - #else - res = WiFi.scanNetworks(); - #endif - #else - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan ASYNC started")); - res = WiFi.scanNetworks(true); - #endif - return false; - } - else{ - res = WiFi.scanNetworks(); - } - if(res == WIFI_SCAN_FAILED) DEBUG_WM(DEBUG_ERROR,"[ERROR] scan failed"); - else if(res == WIFI_SCAN_RUNNING){ - DEBUG_WM(DEBUG_ERROR,"[ERROR] scan waiting"); - while(WiFi.scanComplete() == WIFI_SCAN_RUNNING){ - DEBUG_WM(DEBUG_ERROR,"."); - delay(100); - } - _numNetworks = WiFi.scanComplete(); - } - else if(res >=0 ) _numNetworks = res; - _lastscan = millis(); - DEBUG_WM(DEBUG_VERBOSE,F("WiFi Scan completed"), "in "+(String)(_lastscan - _startscan)+" ms"); - return true; - } else DEBUG_WM(DEBUG_VERBOSE,"Scan is cached",(String)(millis()-_lastscan )+" ms ago"); - return false; -} - -String WiFiManager::WiFiManager::getScanItemOut(){ - String page; - - if(!_numNetworks) WiFi_scanNetworks(); // scan in case this gets called before any scans - - int n = _numNetworks; - if (n == 0) { - DEBUG_WM(F("No networks found")); - page += FPSTR(S_nonetworks); // @token nonetworks - } - else { - DEBUG_WM(n,F("networks found")); - //sort networks - int indices[n]; - for (int i = 0; i < n; i++) { - indices[i] = i; - } - - // RSSI SORT - for (int i = 0; i < n; i++) { - for (int j = i + 1; j < n; j++) { - if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) { - std::swap(indices[i], indices[j]); - } - } - } - - /* test std:sort - std::sort(indices, indices + n, [](const int & a, const int & b) -> bool - { - return WiFi.RSSI(a) > WiFi.RSSI(b); - }); - */ - - // remove duplicates ( must be RSSI sorted ) - if (_removeDuplicateAPs) { - String cssid; - for (int i = 0; i < n; i++) { - if (indices[i] == -1) continue; - cssid = WiFi.SSID(indices[i]); - for (int j = i + 1; j < n; j++) { - if (cssid == WiFi.SSID(indices[j])) { - DEBUG_WM(DEBUG_VERBOSE,F("DUP AP:"),WiFi.SSID(indices[j])); - indices[j] = -1; // set dup aps to index -1 - } - } - } - } - - // token precheck, to speed up replacements on large ap lists - String HTTP_ITEM_STR = FPSTR(HTTP_ITEM); - - // toggle icons with percentage - HTTP_ITEM_STR.replace("{qp}", FPSTR(HTTP_ITEM_QP)); - HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "" : "h"); - HTTP_ITEM_STR.replace("{qi}", FPSTR(HTTP_ITEM_QI)); - HTTP_ITEM_STR.replace("{h}",_scanDispOptions ? "h" : ""); - - // set token precheck flags - bool tok_r = HTTP_ITEM_STR.indexOf(FPSTR(T_r)) > 0; - bool tok_R = HTTP_ITEM_STR.indexOf(FPSTR(T_R)) > 0; - bool tok_e = HTTP_ITEM_STR.indexOf(FPSTR(T_e)) > 0; - bool tok_q = HTTP_ITEM_STR.indexOf(FPSTR(T_q)) > 0; - bool tok_i = HTTP_ITEM_STR.indexOf(FPSTR(T_i)) > 0; - - //display networks in page - for (int i = 0; i < n; i++) { - if (indices[i] == -1) continue; // skip dups - - DEBUG_WM(DEBUG_VERBOSE,F("AP: "),(String)WiFi.RSSI(indices[i]) + " " + (String)WiFi.SSID(indices[i])); - - int rssiperc = getRSSIasQuality(WiFi.RSSI(indices[i])); - uint8_t enc_type = WiFi.encryptionType(indices[i]); - - if (_minimumQuality == -1 || _minimumQuality < rssiperc) { - String item = HTTP_ITEM_STR; - item.replace(FPSTR(T_v), htmlEntities(WiFi.SSID(indices[i]))); // ssid no encoding - if(tok_e) item.replace(FPSTR(T_e), encryptionTypeStr(enc_type)); - if(tok_r) item.replace(FPSTR(T_r), (String)rssiperc); // rssi percentage 0-100 - if(tok_R) item.replace(FPSTR(T_R), (String)WiFi.RSSI(indices[i])); // rssi db - if(tok_q) item.replace(FPSTR(T_q), (String)int(round(map(rssiperc,0,100,1,4)))); //quality icon 1-4 - if(tok_i){ - if (enc_type != WM_WIFIOPEN) { - item.replace(FPSTR(T_i), F("l")); - } else { - item.replace(FPSTR(T_i), ""); - } - } - //DEBUG_WM(item); - page += item; - delay(0); - } else { - DEBUG_WM(DEBUG_VERBOSE,F("Skipping , does not meet _minimumQuality")); - } - - } - page += FPSTR(HTTP_BR); - } - - return page; -} - -String WiFiManager::getIpForm(String id, String title, String value){ - String item = FPSTR(HTTP_FORM_LABEL); - item += FPSTR(HTTP_FORM_PARAM); - item.replace(FPSTR(T_i), id); - item.replace(FPSTR(T_n), id); - item.replace(FPSTR(T_p), FPSTR(T_t)); - // item.replace(FPSTR(T_p), default); - item.replace(FPSTR(T_t), title); - item.replace(FPSTR(T_l), F("15")); - item.replace(FPSTR(T_v), value); - item.replace(FPSTR(T_c), ""); - return item; -} - -String WiFiManager::getStaticOut(){ - String page; - if ((_staShowStaticFields || _sta_static_ip) && _staShowStaticFields>=0) { - DEBUG_WM(DEBUG_DEV,"_staShowStaticFields"); - page += FPSTR(HTTP_FORM_STATIC_HEAD); - // @todo how can we get these accurate settings from memory , wifi_get_ip_info does not seem to reveal if struct ip_info is static or not - page += getIpForm(FPSTR(S_ip),FPSTR(S_staticip),(_sta_static_ip ? _sta_static_ip.toString() : "")); // @token staticip - // WiFi.localIP().toString(); - page += getIpForm(FPSTR(S_gw),FPSTR(S_staticgw),(_sta_static_gw ? _sta_static_gw.toString() : "")); // @token staticgw - // WiFi.gatewayIP().toString(); - page += getIpForm(FPSTR(S_sn),FPSTR(S_subnet),(_sta_static_sn ? _sta_static_sn.toString() : "")); // @token subnet - // WiFi.subnetMask().toString(); - } - - if((_staShowDns || _sta_static_dns) && _staShowDns>=0){ - page += getIpForm(FPSTR(S_dns),FPSTR(S_staticdns),(_sta_static_dns ? _sta_static_dns.toString() : "")); // @token dns - } - - if(page!="") page += FPSTR(HTTP_BR); // @todo remove these, use css - - return page; -} - -String WiFiManager::getParamOut(){ - String page; - - if(_paramsCount > 0){ - - String HTTP_PARAM_temp = FPSTR(HTTP_FORM_LABEL); - HTTP_PARAM_temp += FPSTR(HTTP_FORM_PARAM); - bool tok_I = HTTP_PARAM_temp.indexOf(FPSTR(T_I)) > 0; - bool tok_i = HTTP_PARAM_temp.indexOf(FPSTR(T_i)) > 0; - bool tok_n = HTTP_PARAM_temp.indexOf(FPSTR(T_n)) > 0; - bool tok_p = HTTP_PARAM_temp.indexOf(FPSTR(T_p)) > 0; - bool tok_t = HTTP_PARAM_temp.indexOf(FPSTR(T_t)) > 0; - bool tok_l = HTTP_PARAM_temp.indexOf(FPSTR(T_l)) > 0; - bool tok_v = HTTP_PARAM_temp.indexOf(FPSTR(T_v)) > 0; - bool tok_c = HTTP_PARAM_temp.indexOf(FPSTR(T_c)) > 0; - - char valLength[5]; - // add the extra parameters to the form - for (int i = 0; i < _paramsCount; i++) { - if (_params[i] == NULL || _params[i]->_length == 0) { - DEBUG_WM(DEBUG_ERROR,"[ERROR] WiFiManagerParameter is out of scope"); - break; - } - - // label before or after, @todo this could be done via floats or CSS and eliminated - String pitem; - switch (_params[i]->getLabelPlacement()) { - case WFM_LABEL_BEFORE: - pitem = FPSTR(HTTP_FORM_LABEL); - pitem += FPSTR(HTTP_FORM_PARAM); - break; - case WFM_LABEL_AFTER: - pitem = FPSTR(HTTP_FORM_PARAM); - pitem += FPSTR(HTTP_FORM_LABEL); - break; - default: - // WFM_NO_LABEL - pitem = FPSTR(HTTP_FORM_PARAM); - break; - } - - // Input templating - // "
"; - // if no ID use customhtml for item, else generate from param string - if (_params[i]->getID() != NULL) { - if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); // T_I id number - if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); // T_i id name - if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); // T_n id name alias - if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); // T_p replace legacy placeholder token - if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getLabel()); // T_t title/label - snprintf(valLength, 5, "%d", _params[i]->getValueLength()); - if(tok_l)pitem.replace(FPSTR(T_l), valLength); // T_l value length - if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); // T_v value - if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // T_c meant for additional attributes, not html, but can stuff - } else { - pitem = _params[i]->getCustomHTML(); - } - - page += pitem; - } - } - - return page; -} - -void WiFiManager::handleWiFiStatus(){ - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi status ")); - handleRequest(); - String page; - // String page = "{\"result\":true,\"count\":1}"; - #ifdef WM_JSTEST - page = FPSTR(HTTP_JS); - #endif - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); -} - -/** - * HTTPD CALLBACK save form and redirect to WLAN config page again - */ -void WiFiManager::handleWifiSave() { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); - DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); - handleRequest(); - - // @todo use new callback for before paramsaves - if ( _presavecallback != NULL) { - _presavecallback(); - } - - //SAVE/connect here - _ssid = server->arg(F("s")).c_str(); - _pass = server->arg(F("p")).c_str(); - - if(_paramsInWifi) doParamSave(); - - if (server->arg(FPSTR(S_ip)) != "") { - //_sta_static_ip.fromString(server->arg(FPSTR(S_ip)); - String ip = server->arg(FPSTR(S_ip)); - optionalIPFromString(&_sta_static_ip, ip.c_str()); - DEBUG_WM(DEBUG_DEV,F("static ip:"),ip); - } - if (server->arg(FPSTR(S_gw)) != "") { - String gw = server->arg(FPSTR(S_gw)); - optionalIPFromString(&_sta_static_gw, gw.c_str()); - DEBUG_WM(DEBUG_DEV,F("static gateway:"),gw); - } - if (server->arg(FPSTR(S_sn)) != "") { - String sn = server->arg(FPSTR(S_sn)); - optionalIPFromString(&_sta_static_sn, sn.c_str()); - DEBUG_WM(DEBUG_DEV,F("static netmask:"),sn); - } - if (server->arg(FPSTR(S_dns)) != "") { - String dns = server->arg(FPSTR(S_dns)); - optionalIPFromString(&_sta_static_dns, dns.c_str()); - DEBUG_WM(DEBUG_DEV,F("static DNS:"),dns); - } - - String page; - - if(_ssid == ""){ - page = getHTTPHead(FPSTR(S_titlewifisettings)); // @token titleparamsaved - page += FPSTR(HTTP_PARAMSAVED); - } - else { - page = getHTTPHead(FPSTR(S_titlewifisaved)); // @token titlewifisaved - page += FPSTR(HTTP_SAVED); - } - page += FPSTR(HTTP_END); - - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->sendHeader(FPSTR(HTTP_HEAD_CORS), FPSTR(HTTP_HEAD_CORS_ALLOW_ALL)); - server->send(200, FPSTR(HTTP_HEAD_CT), page); - - DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); - - connect = true; //signal ready to connect/reset process in processConfigPortal -} - -void WiFiManager::handleParamSave() { - - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); - DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); - handleRequest(); - - doParamSave(); - - String page = getHTTPHead(FPSTR(S_titleparamsaved)); // @token titleparamsaved - page += FPSTR(HTTP_PARAMSAVED); - page += FPSTR(HTTP_END); - - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); - - DEBUG_WM(DEBUG_DEV,F("Sent param save page")); -} - -void WiFiManager::doParamSave(){ - // @todo use new callback for before paramsaves, is this really needed? - if ( _presavecallback != NULL) { - _presavecallback(); - } - - //parameters - if(_paramsCount > 0){ - DEBUG_WM(DEBUG_VERBOSE,F("Parameters")); - DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); - - for (int i = 0; i < _paramsCount; i++) { - if (_params[i] == NULL || _params[i]->_length == 0) { - DEBUG_WM(DEBUG_ERROR,"[ERROR] WiFiManagerParameter is out of scope"); - break; // @todo might not be needed anymore - } - //read parameter from server - String name = (String)FPSTR(S_parampre)+(String)i; - String value; - if(server->hasArg(name)) { - value = server->arg(name); - } else { - value = server->arg(_params[i]->getID()); - } - - //store it in params array - value.toCharArray(_params[i]->_value, _params[i]->_length+1); // length+1 null terminated - DEBUG_WM(DEBUG_VERBOSE,(String)_params[i]->getID() + ":",value); - } - DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); - } - - if ( _saveparamscallback != NULL) { - _saveparamscallback(); - } - -} - -/** - * HTTPD CALLBACK info page - */ -void WiFiManager::handleInfo() { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Info")); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo - reportStatus(page); - - uint16_t infos = 0; - - //@todo convert to enum or refactor to strings - //@todo wrap in build flag to remove all info code for memory saving - #ifdef ESP8266 - infos = 27; - String infoids[] = { - F("esphead"), - F("uptime"), - F("chipid"), - F("fchipid"), - F("idesize"), - F("flashsize"), - F("sdkver"), - F("corever"), - F("bootver"), - F("cpufreq"), - F("freeheap"), - F("memsketch"), - F("memsmeter"), - F("lastreset"), - F("wifihead"), - F("apip"), - F("apmac"), - F("apssid"), - F("apbssid"), - F("staip"), - F("stagw"), - F("stasub"), - F("dnss"), - F("host"), - F("stamac"), - F("conx"), - F("autoconx") - }; - - #elif defined(ESP32) - infos = 22; - String infoids[] = { - F("esphead"), - F("uptime"), - F("chipid"), - F("chiprev"), - F("idesize"), - F("sdkver"), - F("cpufreq"), - F("freeheap"), - F("lastreset"), - // F("temp"), - F("wifihead"), - F("apip"), - F("apmac"), - F("aphost"), - F("apssid"), - F("apbssid"), - F("staip"), - F("stagw"), - F("stasub"), - F("dnss"), - F("host"), - F("stamac"), - F("conx") - }; - #endif - - for(size_t i=0; i"); - if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); - if(_showBack) page += FPSTR(HTTP_BACKBTN); - page += FPSTR(HTTP_HELP); - page += FPSTR(HTTP_END); - - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); - - DEBUG_WM(DEBUG_DEV,F("Sent info page")); -} - -String WiFiManager::getInfoData(String id){ - - String p; - // @todo add WM versioning - if(id==F("esphead"))p = FPSTR(HTTP_INFO_esphead); - else if(id==F("wifihead"))p = FPSTR(HTTP_INFO_wifihead); - else if(id==F("uptime")){ - // subject to rollover! - p = FPSTR(HTTP_INFO_uptime); - p.replace(FPSTR(T_1),(String)(millis() / 1000 / 60)); - p.replace(FPSTR(T_2),(String)((millis() / 1000) % 60)); - } - else if(id==F("chipid")){ - p = FPSTR(HTTP_INFO_chipid); - p.replace(FPSTR(T_1),String(WIFI_getChipId(),HEX)); - } - #ifdef ESP32 - else if(id==F("chiprev")){ - p = FPSTR(HTTP_INFO_chiprev); - String rev = (String)ESP.getChipRevision(); - #ifdef _SOC_EFUSE_REG_H_ - String revb = (String)(REG_READ(EFUSE_BLK0_RDATA3_REG) >> (EFUSE_RD_CHIP_VER_RESERVE_S)&&EFUSE_RD_CHIP_VER_RESERVE_V); - p.replace(FPSTR(T_1),rev+"
"+revb); - #else - p.replace(FPSTR(T_1),rev); - #endif - } - #endif - #ifdef ESP8266 - else if(id==F("fchipid")){ - p = FPSTR(HTTP_INFO_fchipid); - p.replace(FPSTR(T_1),(String)ESP.getFlashChipId()); - } - #endif - else if(id==F("idesize")){ - p = FPSTR(HTTP_INFO_idesize); - p.replace(FPSTR(T_1),(String)ESP.getFlashChipSize()); - } - else if(id==F("flashsize")){ - #ifdef ESP8266 - p = FPSTR(HTTP_INFO_flashsize); - p.replace(FPSTR(T_1),(String)ESP.getFlashChipRealSize()); - #endif - } - else if(id==F("sdkver")){ - p = FPSTR(HTTP_INFO_sdkver); - #ifdef ESP32 - p.replace(FPSTR(T_1),(String)esp_get_idf_version()); - #else - p.replace(FPSTR(T_1),(String)system_get_sdk_version()); - #endif - } - else if(id==F("corever")){ - #ifdef ESP8266 - p = FPSTR(HTTP_INFO_corever); - p.replace(FPSTR(T_1),(String)ESP.getCoreVersion()); - #endif - } - #ifdef ESP8266 - else if(id==F("bootver")){ - p = FPSTR(HTTP_INFO_bootver); - p.replace(FPSTR(T_1),(String)system_get_boot_version()); - } - #endif - else if(id==F("cpufreq")){ - p = FPSTR(HTTP_INFO_cpufreq); - p.replace(FPSTR(T_1),(String)ESP.getCpuFreqMHz()); - } - else if(id==F("freeheap")){ - p = FPSTR(HTTP_INFO_freeheap); - p.replace(FPSTR(T_1),(String)ESP.getFreeHeap()); - } - #ifdef ESP8266 - else if(id==F("memsketch")){ - p = FPSTR(HTTP_INFO_memsketch); - p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); - p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); - } - #endif - #ifdef ESP8266 - else if(id==F("memsmeter")){ - p = FPSTR(HTTP_INFO_memsmeter); - p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); - p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); - } - #endif - else if(id==F("lastreset")){ - #ifdef ESP8266 - p = FPSTR(HTTP_INFO_lastreset); - p.replace(FPSTR(T_1),(String)ESP.getResetReason()); - #elif defined(ESP32) && defined(_ROM_RTC_H_) - // requires #include - p = FPSTR(HTTP_INFO_lastreset); - for(int i=0;i<2;i++){ - int reason = rtc_get_reset_reason(i); - String tok = (String)T_ss+(String)(i+1)+(String)T_es; - switch (reason) - { - //@todo move to array - case 1 : p.replace(tok,F("Vbat power on reset"));break; - case 3 : p.replace(tok,F("Software reset digital core"));break; - case 4 : p.replace(tok,F("Legacy watch dog reset digital core"));break; - case 5 : p.replace(tok,F("Deep Sleep reset digital core"));break; - case 6 : p.replace(tok,F("Reset by SLC module, reset digital core"));break; - case 7 : p.replace(tok,F("Timer Group0 Watch dog reset digital core"));break; - case 8 : p.replace(tok,F("Timer Group1 Watch dog reset digital core"));break; - case 9 : p.replace(tok,F("RTC Watch dog Reset digital core"));break; - case 10 : p.replace(tok,F("Instrusion tested to reset CPU"));break; - case 11 : p.replace(tok,F("Time Group reset CPU"));break; - case 12 : p.replace(tok,F("Software reset CPU"));break; - case 13 : p.replace(tok,F("RTC Watch dog Reset CPU"));break; - case 14 : p.replace(tok,F("for APP CPU, reseted by PRO CPU"));break; - case 15 : p.replace(tok,F("Reset when the vdd voltage is not stable"));break; - case 16 : p.replace(tok,F("RTC Watch dog reset digital core and rtc module"));break; - default : p.replace(tok,F("NO_MEAN")); - } - } - #endif - } - else if(id==F("apip")){ - p = FPSTR(HTTP_INFO_apip); - p.replace(FPSTR(T_1),WiFi.softAPIP().toString()); - } - else if(id==F("apmac")){ - p = FPSTR(HTTP_INFO_apmac); - p.replace(FPSTR(T_1),(String)WiFi.softAPmacAddress()); - } - #ifdef ESP32 - else if(id==F("aphost")){ - p = FPSTR(HTTP_INFO_aphost); - p.replace(FPSTR(T_1),WiFi.softAPgetHostname()); - } - #endif - else if(id==F("apssid")){ - p = FPSTR(HTTP_INFO_apssid); - p.replace(FPSTR(T_1),htmlEntities((String)WiFi_SSID())); - } - else if(id==F("apbssid")){ - p = FPSTR(HTTP_INFO_apbssid); - p.replace(FPSTR(T_1),(String)WiFi.BSSIDstr()); - } - else if(id==F("staip")){ - p = FPSTR(HTTP_INFO_staip); - p.replace(FPSTR(T_1),WiFi.localIP().toString()); - } - else if(id==F("stagw")){ - p = FPSTR(HTTP_INFO_stagw); - p.replace(FPSTR(T_1),WiFi.gatewayIP().toString()); - } - else if(id==F("stasub")){ - p = FPSTR(HTTP_INFO_stasub); - p.replace(FPSTR(T_1),WiFi.subnetMask().toString()); - } - else if(id==F("dnss")){ - p = FPSTR(HTTP_INFO_dnss); - p.replace(FPSTR(T_1),WiFi.dnsIP().toString()); - } - else if(id==F("host")){ - p = FPSTR(HTTP_INFO_host); - #ifdef ESP32 - p.replace(FPSTR(T_1),WiFi.getHostname()); - #else - p.replace(FPSTR(T_1),WiFi.hostname()); - #endif - } - else if(id==F("stamac")){ - p = FPSTR(HTTP_INFO_stamac); - p.replace(FPSTR(T_1),WiFi.macAddress()); - } - else if(id==F("conx")){ - p = FPSTR(HTTP_INFO_conx); - p.replace(FPSTR(T_1),WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); - } - #ifdef ESP8266 - else if(id==F("autoconx")){ - p = FPSTR(HTTP_INFO_autoconx); - p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); - } - #endif - #ifdef ESP32 - else if(id==F("temp")){ - // temperature is not calibrated, varying large offsets are present, use for relative temp changes only - p = FPSTR(HTTP_INFO_temp); - p.replace(FPSTR(T_1),(String)temperatureRead()); - p.replace(FPSTR(T_2),(String)((temperatureRead()+32)*1.8)); - } - #endif - return p; -} - -/** - * HTTPD CALLBACK root or redirect to captive portal - */ -void WiFiManager::handleExit() { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Exit")); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titleexit)); // @token titleexit - page += FPSTR(S_exiting); // @token exiting - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); - abort = true; -} - -/** - * HTTPD CALLBACK reset page - */ -void WiFiManager::handleReset() { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Reset")); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titlereset)); //@token titlereset - page += FPSTR(S_resetting); //@token resetting - page += FPSTR(HTTP_END); - - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); - - DEBUG_WM(F("RESETTING ESP")); - delay(1000); - reboot(); -} - -/** - * HTTPD CALLBACK erase page - */ - -// void WiFiManager::handleErase() { -// handleErase(false); -// } -void WiFiManager::handleErase(boolean opt) { - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Erase")); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase - - bool ret = erase(opt); - - if(ret) page += FPSTR(S_resetting); // @token resetting - else { - page += FPSTR(S_error); // @token erroroccur - DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFi EraseConfig failed")); - } - - page += FPSTR(HTTP_END); - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); - - if(ret){ - delay(2000); - DEBUG_WM(F("RESETTING ESP")); - reboot(); - } -} - -/** - * HTTPD CALLBACK 404 - */ -void WiFiManager::handleNotFound() { - if (captivePortal()) return; // If captive portal redirect instead of displaying the page - handleRequest(); - String message = FPSTR(S_notfound); // @token notfound - message += FPSTR(S_uri); // @token uri - message += server->uri(); - message += FPSTR(S_method); // @token method - message += ( server->method() == HTTP_GET ) ? FPSTR(S_GET) : FPSTR(S_POST); - message += FPSTR(S_args); // @token args - message += server->args(); - message += F("\n"); - - for ( uint8_t i = 0; i < server->args(); i++ ) { - message += " " + server->argName ( i ) + ": " + server->arg ( i ) + "\n"; - } - server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); - server->sendHeader(F("Pragma"), F("no-cache")); - server->sendHeader(F("Expires"), F("-1")); - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(message.length())); - server->send ( 404, FPSTR(HTTP_HEAD_CT2), message ); -} - -/** - * HTTPD redirector - * Redirect to captive portal if we got a request for another domain. - * Return true in that case so the page handler do not try to handle the request again. - */ -boolean WiFiManager::captivePortal() { - DEBUG_WM(DEBUG_DEV,"-> " + server->hostHeader()); - - if(!_enableCaptivePortal) return false; // skip redirections, @todo maybe allow redirection even when no cp ? might be useful - - String serverLoc = toStringIp(server->client().localIP()); - if(_httpPort != 80) serverLoc += ":" + (String)_httpPort; // add port if not default - bool doredirect = serverLoc != server->hostHeader(); // redirect if hostheader not server ip, prevent redirect loops - // doredirect = !isIp(server->hostHeader()) // old check - - if (doredirect) { - DEBUG_WM(DEBUG_VERBOSE,F("<- Request redirected to captive portal")); - server->sendHeader(F("Location"), (String)F("http://") + serverLoc, true); - server->send ( 302, FPSTR(HTTP_HEAD_CT2), ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. - server->client().stop(); // Stop is needed because we sent no content length - return true; - } - return false; -} - -void WiFiManager::stopCaptivePortal(){ - _enableCaptivePortal= false; - // @todo maybe disable configportaltimeout(optional), or just provide callback for user -} - -void WiFiManager::handleClose(){ - stopCaptivePortal(); - DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP close")); - handleRequest(); - String page = getHTTPHead(FPSTR(S_titleclose)); // @token titleclose - page += FPSTR(S_closing); // @token closing - server->sendHeader(FPSTR(HTTP_HEAD_CL), String(page.length())); - server->send(200, FPSTR(HTTP_HEAD_CT), page); -} - -void WiFiManager::reportStatus(String &page){ - updateConxResult(WiFi.status()); - String str; - if (WiFi_SSID() != ""){ - if (WiFi.status()==WL_CONNECTED){ - str = FPSTR(HTTP_STATUS_ON); - str.replace(FPSTR(T_i),WiFi.localIP().toString()); - str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); - } - else { - str = FPSTR(HTTP_STATUS_OFF); - str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); - if(_lastconxresult == WL_STATION_WRONG_PASSWORD){ - // wrong password - str.replace(FPSTR(T_c),"D"); // class - str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFPW)); - } - else if(_lastconxresult == WL_NO_SSID_AVAIL){ - // connect failed, or ap not found - str.replace(FPSTR(T_c),"D"); - str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFNOAP)); - } - else if(_lastconxresult == WL_CONNECT_FAILED){ - // connect failed - str.replace(FPSTR(T_c),"D"); - str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFFAIL)); - } - else{ - str.replace(FPSTR(T_c),""); - str.replace(FPSTR(T_r),""); - } - } - } - else { - str = FPSTR(HTTP_STATUS_NONE); - } - page += str; -} - -// PUBLIC - -// METHODS - -/** - * reset wifi settings, clean stored ap password - */ - -/** - * [stopConfigPortal description] - * @return {[type]} [description] - */ -bool WiFiManager::stopConfigPortal(){ - if(_configPortalIsBlocking){ - abort = true; - return true; - } - return shutdownConfigPortal(); -} - -/** - * disconnect - * @access public - * @since $dev - * @return bool success - */ -bool WiFiManager::disconnect(){ - if(WiFi.status() != WL_CONNECTED){ - DEBUG_WM(DEBUG_VERBOSE,"Disconnecting: Not connected"); - return false; - } - DEBUG_WM("Disconnecting"); - return WiFi_Disconnect(); -} - -/** - * reboot the device - * @access public - */ -void WiFiManager::reboot(){ - DEBUG_WM("Restarting"); - ESP.restart(); -} - -/** - * reboot the device - * @access public - */ -bool WiFiManager::erase(){ - return erase(false); -} - -bool WiFiManager::erase(bool opt){ - DEBUG_WM("Erasing"); - - #if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) - // if opt true, do nvs erase - if(opt){ - DEBUG_WM("Erasing NVS"); - esp_err_t err; - err = nvs_flash_init(); - DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_init: ",err!=ESP_OK ? (String)err : "Success"); - err = nvs_flash_erase(); - DEBUG_WM(DEBUG_VERBOSE,"nvs_flash_erase: ", err!=ESP_OK ? (String)err : "Success"); - return err == ESP_OK; - } - #elif defined(ESP8266) && defined(spiffs_api_h) - if(opt){ - bool ret = false; - if(SPIFFS.begin()){ - DEBUG_WM("Erasing SPIFFS"); - bool ret = SPIFFS.format(); - DEBUG_WM(DEBUG_VERBOSE,"spiffs erase: ",ret ? "Success" : "ERROR"); - } else DEBUG_WM("[ERROR] Could not start SPIFFS"); - return ret; - } - #else - (void)opt; - #endif - - DEBUG_WM("Erasing WiFi Config"); - return WiFi_eraseConfig(); -} - -/** - * [resetSettings description] - * ERASES STA CREDENTIALS - * @access public - */ -void WiFiManager::resetSettings() { - DEBUG_WM(F("resetSettings")); - WiFi_enableSTA(true,true); // must be sta to disconnect erase - - if (_resetcallback != NULL) - _resetcallback(); - - #ifdef ESP32 - WiFi.disconnect(true,true); - #else - WiFi.persistent(true); - WiFi.disconnect(true); - WiFi.persistent(false); - #endif - DEBUG_WM(F("SETTINGS ERASED")); -} - -// SETTERS - -/** - * [setTimeout description] - * @access public - * @param {[type]} unsigned long seconds [description] - */ -void WiFiManager::setTimeout(unsigned long seconds) { - setConfigPortalTimeout(seconds); -} - -/** - * [setConfigPortalTimeout description] - * @access public - * @param {[type]} unsigned long seconds [description] - */ -void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { - _configPortalTimeout = seconds * 1000; -} - -/** - * [setConnectTimeout description] - * @access public - * @param {[type]} unsigned long seconds [description] - */ -void WiFiManager::setConnectTimeout(unsigned long seconds) { - _connectTimeout = seconds * 1000; -} -/** - * toggle _cleanconnect, always disconnect before connecting - * @param {[type]} bool enable [description] - */ -void WiFiManager::setCleanConnect(bool enable){ - _cleanConnect = enable; -} - -/** - * [setConnectTimeout description - * @access public - * @param {[type]} unsigned long seconds [description] - */ -void WiFiManager::setSaveConnectTimeout(unsigned long seconds) { - _saveTimeout = seconds * 1000; -} - -/** - * [setDebugOutput description] - * @access public - * @param {[type]} boolean debug [description] - */ -void WiFiManager::setDebugOutput(boolean debug) { - _debug = debug; - if(_debug && _debugLevel == DEBUG_DEV) debugPlatformInfo(); -} - -/** - * [setAPStaticIPConfig description] - * @access public - * @param {[type]} IPAddress ip [description] - * @param {[type]} IPAddress gw [description] - * @param {[type]} IPAddress sn [description] - */ -void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { - _ap_static_ip = ip; - _ap_static_gw = gw; - _ap_static_sn = sn; -} - -/** - * [setSTAStaticIPConfig description] - * @access public - * @param {[type]} IPAddress ip [description] - * @param {[type]} IPAddress gw [description] - * @param {[type]} IPAddress sn [description] - */ -void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { - _sta_static_ip = ip; - _sta_static_gw = gw; - _sta_static_sn = sn; -} - -/** - * [setSTAStaticIPConfig description] - * @since $dev - * @access public - * @param {[type]} IPAddress ip [description] - * @param {[type]} IPAddress gw [description] - * @param {[type]} IPAddress sn [description] - * @param {[type]} IPAddress dns [description] - */ -void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns) { - setSTAStaticIPConfig(ip,gw,sn); - _sta_static_dns = dns; -} - -/** - * [setMinimumSignalQuality description] - * @access public - * @param {[type]} int quality [description] - */ -void WiFiManager::setMinimumSignalQuality(int quality) { - _minimumQuality = quality; -} - -/** - * [setBreakAfterConfig description] - * @access public - * @param {[type]} boolean shouldBreak [description] - */ -void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { - _shouldBreakAfterConfig = shouldBreak; -} - -/** - * setAPCallback, set a callback when softap is started - * @access public - * @param {[type]} void (*func)(WiFiManager* wminstance) - */ -void WiFiManager::setAPCallback( std::function func ) { - _apcallback = func; -} - -/** - * setWebServerCallback, set a callback after webserver is reset, and before routes are setup - * if we set webserver handlers before wm, they are used and wm is not by esp webserver - * on events cannot be overrided once set, and are not mutiples - * @access public - * @param {[type]} void (*func)(void) - */ -void WiFiManager::setWebServerCallback( std::function func ) { - _webservercallback = func; -} - -/** - * setSaveConfigCallback, set a save config callback after closing configportal - * @note calls only if wifi is saved or changed, or setBreakAfterConfig(true) - * @access public - * @param {[type]} void (*func)(void) - */ -void WiFiManager::setSaveConfigCallback( std::function func ) { - _savewificallback = func; -} - -/** - * setConfigResetCallback, set a callback to occur when a resetSettings() occurs - * @access public - * @param {[type]} void(*func)(void) - */ -void WiFiManager::setConfigResetCallback( std::function func ) { - _resetcallback = func; -} - -/** - * setSaveParamsCallback, set a save params callback on params save in wifi or params pages - * @access public - * @param {[type]} void (*func)(void) - */ -void WiFiManager::setSaveParamsCallback( std::function func ) { - _saveparamscallback = func; -} - -/** - * setPreSaveConfigCallback, set a callback to fire before saving wifi or params - * @access public - * @param {[type]} void (*func)(void) - */ -void WiFiManager::setPreSaveConfigCallback( std::function func ) { - _presavecallback = func; -} - -/** - * set custom head html - * custom element will be added to head, eg. new style tag etc. - * @access public - * @param char element - */ -void WiFiManager::setCustomHeadElement(const char* element) { - _customHeadElement = element; -} - -/** - * toggle wifiscan hiding of duplicate ssid names - * if this is false, wifiscan will remove duplicat Access Points - defaut true - * @access public - * @param boolean removeDuplicates [true] - */ -void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) { - _removeDuplicateAPs = removeDuplicates; -} - -/** - * toggle configportal blocking loop - * if enabled, then the configportal will enter a blocking loop and wait for configuration - * if disabled use with process() to manually process webserver - * @since $dev - * @access public - * @param boolean shoudlBlock [false] - */ -void WiFiManager::setConfigPortalBlocking(boolean shoudlBlock) { - _configPortalIsBlocking = shoudlBlock; -} - -/** - * toggle restore persistent, track internally - * sets ESP wifi.persistent so we can remember it and restore user preference on destruct - * there is no getter in esp8266 platform prior to https://github.com/esp8266/Arduino/pull/3857 - * @since $dev - * @access public - * @param boolean persistent [true] - */ -void WiFiManager::setRestorePersistent(boolean persistent) { - _userpersistent = persistent; - if(!persistent) DEBUG_WM(F("persistent is off")); -} - -/** - * toggle showing static ip form fields - * if enabled, then the static ip, gateway, subnet fields will be visible, even if not set in code - * @since $dev - * @access public - * @param boolean alwaysShow [false] - */ -void WiFiManager::setShowStaticFields(boolean alwaysShow){ - if(_disableIpFields) _staShowStaticFields = alwaysShow ? 1 : -1; - else _staShowStaticFields = alwaysShow ? 1 : 0; -} - -/** - * toggle showing dns fields - * if enabled, then the dns1 field will be visible, even if not set in code - * @since $dev - * @access public - * @param boolean alwaysShow [false] - */ -void WiFiManager::setShowDnsFields(boolean alwaysShow){ - if(_disableIpFields) _staShowDns = alwaysShow ? 1 : -1; - _staShowDns = alwaysShow ? 1 : 0; -} - -/** - * toggle showing password in wifi password field - * if not enabled, placeholder will be S_passph - * @since $dev - * @access public - * @param boolean alwaysShow [false] - */ -void WiFiManager::setShowPassword(boolean show){ - _showPassword = show; -} - -/** - * toggle captive portal - * if enabled, then devices that use captive portal checks will be redirected to root - * if not you will automatically have to navigate to ip [192.168.4.1] - * @since $dev - * @access public - * @param boolean enabled [true] - */ -void WiFiManager::setCaptivePortalEnable(boolean enabled){ - _enableCaptivePortal = enabled; -} - -/** - * toggle wifi autoreconnect policy - * if enabled, then wifi will autoreconnect automatically always - * On esp8266 we force this on when autoconnect is called, see notes - * On esp32 this is handled on SYSTEM_EVENT_STA_DISCONNECTED since it does not exist in core yet - * @since $dev - * @access public - * @param boolean enabled [true] - */ -void WiFiManager::setWiFiAutoReconnect(boolean enabled){ - _wifiAutoReconnect = enabled; -} - -/** - * toggle configportal timeout wait for station client - * if enabled, then the configportal will start timeout when no stations are connected to softAP - * disabled by default as rogue stations can keep it open if there is no auth - * @since $dev - * @access public - * @param boolean enabled [false] - */ -void WiFiManager::setAPClientCheck(boolean enabled){ - _apClientCheck = enabled; -} - -/** - * toggle configportal timeout wait for web client - * if enabled, then the configportal will restart timeout when client requests come in - * @since $dev - * @access public - * @param boolean enabled [true] - */ -void WiFiManager::setWebPortalClientCheck(boolean enabled){ - _webClientCheck = enabled; -} - -/** - * toggle wifiscan percentages or quality icons - * @since $dev - * @access public - * @param boolean enabled [false] - */ -void WiFiManager::setScanDispPerc(boolean enabled){ - _scanDispOptions = enabled; -} - -/** - * toggle configportal if autoconnect failed - * if enabled, then the configportal will be activated on autoconnect failure - * @since $dev - * @access public - * @param boolean enabled [true] - */ -void WiFiManager::setEnableConfigPortal(boolean enable) -{ - _enableConfigPortal = enable; -} - - -/** - * set the hostname (dhcp client id) - * @since $dev - * @access public - * @param char* hostname 32 character hostname to use for sta+ap in esp32, sta in esp8266 - * @return bool false if hostname is not valid - */ -bool WiFiManager::setHostname(const char * hostname){ - //@todo max length 32 - _hostname = hostname; - return true; -} - -/** - * set the soft ao channel, ignored if channelsync is true and connected - * @param int32_t wifi channel, 0 to disable - */ -void WiFiManager::setWiFiAPChannel(int32_t channel){ - _apChannel = channel; -} - -/** - * set the soft ap hidden - * @param bool wifi ap hidden, default is false - */ -void WiFiManager::setWiFiAPHidden(bool hidden){ - _apHidden = hidden; -} - - -/** - * toggle showing erase wifi config button on info page - * @param boolean enabled - */ -void WiFiManager::setShowInfoErase(boolean enabled){ - _showInfoErase = enabled; -} - -/** - * set menu items and order - * if param is present in menu , params will be removed from wifi page automatically - * eg. - * const char * menu[] = {"wifi","setup","sep","info","exit"}; - * WiFiManager.setMenu(menu); - * @since $dev - * @param uint8_t menu[] array of menu ids - */ -void WiFiManager::setMenu(const char * menu[], uint8_t size){ - // DEBUG_WM(DEBUG_VERBOSE,"setmenu array"); - _menuIds.clear(); - for(size_t i = 0; i < size; i++){ - for(size_t j = 0; j < _nummenutokens; j++){ - if(menu[i] == _menutokens[j]){ - if((String)menu[i] == "param") _paramsInWifi = false; // param auto flag - _menuIds.push_back(j); - } - } - } - // DEBUG_WM(getMenuOut()); -} - -/** - * setMenu with vector - * eg. - * std::vector menu = {"wifi","setup","sep","info","exit"}; - * WiFiManager.setMenu(menu); - * tokens can be found in _menutokens array in strings_en.h - * @shiftIncrement $dev - * @param {[type]} std::vector& menu [description] - */ -void WiFiManager::setMenu(std::vector& menu){ - // DEBUG_WM(DEBUG_VERBOSE,"setmenu vector"); - _menuIds.clear(); - for(auto menuitem : menu ){ - for(size_t j = 0; j < _nummenutokens; j++){ - if(menuitem == _menutokens[j]){ - if((String)menuitem == "param") _paramsInWifi = false; // param auto flag - _menuIds.push_back(j); - } - } - } - // DEBUG_WM(getMenuOut()); -} - - -/** - * set params as sperate page not in wifi - * NOT COMPATIBLE WITH setMenu! - * @todo scan menuids and insert param after wifi or something, same for ota - * @param bool enable - * @since $dev - */ -void WiFiManager::setParamsPage(bool enable){ - _paramsInWifi = !enable; - setMenu(enable ? _menuIdsParams : _menuIdsDefault); -} - -// GETTERS - -/** - * get config portal AP SSID - * @since 0.0.1 - * @access public - * @return String the configportal ap name - */ -String WiFiManager::getConfigPortalSSID() { - return _apName; -} - -/** - * return the last known connection result - * logged on autoconnect and wifisave, can be used to check why failed - * get as readable string with getWLStatusString(getLastConxResult); - * @since $dev - * @access public - * @return bool return wl_status codes - */ -uint8_t WiFiManager::getLastConxResult(){ - return _lastconxresult; -} - -/** - * check if wifi has a saved ap or not - * @since $dev - * @access public - * @return bool true if a saved ap config exists - */ -bool WiFiManager::getWiFiIsSaved(){ - return WiFi_hasAutoConnect(); -} - -String WiFiManager::getDefaultAPName(){ - String hostString = String(WIFI_getChipId(),HEX); - hostString.toUpperCase(); - // char hostString[16] = {0}; - // sprintf(hostString, "%06X", ESP.getChipId()); - return _wifissidprefix + "_" + hostString; -} - -/** - * setCountry - * @since $dev - * @param String cc country code, must be defined in WiFiSetCountry, US, JP, CN - */ -void WiFiManager::setCountry(String cc){ - _wificountry = cc; -} - -/** - * setClass - * @param String str body class string - */ -void WiFiManager::setClass(String str){ - _bodyClass = str; -} - -void WiFiManager::setHttpPort(uint16_t port){ - _httpPort = port; -} - -// HELPERS - -/** - * getWiFiSSID - * @since $dev - * @param bool persistent - * @return String - */ -String WiFiManager::getWiFiSSID(bool persistent){ - return WiFi_SSID(persistent); -} - -/** - * getWiFiPass - * @since $dev - * @param bool persistent - * @return String - */ -String WiFiManager::getWiFiPass(bool persistent){ - return WiFi_psk(persistent); -} - -// DEBUG -// @todo fix DEBUG_WM(0,0); -template -void WiFiManager::DEBUG_WM(Generic text) { - DEBUG_WM(DEBUG_NOTIFY,text,""); -} - -template -void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text) { - if(_debugLevel >= level) DEBUG_WM(level,text,""); -} - -template -void WiFiManager::DEBUG_WM(Generic text,Genericb textb) { - DEBUG_WM(DEBUG_NOTIFY,text,textb); -} - -template -void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { - if(!_debug || _debugLevel < level) return; - - if(_debugLevel >= DEBUG_MAX){ - uint32_t free; - uint16_t max; - uint8_t frag; - #ifdef ESP8266 - ESP.getHeapStats(&free, &max, &frag); - _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); - #elif defined ESP32 - // total_free_bytes; ///< Total free bytes in the heap. Equivalent to multi_free_heap_size(). - // total_allocated_bytes; ///< Total bytes allocated to data in the heap. - // largest_free_block; ///< Size of largest free block in the heap. This is the largest malloc-able size. - // minimum_free_bytes; ///< Lifetime minimum free heap size. Equivalent to multi_minimum_free_heap_size(). - // allocated_blocks; ///< Number of (variable size) blocks allocated in the heap. - // free_blocks; ///< Number of (variable size) free blocks in the heap. - // total_blocks; ///< Total number of (variable size) blocks in the heap. - multi_heap_info_t info; - heap_caps_get_info(&info, MALLOC_CAP_INTERNAL); - free = info.total_free_bytes; - max = info.largest_free_block; - frag = 100 - (max * 100) / free; - _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); - #endif - } - _debugPort.print("*WM: "); - if(_debugLevel == DEBUG_DEV) _debugPort.print("["+(String)level+"] "); - _debugPort.print(text); - if(textb){ - _debugPort.print(" "); - _debugPort.print(textb); - } - _debugPort.println(); -} - -/** - * [debugSoftAPConfig description] - * @access public - * @return {[type]} [description] - */ -void WiFiManager::debugSoftAPConfig(){ - wifi_country_t country; - - #ifdef ESP8266 - softap_config config; - wifi_softap_get_config(&config); - wifi_get_country(&country); - #elif defined(ESP32) - wifi_config_t conf_config; - esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK - wifi_ap_config_t config = conf_config.ap; - esp_wifi_get_country(&country); - #endif - - DEBUG_WM(F("SoftAP Configuration")); - DEBUG_WM(FPSTR(D_HR)); - DEBUG_WM(F("ssid: "),(char *) config.ssid); - DEBUG_WM(F("password: "),(char *) config.password); - DEBUG_WM(F("ssid_len: "),config.ssid_len); - DEBUG_WM(F("channel: "),config.channel); - DEBUG_WM(F("authmode: "),config.authmode); - DEBUG_WM(F("ssid_hidden: "),config.ssid_hidden); - DEBUG_WM(F("max_connection: "),config.max_connection); - DEBUG_WM(F("country: "),(String)country.cc); - DEBUG_WM(F("beacon_interval: "),(String)config.beacon_interval + "(ms)"); - DEBUG_WM(FPSTR(D_HR)); -} - -/** - * [debugPlatformInfo description] - * @access public - * @return {[type]} [description] - */ -void WiFiManager::debugPlatformInfo(){ - #ifdef ESP8266 - system_print_meminfo(); - DEBUG_WM(F("getCoreVersion(): "),ESP.getCoreVersion()); - DEBUG_WM(F("system_get_sdk_version(): "),system_get_sdk_version()); - DEBUG_WM(F("system_get_boot_version():"),system_get_boot_version()); - DEBUG_WM(F("getFreeHeap(): "),(String)ESP.getFreeHeap()); - #elif defined(ESP32) - size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); - DEBUG_WM("Free heap: ", ESP.getFreeHeap()); - DEBUG_WM("ESP SDK version: ", ESP.getSdkVersion()); - // esp_chip_info_t chipInfo; - // esp_chip_info(&chipInfo); - // DEBUG_WM("Chip Info: Model: ",chipInfo.model); - // DEBUG_WM("Chip Info: Cores: ",chipInfo.cores); - // DEBUG_WM("Chip Info: Rev: ",chipInfo.revision); - // DEBUG_WM(printf("Chip Info: Model: %d, cores: %d, revision: %d", chipInfo.model.c_str(), chipInfo.cores, chipInfo.revision)); - // DEBUG_WM("Chip Rev: ",(String)ESP.getChipRevision()); - // core version is not avail - #endif -} - -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) { - for (size_t i = 0; i < str.length(); i++) { - int c = str.charAt(i); - if (c != '.' && (c < '0' || c > '9')) { - return false; - } - } - return true; -} - -/** IP to String? */ -String WiFiManager::toStringIp(IPAddress ip) { - String res = ""; - for (int i = 0; i < 3; i++) { - res += String((ip >> (8 * i)) & 0xFF) + "."; - } - res += String(((ip >> 8 * 3)) & 0xFF); - return res; -} - -boolean WiFiManager::validApPassword(){ - // check that ap password is valid, return false - if (_apPassword == NULL) _apPassword = ""; - if (_apPassword != "") { - if (_apPassword.length() < 8 || _apPassword.length() > 63) { - DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); - _apPassword = ""; - return false; // @todo FATAL or fallback to empty ? - } - DEBUG_WM(DEBUG_VERBOSE,F("AccessPoint set password is VALID")); - DEBUG_WM(_apPassword); - } - return true; -} - -/** - * encode htmlentities - * @since $dev - * @param string str string to replace entities - * @return string encoded string - */ -String WiFiManager::htmlEntities(String str) { - str.replace("&","&"); - str.replace("<","<"); - str.replace(">",">"); - // str.replace("'","'"); - // str.replace("\"","""); - // str.replace("/": "/"); - // str.replace("`": "`"); - // str.replace("=": "="); -return str; -} - -/** - * [getWLStatusString description] - * @access public - * @param {[type]} uint8_t status [description] - * @return {[type]} [description] - */ -String WiFiManager::getWLStatusString(uint8_t status){ - if(status <= 7) return WIFI_STA_STATUS[status]; - return FPSTR(S_NA); -} - -String WiFiManager::encryptionTypeStr(uint8_t authmode) { - // DEBUG_WM("enc_tye: ",authmode); - return AUTH_MODE_NAMES[authmode]; -} - -String WiFiManager::getModeString(uint8_t mode){ - if(mode <= 3) return WIFI_MODES[mode]; - return FPSTR(S_NA); -} - -bool WiFiManager::WiFiSetCountry(){ - if(_wificountry == "") return false; // skip not set - bool ret = false; - #ifdef ESP32 - // @todo check if wifi is init, no idea how, doesnt seem to be exposed atm ( might be now! ) - if(WiFi.getMode() == WIFI_MODE_NULL); // exception if wifi not init! - else if(_wificountry == "US") ret = esp_wifi_set_country(&WM_COUNTRY_US) == ESP_OK; - else if(_wificountry == "JP") ret = esp_wifi_set_country(&WM_COUNTRY_JP) == ESP_OK; - else if(_wificountry == "CN") ret = esp_wifi_set_country(&WM_COUNTRY_CN) == ESP_OK; - else DEBUG_WM(DEBUG_ERROR,"[ERROR] country code not found"); - - #elif defined(ESP8266) - // if(WiFi.getMode() == WIFI_OFF); // exception if wifi not init! - if(_wificountry == "US") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_US); - else if(_wificountry == "JP") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_JP); - else if(_wificountry == "CN") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_CN); - else DEBUG_WM(DEBUG_ERROR,"[ERROR] country code not found"); - #endif - - if(ret) DEBUG_WM(DEBUG_VERBOSE,"esp_wifi_set_country: " + _wificountry); - else DEBUG_WM(DEBUG_ERROR,"[ERROR] esp_wifi_set_country failed"); - return ret; -} - -// set mode ignores WiFi.persistent -bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { - bool ret; - #ifdef ESP8266 - if((wifi_get_opmode() == (uint8) m ) && !persistent) { - return true; - } - ETS_UART_INTR_DISABLE(); - if(persistent) ret = wifi_set_opmode(m); - else ret = wifi_set_opmode_current(m); - ETS_UART_INTR_ENABLE(); - return ret; - #elif defined(ESP32) - if(persistent && esp32persistent) WiFi.persistent(true); - ret = WiFi.mode(m); // @todo persistent check persistant mode , NI - if(persistent && esp32persistent) WiFi.persistent(false); - return ret; - #endif -} -bool WiFiManager::WiFi_Mode(WiFiMode_t m) { - return WiFi_Mode(m,false); -} - -// sta disconnect without persistent -bool WiFiManager::WiFi_Disconnect() { - #ifdef ESP8266 - if((WiFi.getMode() & WIFI_STA) != 0) { - bool ret; - DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); - ETS_UART_INTR_DISABLE(); // @todo probably not needed - ret = wifi_station_disconnect(); - ETS_UART_INTR_ENABLE(); - return ret; - } - #elif defined(ESP32) - DEBUG_WM(DEBUG_DEV,F("WIFI station disconnect")); - return WiFi.disconnect(); // not persistent atm - #endif - return false; -} - -// toggle STA without persistent -bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { - DEBUG_WM(DEBUG_DEV,F("WiFi station enable")); - #ifdef ESP8266 - WiFiMode_t newMode; - WiFiMode_t currentMode = WiFi.getMode(); - bool isEnabled = (currentMode & WIFI_STA) != 0; - if(enable) newMode = (WiFiMode_t)(currentMode | WIFI_STA); - else newMode = (WiFiMode_t)(currentMode & (~WIFI_STA)); - - if((isEnabled != enable) || persistent) { - if(enable) { - if(persistent) DEBUG_WM(DEBUG_DEV,F("enableSTA PERSISTENT ON")); - return WiFi_Mode(newMode,persistent); - } - else { - return WiFi_Mode(newMode,persistent); - } - } else { - return true; - } - #elif defined(ESP32) - bool ret; - if(persistent && esp32persistent) WiFi.persistent(true); - ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform - if(persistent && esp32persistent) WiFi.persistent(false); - return ret; - #endif -} -bool WiFiManager::WiFi_enableSTA(bool enable) { - return WiFi_enableSTA(enable,false); -} - -bool WiFiManager::WiFi_eraseConfig() { - #ifdef ESP8266 - #ifndef WM_FIXERASECONFIG - return ESP.eraseConfig(); - #else - // erase config BUG replacement - // https://github.com/esp8266/Arduino/pull/3635 - const size_t cfgSize = 0x4000; - size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; - - for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) { - if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) { - return false; - } - } - return true; - #endif - #elif defined(ESP32) - bool ret; - WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! - WiFi.persistent(true); - ret = WiFi.disconnect(true,true); - WiFi.persistent(false); - return ret; - #endif -} - -uint8_t WiFiManager::WiFi_softap_num_stations(){ - #ifdef ESP8266 - return wifi_softap_get_station_num(); - #elif defined(ESP32) - return WiFi.softAPgetStationNum(); - #endif -} - -bool WiFiManager::WiFi_hasAutoConnect(){ - return WiFi_SSID(true) != ""; -} - -String WiFiManager::WiFi_SSID(bool persistent) const{ - - #ifdef ESP8266 - struct station_config conf; - if(persistent) wifi_station_get_config_default(&conf); - else wifi_station_get_config(&conf); - - char tmp[33]; //ssid can be up to 32chars, => plus null term - memcpy(tmp, conf.ssid, sizeof(conf.ssid)); - tmp[32] = 0; //nullterm in case of 32 char ssid - return String(reinterpret_cast(tmp)); - - #elif defined(ESP32) - if(persistent){ - wifi_config_t conf; - esp_wifi_get_config(WIFI_IF_STA, &conf); - return String(reinterpret_cast(conf.sta.ssid)); - } - else { - if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ - return String(); - } - wifi_ap_record_t info; - if(!esp_wifi_sta_get_ap_info(&info)) { - return String(reinterpret_cast(info.ssid)); - } - return String(); - } - #endif -} - -String WiFiManager::WiFi_psk(bool persistent) const { - #ifdef ESP8266 - struct station_config conf; - - if(persistent) wifi_station_get_config_default(&conf); - else wifi_station_get_config(&conf); - - char tmp[65]; //psk is 64 bytes hex => plus null term - memcpy(tmp, conf.password, sizeof(conf.password)); - tmp[64] = 0; //null term in case of 64 byte psk - return String(reinterpret_cast(tmp)); - - #elif defined(ESP32) - // only if wifi is init - if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ - return String(); - } - wifi_config_t conf; - esp_wifi_get_config(WIFI_IF_STA, &conf); - return String(reinterpret_cast(conf.sta.password)); - #endif -} - -#ifdef ESP32 -void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ - if(!_hasBegun){ - // DEBUG_WM(DEBUG_VERBOSE,"[ERROR] WiFiEvent, not ready"); - Serial.println("[ERROR] wm not ready"); - return; - } - // DEBUG_WM(DEBUG_VERBOSE,"[EVENT]",event); - if(event == SYSTEM_EVENT_STA_DISCONNECTED){ - DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON:",info.disconnected.reason); - if(info.disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.disconnected.reason == WIFI_REASON_AUTH_FAIL){ - _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail - } else _lastconxresulttmp = WiFi.status(); - if(info.disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(DEBUG_VERBOSE,"[EVENT] WIFI_REASON: NO_AP_FOUND"); - #ifdef esp32autoreconnect - DEBUG_WM(DEBUG_VERBOSE,"[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting"); - WiFi.reconnect(); - #endif - } - else if(event == SYSTEM_EVENT_SCAN_DONE){ - uint16_t scans = WiFi.scanComplete(); - WiFi_scanComplete(scans); - } -} -#endif - -void WiFiManager::WiFi_autoReconnect(){ - #ifdef ESP8266 - WiFi.setAutoReconnect(_wifiAutoReconnect); - #elif defined(ESP32) - // if(_wifiAutoReconnect){ - // @todo move to seperate method, used for event listener now - DEBUG_WM(DEBUG_VERBOSE,"ESP32 event handler enabled"); - using namespace std::placeholders; - wm_event_id = WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); - // } - #endif -} - -#endif diff --git a/lib/WiFiManager-2.0.3-alpha/WiFiManager.h b/lib/WiFiManager-2.0.3-alpha/WiFiManager.h deleted file mode 100644 index 0834390a..00000000 --- a/lib/WiFiManager-2.0.3-alpha/WiFiManager.h +++ /dev/null @@ -1,616 +0,0 @@ -/** - * WiFiManager.h - * - * WiFiManager, a library for the ESP8266/Arduino platform - * for configuration of WiFi credentials using a Captive Portal - * - * @author Creator tzapu - * @author tablatronix - * @version 0.0.0 - * @license MIT - */ - - -#ifndef WiFiManager_h -#define WiFiManager_h - -#if defined(ESP8266) || defined(ESP32) - -#ifdef ESP8266 -#include -#endif - -#include - -// #define WM_MDNS // includes MDNS, also set MDNS with sethostname -// #define WM_FIXERASECONFIG // use erase flash fix -// #define WM_ERASE_NVS // esp32 erase(true) will erase NVS -// #define WM_RTC // esp32 info page will include reset reasons - -// #define WM_JSTEST // build flag for enabling js xhr tests -// #define WIFI_MANAGER_OVERRIDE_STRINGS // build flag for using own strings include - -#ifdef ARDUINO_ESP8266_RELEASE_2_3_0 -#warning "ARDUINO_ESP8266_RELEASE_2_3_0, some WM features disabled" -#define WM_NOASYNC // esp8266 no async scan wifi -#endif - -// #include "soc/efuse_reg.h" // include to add efuse chip rev to info, getChipRevision() is almost always the same though, so not sure why it matters. - -// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge, @DEPRECATED -// autoreconnect is WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 - -#define WM_WEBSERVERSHIM // use webserver shim lib - -#ifdef ESP8266 - - extern "C" { - #include "user_interface.h" - } - #include - #include - - #ifdef WM_MDNS - #include - #endif - - #define WIFI_getChipId() ESP.getChipId() - #define WM_WIFIOPEN ENC_TYPE_NONE - -#elif defined(ESP32) - - #include - #include - - #define WIFI_getChipId() (uint32_t)ESP.getEfuseMac() - #define WM_WIFIOPEN WIFI_AUTH_OPEN - - #ifndef WEBSERVER_H - #ifdef WM_WEBSERVERSHIM - #include - #else - #include - // Forthcoming official ? probably never happening - // https://github.com/esp8266/ESPWebServer - #endif - #endif - - #ifdef WM_ERASE_NVS - #include - #include - #endif - - #ifdef WM_MDNS - #include - #endif - - #ifdef WM_RTC - #include - #endif - -#else -#endif - -#include -#include -#include "strings_en.h" - -#ifndef WIFI_MANAGER_MAX_PARAMS - #define WIFI_MANAGER_MAX_PARAMS 5 // params will autoincrement and realloc by this amount when max is reached -#endif - -#define WFM_LABEL_BEFORE 1 -#define WFM_LABEL_AFTER 2 -#define WFM_NO_LABEL 0 - -class WiFiManagerParameter { - public: - /** - Create custom parameters that can be added to the WiFiManager setup web page - @id is used for HTTP queries and must not contain spaces nor other special characters - */ - WiFiManagerParameter(); - WiFiManagerParameter(const char *custom); - WiFiManagerParameter(const char *id, const char *label); - WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length); - WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom); - WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); - ~WiFiManagerParameter(); - // WiFiManagerParameter& operator=(const WiFiManagerParameter& rhs); - - const char *getID(); - const char *getValue(); - const char *getLabel(); - const char *getPlaceholder(); // @deprecated, use getLabel - int getValueLength(); - int getLabelPlacement(); - const char *getCustomHTML(); - void setValue(const char *defaultValue, int length); - - protected: - void init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); - - private: - WiFiManagerParameter& operator=(const WiFiManagerParameter&); - const char *_id; - const char *_label; - char *_value; - int _length; - int _labelPlacement; - const char *_customHTML; - friend class WiFiManager; -}; - - -class WiFiManager -{ - public: - WiFiManager(Stream& consolePort); - WiFiManager(); - ~WiFiManager(); - void WiFiManagerInit(); - - // auto connect to saved wifi, or custom, and start config portal on failures - boolean autoConnect(); - boolean autoConnect(char const *apName, char const *apPassword = NULL); - - //manually start the config portal, autoconnect does this automatically on connect failure - boolean startConfigPortal(); // auto generates apname - boolean startConfigPortal(char const *apName, char const *apPassword = NULL); - - //manually stop the config portal if started manually, stop immediatly if non blocking, flag abort if blocking - bool stopConfigPortal(); - - //manually start the web portal, autoconnect does this automatically on connect failure - void startWebPortal(); - - //manually stop the web portal if started manually - void stopWebPortal(); - - // Run webserver processing, if setConfigPortalBlocking(false) - boolean process(); - - // get the AP name of the config portal, so it can be used in the callback - String getConfigPortalSSID(); - int getRSSIasQuality(int RSSI); - - // erase wifi credentials - void resetSettings(); - - // reboot esp - void reboot(); - - // disconnect wifi, without persistent saving or erasing - bool disconnect(); - - // erase esp - bool erase(); - bool erase(bool opt); - - //adds a custom parameter, returns false on failure - bool addParameter(WiFiManagerParameter *p); - - //returns the list of Parameters - WiFiManagerParameter** getParameters(); - - // returns the Parameters Count - int getParametersCount(); - - // SET CALLBACKS - - //called after AP mode and config portal has started - void setAPCallback( std::function func ); - - //called after webserver has started - void setWebServerCallback( std::function func ); - - //called when settings reset have been triggered - void setConfigResetCallback( std::function func ); - - //called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) - void setSaveConfigCallback( std::function func ); - - //called when settings have been changed and connection was successful - void setSaveParamsCallback( std::function func ); - - //called when settings before have been changed and connection was successful - void setPreSaveConfigCallback( std::function func ); - - - //sets timeout before AP,webserver loop ends and exits even if there has been no setup. - //useful for devices that failed to connect at some point and got stuck in a webserver loop - //in seconds setConfigPortalTimeout is a new name for setTimeout, ! not used if setConfigPortalBlocking - void setConfigPortalTimeout(unsigned long seconds); - void setTimeout(unsigned long seconds); // @deprecated, alias - - //sets timeout for which to attempt connecting, useful if you get a lot of failed connects - void setConnectTimeout(unsigned long seconds); - - //sets timeout for which to attempt connecting on saves, useful if there are bugs in esp waitforconnectloop - void setSaveConnectTimeout(unsigned long seconds); - - // toggle debug output - void setDebugOutput(boolean debug); - - //set min quality percentage to include in scan, defaults to 8% if not specified - void setMinimumSignalQuality(int quality = 8); - - //sets a custom ip /gateway /subnet configuration - void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); - - //sets config for a static IP - void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); - - //sets config for a static IP with DNS - void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns); - - //if this is set, it will exit after config, even if connection is unsuccessful. - void setBreakAfterConfig(boolean shouldBreak); - - // if this is set, portal will be blocking and wait until save or exit, - // is false user must manually `process()` to handle config portal, - // setConfigPortalTimeout is ignored in this mode, user is responsible for closing configportal - void setConfigPortalBlocking(boolean shouldBlock); - - //if this is set, customise style - void setCustomHeadElement(const char* element); - - //if this is true, remove duplicated Access Points - defaut true - void setRemoveDuplicateAPs(boolean removeDuplicates); - - //setter for ESP wifi.persistent so we can remember it and restore user preference, as WIFi._persistent is protected - void setRestorePersistent(boolean persistent); - - //if true, always show static net inputs, IP, subnet, gateway, else only show if set via setSTAStaticIPConfig - void setShowStaticFields(boolean alwaysShow); - - //if true, always show static dns, esle only show if set via setSTAStaticIPConfig - void setShowDnsFields(boolean alwaysShow); - - // toggle showing the saved wifi password in wifi form, could be a security issue. - void setShowPassword(boolean show); - - //if false, disable captive portal redirection - void setCaptivePortalEnable(boolean enabled); - - //if false, timeout captive portal even if a STA client connected to softAP (false), suggest disabling if captiveportal is open - void setAPClientCheck(boolean enabled); - - //if true, reset timeout when webclient connects (true), suggest disabling if captiveportal is open - void setWebPortalClientCheck(boolean enabled); - - // if true, enable autoreconnecting - void setWiFiAutoReconnect(boolean enabled); - - // if true, wifiscan will show percentage instead of quality icons, until we have better templating - void setScanDispPerc(boolean enabled); - - // if true (default) then start the config portal from autoConnect if connection failed - void setEnableConfigPortal(boolean enable); - - // set a custom hostname, sets sta and ap dhcp client id for esp32, and sta for esp8266 - bool setHostname(const char * hostname); - - // show erase wifi onfig button on info page, true - void setShowInfoErase(boolean enabled); - - // set ap channel - void setWiFiAPChannel(int32_t channel); - - // set ap hidden - void setWiFiAPHidden(bool hidden); // default false - - // clean connect, always disconnect before connecting - void setCleanConnect(bool enable); // default false - - // set custom menu items and order, vector or arr - // see _menutokens for ids - void setMenu(std::vector& menu); - void setMenu(const char* menu[], uint8_t size); - - // add params to its own menu page and remove from wifi, NOT TO BE COMBINED WITH setMenu! - void setParamsPage(bool enable); - - // get last connection result, includes autoconnect and wifisave - uint8_t getLastConxResult(); - - // get a status as string - String getWLStatusString(uint8_t status); - - // get wifi mode as string - String getModeString(uint8_t mode); - - // check if the module has a saved ap to connect to - bool getWiFiIsSaved(); - - // helper to get saved ssid, if persistent get stored, else get current if connected - String getWiFiPass(bool persistent = false); - - // helper to get saved password, if persistent get stored, else get current if connected - String getWiFiSSID(bool persistent = false); - - // debug output the softap config - void debugSoftAPConfig(); - - // debug output platform info and versioning - void debugPlatformInfo(); - - // helper for html - String htmlEntities(String str); - - // set the country code for wifi settings, CN - void setCountry(String cc); - - // set body class (invert), may be used for hacking in alt classes in the future - void setClass(String str); - - // get default ap esp uses , esp_chipid etc - String getDefaultAPName(); - - // set port of webserver, 80 - void setHttpPort(uint16_t port); - - std::unique_ptr dnsServer; - - #if defined(ESP32) && defined(WM_WEBSERVERSHIM) - using WM_WebServer = WebServer; - #else - using WM_WebServer = ESP8266WebServer; - #endif - - std::unique_ptr server; - - private: - std::vector _menuIds; - std::vector _menuIdsParams = {"wifi","param","info","exit"}; - std::vector _menuIdsDefault = {"wifi","info","exit"}; - - // ip configs @todo struct ? - IPAddress _ap_static_ip; - IPAddress _ap_static_gw; - IPAddress _ap_static_sn; - IPAddress _sta_static_ip; - IPAddress _sta_static_gw; - IPAddress _sta_static_sn; - IPAddress _sta_static_dns; - - // defaults - const byte DNS_PORT = 53; - const byte HTTP_PORT = 80; - String _apName = "no-net"; - String _apPassword = ""; - String _ssid = ""; - String _pass = ""; - - // options flags - unsigned long _configPortalTimeout = 0; // ms close config portal loop if set (depending on _cp/webClientCheck options) - unsigned long _connectTimeout = 0; // ms stop trying to connect to ap if set - unsigned long _saveTimeout = 0; // ms stop trying to connect to ap on saves, in case bugs in esp waitforconnectresult - unsigned long _configPortalStart = 0; // ms config portal start time (updated for timeouts) - unsigned long _webPortalAccessed = 0; // ms last web access time - WiFiMode_t _usermode = WIFI_STA; // Default user mode - String _wifissidprefix = FPSTR(S_ssidpre); // auto apname prefix prefix+chipid - uint8_t _lastconxresult = WL_IDLE_STATUS; // store last result when doing connect operations - int _numNetworks = 0; // init index for numnetworks wifiscans - unsigned long _lastscan = 0; // ms for timing wifi scans - unsigned long _startscan = 0; // ms for timing wifi scans - int _cpclosedelay = 2000; // delay before wifisave, prevents captive portal from closing to fast. - bool _cleanConnect = false; // disconnect before connect in connectwifi, increases stability on connects - - bool _disableSTA = false; // disable sta when starting ap, always - bool _disableSTAConn = true; // disable sta when starting ap, if sta is not connected ( stability ) - bool _channelSync = false; // use same wifi sta channel when starting ap - int32_t _apChannel = 0; // channel to use for ap - bool _apHidden = false; // store softap hidden value - uint16_t _httpPort = 80; // port for webserver - - #ifdef ESP32 - wifi_event_id_t wm_event_id; - static uint8_t _lastconxresulttmp; // tmp var for esp32 callback - #endif - - #ifndef WL_STATION_WRONG_PASSWORD - uint8_t WL_STATION_WRONG_PASSWORD = 7; // @kludge define a WL status for wrong password - #endif - - // parameter options - int _minimumQuality = -1; // filter wifiscan ap by this rssi - int _staShowStaticFields = 0; // ternary 1=always show static ip fields, 0=only if set, -1=never(cannot change ips via web!) - int _staShowDns = 0; // ternary 1=always show dns, 0=only if set, -1=never(cannot change dns via web!) - boolean _removeDuplicateAPs = true; // remove dup aps from wifiscan - boolean _showPassword = false; // show or hide saved password on wifi form, might be a security issue! - boolean _shouldBreakAfterConfig = false; // stop configportal on save failure - boolean _configPortalIsBlocking = true; // configportal enters blocking loop - boolean _enableCaptivePortal = true; // enable captive portal redirection - boolean _userpersistent = true; // users preffered persistence to restore - boolean _wifiAutoReconnect = true; // there is no platform getter for this, we must assume its true and make it so - boolean _apClientCheck = false; // keep cp alive if ap have station - boolean _webClientCheck = true; // keep cp alive if web have client - boolean _scanDispOptions = false; // show percentage in scans not icons - boolean _paramsInWifi = true; // show custom parameters on wifi page - boolean _showInfoErase = true; // info page erase button - boolean _showBack = false; // show back button - boolean _enableConfigPortal = true; // use config portal if autoconnect failed - const char * _hostname = ""; // hostname for esp8266 for dhcp, and or MDNS - - const char* _customHeadElement = ""; // store custom head element html from user - String _bodyClass = ""; // class to add to body - - // internal options - - // wifiscan notes - // The following are background wifi scanning optimizations - // experimental to make scans faster, preload scans after starting cp, and visiting home page, so when you click wifi its already has your list - // ideally we would add async and xhr here but I am holding off on js requirements atm - // might be slightly buggy since captive portals hammer the home page, @todo workaround this somehow. - // cache time helps throttle this - // async enables asyncronous scans, so they do not block anything - // the refresh button bypasses cache - boolean _preloadwifiscan = true; // preload wifiscan if true - boolean _asyncScan = false; // perform wifi network scan async - unsigned int _scancachetime = 30000; // ms cache time for background scans - - boolean _disableIpFields = false; // modify function of setShow_X_Fields(false), forces ip fields off instead of default show if set, eg. _staShowStaticFields=-1 - - String _wificountry = ""; // country code, @todo define in strings lang - - // wrapper functions for handling setting and unsetting persistent for now. - bool esp32persistent = false; - bool _hasBegun = false; // flag wm loaded,unloaded - void _begin(); - void _end(); - - void setupConfigPortal(); - bool shutdownConfigPortal(); - bool setupHostname(bool restart); - -#ifdef NO_EXTRA_4K_HEAP - boolean _tryWPS = false; // try WPS on save failure, unsupported - void startWPS(); -#endif - - bool startAP(); - - uint8_t connectWifi(String ssid, String pass); - bool setSTAConfig(); - bool wifiConnectDefault(); - bool wifiConnectNew(String ssid, String pass); - - uint8_t waitForConnectResult(); - uint8_t waitForConnectResult(uint16_t timeout); - void updateConxResult(uint8_t status); - - // webserver handlers - void handleRoot(); - void handleWifi(boolean scan); - void handleWifiSave(); - void handleInfo(); - void handleReset(); - void handleNotFound(); - void handleExit(); - void handleClose(); - // void handleErase(); - void handleErase(boolean opt); - void handleParam(); - void handleWiFiStatus(); - void handleRequest(); - void handleParamSave(); - void doParamSave(); - - boolean captivePortal(); - boolean configPortalHasTimeout(); - uint8_t processConfigPortal(); - void stopCaptivePortal(); - - // wifi platform abstractions - bool WiFi_Mode(WiFiMode_t m); - bool WiFi_Mode(WiFiMode_t m,bool persistent); - bool WiFi_Disconnect(); - bool WiFi_enableSTA(bool enable); - bool WiFi_enableSTA(bool enable,bool persistent); - bool WiFi_eraseConfig(); - uint8_t WiFi_softap_num_stations(); - bool WiFi_hasAutoConnect(); - void WiFi_autoReconnect(); - String WiFi_SSID(bool persistent = false) const; - String WiFi_psk(bool persistent = false) const; - bool WiFi_scanNetworks(); - bool WiFi_scanNetworks(bool force,bool async); - bool WiFi_scanNetworks(unsigned int cachetime,bool async); - bool WiFi_scanNetworks(unsigned int cachetime); - void WiFi_scanComplete(int networksFound); - bool WiFiSetCountry(); - - #ifdef ESP32 - void WiFiEvent(WiFiEvent_t event, system_event_info_t info); - #endif - - // output helpers - String getParamOut(); - String getIpForm(String id, String title, String value); - String getScanItemOut(); - String getStaticOut(); - String getHTTPHead(String title); - String getMenuOut(); - //helpers - boolean isIp(String str); - String toStringIp(IPAddress ip); - boolean validApPassword(); - String encryptionTypeStr(uint8_t authmode); - void reportStatus(String &page); - String getInfoData(String id); - - // flags - boolean connect; - boolean abort; - boolean reset = false; - boolean configPortalActive = false; - boolean webPortalActive = false; - boolean portalTimeoutResult = false; - boolean portalAbortResult = false; - boolean storeSTAmode = true; // option store persistent STA mode in connectwifi - int timer = 0; - - // WiFiManagerParameter - int _paramsCount = 0; - int _max_params; - WiFiManagerParameter** _params = NULL; - - // debugging - typedef enum { - DEBUG_ERROR = 0, - DEBUG_NOTIFY = 1, // default stable - DEBUG_VERBOSE = 2, - DEBUG_DEV = 3, // default dev - DEBUG_MAX = 4 - } wm_debuglevel_t; - - boolean _debug = true; - - // build debuglevel support - // @todo use DEBUG_ESP_x? - #ifdef WM_DEBUG_LEVEL - uint8_t _debugLevel = (uint8_t)WM_DEBUG_LEVEL; - #else - uint8_t _debugLevel = DEBUG_DEV; // default debug level - #endif - - // @todo use DEBUG_ESP_PORT ? - #ifdef WM_DEBUG_PORT - Stream& _debugPort = WM_DEBUG_PORT; - #else - Stream& _debugPort = Serial; // debug output stream ref - #endif - - template - void DEBUG_WM(Generic text); - - template - void DEBUG_WM(wm_debuglevel_t level,Generic text); - template - void DEBUG_WM(Generic text,Genericb textb); - template - void DEBUG_WM(wm_debuglevel_t level, Generic text,Genericb textb); - - // callbacks - // @todo use cb list (vector) maybe event ids, allow no return value - std::function _apcallback; - std::function _webservercallback; - std::function _savewificallback; - std::function _presavecallback; - std::function _saveparamscallback; - std::function _resetcallback; - - template - auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { - 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 - -#endif \ No newline at end of file diff --git a/lib/WiFiManager-2.0.3-alpha/examples/Advanced/Advanced.ino b/lib/WiFiManager-2.0.3-alpha/examples/Advanced/Advanced.ino deleted file mode 100644 index 6e4ff734..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/Advanced/Advanced.ino +++ /dev/null @@ -1,134 +0,0 @@ -/** - * WiFiManager advanced demo, contains advanced configurartion options - * Implements TRIGGEN_PIN button press, press for ondemand configportal, hold for 3 seconds for reset settings. - */ -#include // https://github.com/tzapu/WiFiManager - -#define TRIGGER_PIN 0 - -WiFiManager wm; // global wm instance -WiFiManagerParameter custom_field; // global param ( for non blocking w params ) - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - Serial.begin(115200); - Serial.setDebugOutput(true); - delay(3000); - Serial.println("\n Starting"); - - pinMode(TRIGGER_PIN, INPUT); - - // wm.resetSettings(); // wipe settings - - // add a custom input field - int customFieldLength = 40; - - - // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\""); - - // test custom html input type(checkbox) - // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\" type=\"checkbox\""); // custom html type - - // test custom html(radio) - const char* custom_radio_str = "
One
Two
Three"; - new (&custom_field) WiFiManagerParameter(custom_radio_str); // custom html input - - wm.addParameter(&custom_field); - wm.setSaveParamsCallback(saveParamCallback); - - // custom menu via array or vector - // - // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (sep is seperator) (if param is in menu, params will not show up in wifi page!) - // const char* menu[] = {"wifi","info","param","sep","restart","exit"}; - // wm.setMenu(menu,6); - std::vector menu = {"wifi","info","param","sep","restart","exit"}; - wm.setMenu(menu); - - // set dark theme - wm.setClass("invert"); - - - //set static ip - // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn - // wm.setShowStaticFields(true); // force show static ip fields - // wm.setShowDnsFields(true); // force show dns field always - - // wm.setConnectTimeout(20); // how long to try to connect for before continuing - wm.setConfigPortalTimeout(30); // auto close configportal after n seconds - // wm.setCaptivePortalEnable(false); // disable captive portal redirection - // wm.setAPClientCheck(true); // avoid timeout if client connected to softap - - // wifi scan settings - // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) - // wm.setMinimumSignalQuality(20); // set min RSSI (percentage) to show in scans, null = 8% - // wm.setShowInfoErase(false); // do not show erase button on info page - // wm.setScanDispPerc(true); // show RSSI as percentage not graph icons - - // wm.setBreakAfterConfig(true); // always exit configportal even if wifi save fails - - bool res; - // res = wm.autoConnect(); // auto generated AP name from chipid - // res = wm.autoConnect("AutoConnectAP"); // anonymous ap - res = wm.autoConnect("AutoConnectAP","password"); // password protected ap - - if(!res) { - Serial.println("Failed to connect or hit timeout"); - // ESP.restart(); - } - else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - } -} - -void checkButton(){ - // check for button press - if ( digitalRead(TRIGGER_PIN) == LOW ) { - // poor mans debounce/press-hold, code not ideal for production - delay(50); - if( digitalRead(TRIGGER_PIN) == LOW ){ - Serial.println("Button Pressed"); - // still holding button for 3000 ms, reset settings, code not ideaa for production - delay(3000); // reset delay hold - if( digitalRead(TRIGGER_PIN) == LOW ){ - Serial.println("Button Held"); - Serial.println("Erasing Config, restarting"); - wm.resetSettings(); - ESP.restart(); - } - - // start portal w delay - Serial.println("Starting config portal"); - wm.setConfigPortalTimeout(120); - - if (!wm.startConfigPortal("OnDemandAP","password")) { - Serial.println("failed to connect or hit timeout"); - delay(3000); - // ESP.restart(); - } else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - } - } - } -} - - -String getParam(String name){ - //read parameter from server, for customhmtl input - String value; - if(wm.server->hasArg(name)) { - value = wm.server->arg(name); - } - return value; -} - -void saveParamCallback(){ - Serial.println("[CALLBACK] saveParamCallback fired"); - Serial.println("PARAM customfieldid = " + getParam("customfieldid")); -} - -void loop() { - checkButton(); - // put your main code here, to run repeatedly: -} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino deleted file mode 100644 index fea3287a..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ /dev/null @@ -1,175 +0,0 @@ -#include // this needs to be first, or it all crashes and burns... -#include // https://github.com/tzapu/WiFiManager -#include // https://github.com/bblanchon/ArduinoJson - -#ifdef ESP32 - #include -#endif - -//define your default values here, if there are different values in config.json, they are overwritten. -char mqtt_server[40]; -char mqtt_port[6] = "8080"; -char api_token[32] = "YOUR_API_TOKEN"; - -//default custom static IP -char static_ip[16] = "10.0.1.56"; -char static_gw[16] = "10.0.1.1"; -char static_sn[16] = "255.255.255.0"; - -//flag for saving data -bool shouldSaveConfig = false; - -//callback notifying us of the need to save config -void saveConfigCallback () { - Serial.println("Should save config"); - shouldSaveConfig = true; -} - -void setupSpiffs(){ - //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); - DynamicJsonBuffer 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(api_token, json["api_token"]); - - // if(json["ip"]) { - // Serial.println("setting custom ip from config"); - // strcpy(static_ip, json["ip"]); - // strcpy(static_gw, json["gateway"]); - // strcpy(static_sn, json["subnet"]); - // Serial.println(static_ip); - // } else { - // Serial.println("no custom ip in config"); - // } - - } else { - Serial.println("failed to load json config"); - } - } - } - } else { - Serial.println("failed to mount FS"); - } - //end read -} - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println(); - - setupSpiffs(); - - // WiFiManager, Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wm; - - //set config save notify callback - wm.setSaveConfigCallback(saveConfigCallback); - - // setup custom parameters - // - // The extra parameters to be configured (can be either global or just in the setup) - // After connecting, parameter.getValue() will get you the configured value - // id/name placeholder/prompt default length - WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); - WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); - WiFiManagerParameter custom_api_token("api", "api token", "", 32); - - //add all your parameters here - wm.addParameter(&custom_mqtt_server); - wm.addParameter(&custom_mqtt_port); - wm.addParameter(&custom_api_token); - - // set static ip - // IPAddress _ip,_gw,_sn; - // _ip.fromString(static_ip); - // _gw.fromString(static_gw); - // _sn.fromString(static_sn); - // wm.setSTAStaticIPConfig(_ip, _gw, _sn); - - //reset settings - wipe credentials for testing - //wm.resetSettings(); - - //automatically connect using saved credentials if they exist - //If connection fails it starts an access point with the specified name - //here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous - //and goes into a blocking loop awaiting configuration - if (!wm.autoConnect("AutoConnectAP", "password")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - // if we still have not connected restart and try all over again - ESP.restart(); - delay(5000); - } - - // always start configportal for a little while - // wm.setConfigPortalTimeout(60); - // wm.startConfigPortal("AutoConnectAP","password"); - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - - //read updated parameters - strcpy(mqtt_server, custom_mqtt_server.getValue()); - strcpy(mqtt_port, custom_mqtt_port.getValue()); - strcpy(api_token, custom_api_token.getValue()); - - //save the custom parameters to FS - if (shouldSaveConfig) { - Serial.println("saving config"); - DynamicJsonBuffer jsonBuffer; - JsonObject& json = jsonBuffer.createObject(); - json["mqtt_server"] = mqtt_server; - json["mqtt_port"] = mqtt_port; - json["api_token"] = api_token; - - // json["ip"] = WiFi.localIP().toString(); - // json["gateway"] = WiFi.gatewayIP().toString(); - // json["subnet"] = WiFi.subnetMask().toString(); - - File configFile = SPIFFS.open("/config.json", "w"); - if (!configFile) { - Serial.println("failed to open config file for writing"); - } - - json.prettyPrintTo(Serial); - json.printTo(configFile); - configFile.close(); - //end save - shouldSaveConfig = false; - } - - Serial.println("local ip"); - Serial.println(WiFi.localIP()); - Serial.println(WiFi.gatewayIP()); - Serial.println(WiFi.subnetMask()); -} - -void loop() { - // put your main code here, to run repeatedly: - - -} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino b/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino deleted file mode 100644 index 6b1a7af7..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino +++ /dev/null @@ -1,172 +0,0 @@ -#include // this needs to be first, or it all crashes and burns... -#include // https://github.com/tzapu/WiFiManager -#include // https://github.com/bblanchon/ArduinoJson - -#ifdef ESP32 - #include -#endif - -//define your default values here, if there are different values in config.json, they are overwritten. -char mqtt_server[40]; -char mqtt_port[6] = "8080"; -char api_token[32] = "YOUR_API_TOKEN"; - -//default custom static IP -char static_ip[16] = "10.0.1.56"; -char static_gw[16] = "10.0.1.1"; -char static_sn[16] = "255.255.255.0"; - -//flag for saving data -bool shouldSaveConfig = false; - -//callback notifying us of the need to save config -void saveConfigCallback () { - Serial.println("Should save config"); - shouldSaveConfig = true; -} - -void setupSpiffs(){ - //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); - DynamicJsonBuffer 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(api_token, json["api_token"]); - - if(json["ip"]) { - Serial.println("setting custom ip from config"); - strcpy(static_ip, json["ip"]); - strcpy(static_gw, json["gateway"]); - strcpy(static_sn, json["subnet"]); - Serial.println(static_ip); - } else { - Serial.println("no custom ip in config"); - } - - } else { - Serial.println("failed to load json config"); - } - } - } - } else { - Serial.println("failed to mount FS"); - } - //end read -} - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println(); - - setupSpiffs(); - - // WiFiManager, Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wm; - - //set config save notify callback - wm.setSaveConfigCallback(saveConfigCallback); - - // setup custom parameters - // - // The extra parameters to be configured (can be either global or just in the setup) - // After connecting, parameter.getValue() will get you the configured value - // id/name placeholder/prompt default length - WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); - WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); - WiFiManagerParameter custom_api_token("api", "api token", "", 32); - - //add all your parameters here - wm.addParameter(&custom_mqtt_server); - wm.addParameter(&custom_mqtt_port); - wm.addParameter(&custom_api_token); - - // set static ip - IPAddress _ip,_gw,_sn; - _ip.fromString(static_ip); - _gw.fromString(static_gw); - _sn.fromString(static_sn); - wm.setSTAStaticIPConfig(_ip, _gw, _sn); - - //reset settings - wipe credentials for testing - //wm.resetSettings(); - - //automatically connect using saved credentials if they exist - //If connection fails it starts an access point with the specified name - //here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous - //and goes into a blocking loop awaiting configuration - if (!wm.autoConnect("AutoConnectAP", "password")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - // if we still have not connected restart and try all over again - ESP.restart(); - 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(api_token, custom_api_token.getValue()); - - //save the custom parameters to FS - if (shouldSaveConfig) { - Serial.println("saving config"); - DynamicJsonBuffer jsonBuffer; - JsonObject& json = jsonBuffer.createObject(); - json["mqtt_server"] = mqtt_server; - json["mqtt_port"] = mqtt_port; - json["api_token"] = api_token; - - json["ip"] = WiFi.localIP().toString(); - json["gateway"] = WiFi.gatewayIP().toString(); - json["subnet"] = WiFi.subnetMask().toString(); - - File configFile = SPIFFS.open("/config.json", "w"); - if (!configFile) { - Serial.println("failed to open config file for writing"); - } - - json.prettyPrintTo(Serial); - json.printTo(configFile); - configFile.close(); - //end save - shouldSaveConfig = false; - } - - Serial.println("local ip"); - Serial.println(WiFi.localIP()); - Serial.println(WiFi.gatewayIP()); - Serial.println(WiFi.subnetMask()); -} - -void loop() { - // put your main code here, to run repeatedly: - - -} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino b/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino deleted file mode 100644 index ba468435..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino +++ /dev/null @@ -1,71 +0,0 @@ -// LED will blink when in config mode - -#include // https://github.com/tzapu/WiFiManager - -//for LED status -#include -Ticker ticker; - -#ifndef LED_BUILTIN -#define LED_BUILTIN 13 // ESP32 DOES NOT DEFINE LED_BUILTIN -#endif - -int LED = LED_BUILTIN; - -void tick() -{ - //toggle state - digitalWrite(LED, !digitalRead(LED)); // 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() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once: - Serial.begin(115200); - - //set led pin as output - pinMode(LED, OUTPUT); - // start ticker with 0.5 because we start in AP mode and try to connect - ticker.attach(0.6, tick); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wm; - //reset settings - for testing - // wm.resetSettings(); - - //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode - wm.setAPCallback(configModeCallback); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - if (!wm.autoConnect()) { - Serial.println("failed to connect and hit timeout"); - //reset and try again, or maybe put it to deep sleep - ESP.restart(); - delay(1000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - ticker.detach(); - //keep LED on - digitalWrite(LED, LOW); -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/Basic/Basic.ino b/lib/WiFiManager-2.0.3-alpha/examples/Basic/Basic.ino deleted file mode 100644 index daaee37f..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/Basic/Basic.ino +++ /dev/null @@ -1,41 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - - // put your setup code here, to run once: - Serial.begin(115200); - - // WiFi.mode(WiFi_STA); // it is a good practice to make sure your code sets wifi mode how you want it. - - //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wm; - - //reset settings - wipe credentials for testing - //wm.resetSettings(); - - // Automatically connect using saved credentials, - // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"), - // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect()) - // then goes into a blocking loop awaiting configuration and will return success result - - bool res; - // res = wm.autoConnect(); // auto generated AP name from chipid - // res = wm.autoConnect("AutoConnectAP"); // anonymous ap - res = wm.autoConnect("AutoConnectAP","password"); // password protected ap - - if(!res) { - Serial.println("Failed to connect"); - // ESP.restart(); - } - else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - } - -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino b/lib/WiFiManager-2.0.3-alpha/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino deleted file mode 100644 index 28d14472..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ /dev/null @@ -1,347 +0,0 @@ -/** - * This is a kind of unit test for DEV for now - * It contains many of the public methods - * - */ -#include // https://github.com/tzapu/WiFiManager -#include -#include - -#define USEOTA -// enable OTA -#ifdef USEOTA -#include -#include -#endif - -const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; - -unsigned long mtime = 0; - - - -WiFiManager wm; - -// TEST OPTION FLAGS -bool TEST_CP = true; // always start the configportal, even if ap found -int TESP_CP_TIMEOUT = 90; // test cp timeout - -bool TEST_NET = true; // do a network test after connect, (gets ntp time) -bool ALLOWONDEMAND = true; // enable on demand -int ONDDEMANDPIN = 0; // gpio for button - - -// char ssid[] = "*************"; // your network SSID (name) -// char pass[] = "********"; // your network password - -// OLED TEST , ssd1306 -// #define WM_OLED -#ifdef WM_OLED -#include -#include -#include -#define SCREEN_WIDTH 128 // OLED display width, in pixels -#define SCREEN_HEIGHT 32 // OLED display height, in pixels - -// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) -#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) -Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); -#endif - -void saveWifiCallback(){ - Serial.println("[CALLBACK] saveCallback fired"); -} - -//gets called when WiFiManager enters configuration mode -void configModeCallback (WiFiManager *myWiFiManager) { - Serial.println("[CALLBACK] configModeCallback fired"); - #ifdef ESP8266 - print_oled("WiFiManager Waiting\nIP: " + WiFi.softAPIP().toString() + "\nSSID: " + WiFi.softAPSSID(),1); - #endif - // myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - // Serial.println(WiFi.softAPIP()); - //if you used auto generated SSID, print it - // Serial.println(myWiFiManager->getConfigPortalSSID()); -} - -void saveParamCallback(){ - Serial.println("[CALLBACK] saveParamCallback fired"); - // wm.stopConfigPortal(); -} - -void bindServerCallback(){ - wm.server->on("/custom",handleRoute); - // wm.server->on("/info",handleRoute); // you can override wm! -} - -void handleRoute(){ - Serial.println("[HTTP] handle route"); - wm.server->send(200, "text/plain", "hello from user code"); -} - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - - // put your setup code here, to run once: - Serial.begin(115200); - // Serial1.begin(115200); - - // Serial.setDebugOutput(true); - delay(1000); - - Serial.println("\n Starting"); - // WiFi.setSleepMode(WIFI_NONE_SLEEP); // disable sleep, can improve ap stability - - #ifdef WM_OLED - init_oled(); - #endif - - print_oled(F("Starting..."),2); - wm.debugPlatformInfo(); - - //reset settings - for testing - // wm.resetSettings(); - // wm.erase(); - - // invert theme, dark - wm.setClass("invert"); - - // setup some parameters - WiFiManagerParameter custom_html("

This Is Custom HTML

"); // only custom html - WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); - WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); - WiFiManagerParameter custom_token("api_token", "api token", "", 16); - WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces - WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // custom input attrs (ip mask) - - const char _customHtml_checkbox[] = "type=\"checkbox\""; - WiFiManagerParameter custom_checkbox("checkbox", "my checkbox", "T", 2, _customHtml_checkbox, WFM_LABEL_AFTER); - - // callbacks - wm.setAPCallback(configModeCallback); - wm.setWebServerCallback(bindServerCallback); - wm.setSaveConfigCallback(saveWifiCallback); - wm.setSaveParamsCallback(saveParamCallback); - - // add all your parameters here - wm.addParameter(&custom_html); - wm.addParameter(&custom_mqtt_server); - wm.addParameter(&custom_mqtt_port); - wm.addParameter(&custom_token); - wm.addParameter(&custom_tokenb); - wm.addParameter(&custom_ipaddress); - wm.addParameter(&custom_checkbox); - - // set values later if you want - custom_html.setValue("test",4); - custom_token.setValue("test",4); - -/* - Set cutom menu via menu[] or vector - const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - wm.setMenu(menu,9); // custom menu array must provide length -*/ - - std::vector menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; - // wm.setMenu(menu); // custom menu, pass vector - - // wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu! - - // set STA static ip - // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - // wm.setShowStaticFields(false); - // wm.setShowDnsFields(false); - - // set AP static ip - // wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - // wm.setAPStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - - // set country - // setting wifi country seems to improve OSX soft ap connectivity, - // may help others as well, default is CN which has different channels - wm.setCountry("US"); - - // set Hostname - wm.setHostname("WIFIMANAGERTESTING"); - - // set custom channel - // wm.setWiFiAPChannel(13); - - // set AP hidden - // wm.setAPHidden(true); - - // show password publicly in form - // wm.setShowPassword(true); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep in seconds - wm.setConfigPortalTimeout(120); - - // set connection timeout - // wm.setConnectTimeout(20); - - // show static ip fields - // wm.setShowStaticFields(true); - - // wm.startConfigPortal("AutoConnectAP", "password"); - - // This is sometimes necessary, it is still unknown when and why this is needed but it may solve some race condition or bug in esp SDK/lib - // wm.setCleanConnect(true); // disconnect before connect, clean connect - - // - wm.setBreakAfterConfig(true); - - // set custom webserver port, automatic captive portal does not work with custom ports! - // wm.setHttpPort(8080); - - //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 - - wifiInfo(); - - print_oled(F("Connecting..."),2); - if(!wm.autoConnect("WM_AutoConnectAP","12345678")) { - Serial.println("failed to connect and hit timeout"); - print_oled("Not Connected",2); - } - else if(TEST_CP) { - // start configportal always - delay(1000); - Serial.println("TEST_CP ENABLED"); - wm.setConfigPortalTimeout(TESP_CP_TIMEOUT); - wm.startConfigPortal("WM_ConnectAP"); - } - else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - print_oled("Connected\nIP: " + WiFi.localIP().toString() + "\nSSID: " + WiFi.SSID(),1); - } - - wifiInfo(); - pinMode(ONDDEMANDPIN, INPUT_PULLUP); - - #ifdef USEOTA - ArduinoOTA.begin(); - #endif -} - -void wifiInfo(){ - WiFi.printDiag(Serial); - Serial.println("SAVED: " + (String)wm.getWiFiIsSaved() ? "YES" : "NO"); - Serial.println("SSID: " + (String)wm.getWiFiSSID()); - Serial.println("PASS: " + (String)wm.getWiFiPass()); -} - -void loop() { - - #ifdef USEOTA - ArduinoOTA.handle(); - #endif - // is configuration portal requested? - if (ALLOWONDEMAND && digitalRead(ONDDEMANDPIN) == LOW ) { - delay(100); - if ( digitalRead(ONDDEMANDPIN) == LOW ){ - Serial.println("BUTTON PRESSED"); - wm.setConfigPortalTimeout(140); - wm.setParamsPage(false); // move params to seperate page, not wifi, do not combine with setmenu! - - // disable captive portal redirection - // wm.setCaptivePortalEnable(false); - - if (!wm.startConfigPortal("OnDemandAP","12345678")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - } - } - else { - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - print_oled("Connected\nIP: " + WiFi.localIP().toString() + "\nSSID: " + WiFi.SSID(),1); - getTime(); - } - } - - if(WiFi.status() == WL_CONNECTED && millis()-mtime > 10000 ){ - getTime(); - mtime = millis(); - } - // put your main code here, to run repeatedly: - delay(100); -} - -void getTime() { - int tz = -5; - int dst = 0; - time_t now = time(nullptr); - unsigned timeout = 5000; - unsigned start = millis(); - configTime(tz * 3600, dst * 3600, "pool.ntp.org", "time.nist.gov"); - Serial.print("Waiting for NTP time sync: "); - while (now < 8 * 3600 * 2 ) { - delay(100); - Serial.print("."); - now = time(nullptr); - if((millis() - start) > timeout){ - Serial.println("\n[ERROR] Failed to get NTP time."); - return; - } - } - Serial.println(""); - struct tm timeinfo; - gmtime_r(&now, &timeinfo); - Serial.print("Current time: "); - Serial.print(asctime(&timeinfo)); -} - -void debugchipid(){ - // WiFi.mode(WIFI_STA); - // WiFi.printDiag(Serial); - // Serial.println(modes[WiFi.getMode()]); - - // ESP.eraseConfig(); - // wm.resetSettings(); - // wm.erase(true); - WiFi.mode(WIFI_AP); - // WiFi.softAP(); - WiFi.enableAP(true); - delay(500); - // esp_wifi_start(); - delay(1000); - WiFi.printDiag(Serial); - delay(60000); - ESP.restart(); - - // AP esp_267751 - // 507726A4AE30 - // ESP32 Chip ID = 507726A4AE30 -} - -#ifdef WM_OLED -void init_oled(){ - if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 - Serial.println(F("SSD1306 allocation failed")); - } - - display.clearDisplay(); - display.setTextSize(1); // Normal 1:1 pixepl scale - display.setTextColor(WHITE); // Draw white text - display.setCursor(0,0); // Start at top-left corner - display.display(); -} - -void print_oled(String str,uint8_t size){ - display.clearDisplay(); - display.setTextSize(size); - display.setTextColor(WHITE); - display.setCursor(0,0); - display.println(str); - display.display(); -} -#else - void print_oled(String str,uint8_t size){ - (void)str; - (void)size; - } -#endif diff --git a/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino b/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino deleted file mode 100644 index fa04d917..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino +++ /dev/null @@ -1,27 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager -WiFiManager wm; - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once: - Serial.begin(115200); - - //reset settings - wipe credentials for testing - //wm.resetSettings(); - - wm.setConfigPortalBlocking(false); - - //automatically connect using saved credentials if they exist - //If connection fails it starts an access point with the specified name - if(wm.autoConnect("AutoConnectAP")){ - Serial.println("connected...yeey :)"); - } - else { - Serial.println("Configportal running"); - } -} - -void loop() { - wm.process(); - // put your main code here, to run repeatedly: -} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino b/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino deleted file mode 100644 index 3af79f01..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino +++ /dev/null @@ -1,36 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager -WiFiManager wm; -WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once: - Serial.begin(115200); - - //reset settings - wipe credentials for testing - //wm.resetSettings(); - wm.addParameter(&custom_mqtt_server); - wm.setConfigPortalBlocking(false); - wm.setSaveParamsCallback(saveParamsCallback); - - //automatically connect using saved credentials if they exist - //If connection fails it starts an access point with the specified name - if(wm.autoConnect("AutoConnectAP")){ - Serial.println("connected...yeey :)"); - } - else { - Serial.println("Configportal running"); - } -} - -void loop() { - wm.process(); - // put your main code here, to run repeatedly: -} - -void saveParamsCallback () { - Serial.println("Get Params:"); - Serial.print(custom_mqtt_server.getID()); - Serial.print(" : "); - Serial.println(custom_mqtt_server.getValue()); -} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino b/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino deleted file mode 100644 index 3813356e..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino +++ /dev/null @@ -1,83 +0,0 @@ -/** - * OnDemandNonBlocking.ino - * example of running the webportal or configportal manually and non blocking - * trigger pin will start a webportal for 120 seconds then turn it off. - * startCP = true will start both the configportal AP and webportal - */ -#include // https://github.com/tzapu/WiFiManager - -// include MDNS -#ifdef ESP8266 -#include -#elif defined(ESP32) -#include -#endif - -// select which pin will trigger the configuration portal when set to LOW -#define TRIGGER_PIN 0 - -WiFiManager wm; - -unsigned int timeout = 120; // seconds to run for -unsigned int startTime = millis(); -bool portalRunning = false; -bool startAP = false; // start AP and webserver if true, else start only webserver - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once - Serial.begin(115200); - Serial.setDebugOutput(true); - delay(1000); - Serial.println("\n Starting"); - - pinMode(TRIGGER_PIN, INPUT_PULLUP); - - // wm.resetSettings(); - wm.setHostname("MDNSEXAMPLE"); - // wm.setEnableConfigPortal(false); - // wm.setConfigPortalBlocking(false); - wm.autoConnect(); -} - -void loop() { - #ifdef ESP8266 - MDNS.update(); - #endif - doWiFiManager(); - // put your main code here, to run repeatedly: -} - -void doWiFiManager(){ - // is auto timeout portal running - if(portalRunning){ - wm.process(); - if((millis()-startTime) > (timeout*1000)){ - Serial.println("portaltimeout"); - portalRunning = false; - if(startAP){ - wm.stopConfigPortal(); - } - else{ - wm.stopWebPortal(); - } - } - } - - // is configuration portal requested? - if(digitalRead(TRIGGER_PIN) == LOW && (!portalRunning)) { - if(startAP){ - Serial.println("Button Pressed, Starting Config Portal"); - wm.setConfigPortalBlocking(false); - wm.startConfigPortal(); - } - else{ - Serial.println("Button Pressed, Starting Web Portal"); - wm.startWebPortal(); - } - portalRunning = true; - startTime = millis(); - } -} - - diff --git a/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino deleted file mode 100644 index d3c4ed8b..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino +++ /dev/null @@ -1,42 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - -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()); -} - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - //reset 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.restart(); - delay(1000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino deleted file mode 100644 index 53a0d138..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino +++ /dev/null @@ -1,43 +0,0 @@ -#include // this needs to be first, or it all crashes and burns... -#include // https://github.com/tzapu/WiFiManager - -void setup() { - // put your setup code here, to run once: - 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.restart(); - 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/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino deleted file mode 100644 index 9f88e470..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino +++ /dev/null @@ -1,71 +0,0 @@ -#include // this needs to be first, or it all crashes and burns... -#include // https://github.com/tzapu/WiFiManager - -/************************************************************************************** - * this example shows how to set a static IP configuration for the ESP - * 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 - //block1 should be used for ESP8266 core 2.1.0 or newer, otherwise use block2 - - //start-block1 - //IPAddress _ip,_gw,_sn; - //_ip.fromString(static_ip); - //_gw.fromString(static_gw); - //_sn.fromString(static_sn); - //end-block1 - - //start-block2 - IPAddress _ip = IPAddress(10, 0, 1, 78); - IPAddress _gw = IPAddress(10, 0, 1, 1); - IPAddress _sn = IPAddress(255, 255, 255, 0); - //end-block2 - - 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.restart(); - 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/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino b/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino deleted file mode 100644 index 9df428d4..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino +++ /dev/null @@ -1,38 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - //reset settings - for testing - //wifiManager.resetSettings(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - wifiManager.setConfigPortalTimeout(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.restart(); - 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: - -} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino b/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino deleted file mode 100644 index a352b389..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ /dev/null @@ -1,47 +0,0 @@ -/** - * OnDemandConfigPortal.ino - * example of running the configPortal AP manually, independantly from the captiveportal - * trigger pin will start a configPortal AP for 120 seconds then turn it off. - * - */ -#include // https://github.com/tzapu/WiFiManager - -// select which pin will trigger the configuration portal when set to LOW -#define TRIGGER_PIN 0 - -int timeout = 120; // seconds to run for - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println("\n Starting"); - pinMode(TRIGGER_PIN, INPUT_PULLUP); -} - -void loop() { - // is configuration portal requested? - if ( digitalRead(TRIGGER_PIN) == LOW) { - WiFiManager wm; - - //reset settings - for testing - //wifiManager.resetSettings(); - - // set configportal timeout - wm.setConfigPortalTimeout(timeout); - - if (!wm.startConfigPortal("OnDemandAP")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - //reset and try again, or maybe put it to deep sleep - ESP.restart(); - delay(5000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - - } - - // put your main code here, to run repeatedly: -} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino b/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino deleted file mode 100644 index 7b6676a0..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino +++ /dev/null @@ -1,51 +0,0 @@ -/** - * OnDemandWebPortal.ino - * example of running the webportal (always NON blocking) - */ -#include // https://github.com/tzapu/WiFiManager - -// select which pin will trigger the configuration portal when set to LOW -#define TRIGGER_PIN 0 - -WiFiManager wm; - -bool portalRunning = false; - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - // put your setup code here, to run once - Serial.begin(115200); - Serial.println("\n Starting"); - pinMode(TRIGGER_PIN, INPUT_PULLUP); -} - -void loop() { - checkButton(); - // put your main code here, to run repeatedly: -} - -void checkButton(){ - // is auto timeout portal running - if(portalRunning){ - wm.process(); - } - - // is configuration portal requested? - if(digitalRead(TRIGGER_PIN) == LOW) { - delay(50); - if(digitalRead(TRIGGER_PIN) == LOW) { - if(!portalRunning){ - Serial.println("Button Pressed, Starting Portal"); - wm.startWebPortal(); - portalRunning = true; - } - else{ - Serial.println("Button Pressed, Stopping Portal"); - wm.startWebPortal(); - portalRunning = false; - } - } - } -} - - diff --git a/lib/WiFiManager-2.0.3-alpha/examples/ParamsChildClass/ParamsChildClass.ino b/lib/WiFiManager-2.0.3-alpha/examples/ParamsChildClass/ParamsChildClass.ino deleted file mode 100644 index 0117d773..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/ParamsChildClass/ParamsChildClass.ino +++ /dev/null @@ -1,141 +0,0 @@ -/** - * WiFiManagerParameter child class example - */ -#include // https://github.com/tzapu/WiFiManager -#include -#include - -#define SETUP_PIN 0 - -class IPAddressParameter : public WiFiManagerParameter { -public: - IPAddressParameter(const char *id, const char *placeholder, IPAddress address) - : WiFiManagerParameter("") { - init(id, placeholder, address.toString().c_str(), 16, "", WFM_LABEL_BEFORE); - } - - bool getValue(IPAddress &ip) { - return ip.fromString(WiFiManagerParameter::getValue()); - } -}; - -class IntParameter : public WiFiManagerParameter { -public: - IntParameter(const char *id, const char *placeholder, long value, const uint8_t length = 10) - : WiFiManagerParameter("") { - init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); - } - - long getValue() { - return String(WiFiManagerParameter::getValue()).toInt(); - } -}; - -class FloatParameter : public WiFiManagerParameter { -public: - FloatParameter(const char *id, const char *placeholder, float value, const uint8_t length = 10) - : WiFiManagerParameter("") { - init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); - } - - float getValue() { - return String(WiFiManagerParameter::getValue()).toFloat(); - } -}; - -struct Settings { - float f; - int i; - char s[20]; - uint32_t ip; -} sett; - - -void setup() { - WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP - pinMode(SETUP_PIN, INPUT_PULLUP); - Serial.begin(115200); - - //Delay to push SETUP button - Serial.println("Press setup button"); - for (int sec = 3; sec > 0; sec--) { - Serial.print(sec); - Serial.print(".."); - delay(1000); - } - - EEPROM.begin( 512 ); - EEPROM.get(0, sett); - Serial.println("Settings loaded"); - - if (digitalRead(SETUP_PIN) == LOW) { - // Button pressed - Serial.println("SETUP"); - - WiFiManager wm; - - sett.s[19] = '\0'; //add null terminator at the end cause overflow - WiFiManagerParameter param_str( "str", "param_string", sett.s, 20); - FloatParameter param_float( "float", "param_float", sett.f); - IntParameter param_int( "int", "param_int", sett.i); - - IPAddress ip(sett.ip); - IPAddressParameter param_ip("ip", "param_ip", ip); - - wm.addParameter( ¶m_str ); - wm.addParameter( ¶m_float ); - wm.addParameter( ¶m_int ); - wm.addParameter( ¶m_ip ); - - //SSID & password parameters already included - wm.startConfigPortal(); - - strncpy(sett.s, param_str.getValue(), 20); - sett.s[19] = '\0'; - sett.f = param_float.getValue(); - sett.i = param_int.getValue(); - - Serial.print("String param: "); - Serial.println(sett.s); - Serial.print("Float param: "); - Serial.println(sett.f); - Serial.print("Int param: "); - Serial.println(sett.i, DEC); - - if (param_ip.getValue(ip)) { - sett.ip = ip; - - Serial.print("IP param: "); - Serial.println(ip); - } else { - Serial.println("Incorrect IP"); - } - - EEPROM.put(0, sett); - if (EEPROM.commit()) { - Serial.println("Settings saved"); - } else { - Serial.println("EEPROM error"); - } - } - else { - Serial.println("WORK"); - - //connect to saved SSID - WiFi.begin(); - - //do smth - Serial.print("String param: "); - Serial.println(sett.s); - Serial.print("Float param: "); - Serial.println(sett.f); - Serial.print("Int param: "); - Serial.println(sett.i, DEC); - Serial.print("IP param: "); - IPAddress ip(sett.ip); - Serial.println(ip); - } -} - -void loop() { -} diff --git a/lib/WiFiManager-2.0.3-alpha/examples/Tests/AnonymousCB.ino b/lib/WiFiManager-2.0.3-alpha/examples/Tests/AnonymousCB.ino deleted file mode 100644 index f34d80f7..00000000 --- a/lib/WiFiManager-2.0.3-alpha/examples/Tests/AnonymousCB.ino +++ /dev/null @@ -1,26 +0,0 @@ -#include // https://github.com/tzapu/WiFiManager - -bool _enteredConfigMode = false; - -void setup(){ - Serial.begin(115200); - WiFiManager wifiManager; - - // wifiManager.setAPCallback([this](WiFiManager* wifiManager) { - wifiManager.setAPCallback([&](WiFiManager* wifiManager) { - Serial.printf("Entered config mode:ip=%s, ssid='%s'\n", - WiFi.softAPIP().toString().c_str(), - wifiManager->getConfigPortalSSID().c_str()); - _enteredConfigMode = true; - }); - wifiManager.resetSettings(); - if (!wifiManager.autoConnect()) { - Serial.printf("*** Failed to connect and hit timeout\n"); - ESP.restart(); - delay(1000); - } -} - -void loop(){ - -} diff --git a/lib/WiFiManager-2.0.3-alpha/extras/WiFiManager.template.html b/lib/WiFiManager-2.0.3-alpha/extras/WiFiManager.template.html deleted file mode 100644 index d2c2c398..00000000 --- a/lib/WiFiManager-2.0.3-alpha/extras/WiFiManager.template.html +++ /dev/null @@ -1,324 +0,0 @@ - - - - - - {v} - - - - - - - - - - -
- - - -

/


- - - - -

-

-

-

-

-

-

-

-

-

- - -

/wifi


- - - - - - - - - - - - - - - - - - - - -



- - -

custom parameter


-
-
- - -
- - -
- - -
- - -
- - -

Saving Credentials

Trying to connect ESP to network.
If it fails reconnect to AP to try again
- - -
Connected to {v}
with IP {i}
- - -
Not Connected to {v}{r}
- - -
Not Connected to apname - - -
Authentication Failure - - -
AP not found - - -
Could not Connect - -
- -
No AP set
- - -

H4 Color Header P

content
- - -

H4 Color Header S

content
- - -

/info


-
-
Chip ID
123456
-
Flash Chip ID
1234556
-
IDE Flash Size
4194304 bytes
-
Real Flash Size
4194304 bytes
-
Empty
-
Soft AP IP
192.168.4.1
-
Soft AP MAC
00:00:00:00:00:00
-
Station MAC
00:00:00:00:00:00
-
- - -

Available Pages


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

More information about WiFiManager at https://github.com/tzapu/WiFiManager - - -

Form UPLOAD

- - - -
- - - diff --git a/lib/WiFiManager-2.0.3-alpha/extras/parse.js b/lib/WiFiManager-2.0.3-alpha/extras/parse.js deleted file mode 100644 index 97a3e384..00000000 --- a/lib/WiFiManager-2.0.3-alpha/extras/parse.js +++ /dev/null @@ -1,60 +0,0 @@ -'use strict'; - -const fs = require('fs'); - -console.log('starting'); - -const inFile = 'WiFiManager.template.html'; -const outFile = 'template.h'; - -const defineRegEx = //gm; -console.log('parsing', inFile); - -fs.readFile(inFile, 'utf8', function (err,data) { - if (err) { - return console.log(err); - } - //console.log(data); - - let defines = data.match(defineRegEx); - - //console.log(defines); - var stream = fs.createWriteStream(outFile); - stream.once('open', function(fd) { - for (const i in defines) { - - const start = defines[i]; - const end = start.replace(' - - - - diff --git a/lib/WiFiManager-2.0.3-alpha/keywords.txt b/lib/WiFiManager-2.0.3-alpha/keywords.txt deleted file mode 100644 index 7159e740..00000000 --- a/lib/WiFiManager-2.0.3-alpha/keywords.txt +++ /dev/null @@ -1,39 +0,0 @@ -####################################### -# Syntax Coloring Map For WifiManager -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -WiFiManager KEYWORD1 -WiFiManagerParameter KEYWORD1 - - -####################################### -# Methods and Functions (KEYWORD2) -####################################### -autoConnect KEYWORD2 -getSSID KEYWORD2 -getPassword KEYWORD2 -getConfigPortalSSID KEYWORD2 -resetSettings KEYWORD2 -setConfigPortalTimeout KEYWORD2 -setConnectTimeout KEYWORD2 -setDebugOutput KEYWORD2 -setMinimumSignalQuality KEYWORD2 -setAPStaticIPConfig KEYWORD2 -setSTAStaticIPConfig KEYWORD2 -setAPCallback KEYWORD2 -setSaveConfigCallback KEYWORD2 -addParameter KEYWORD2 -getID KEYWORD2 -getValue KEYWORD2 -getPlaceholder KEYWORD2 -getValueLength KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - -# LITERAL1 diff --git a/lib/WiFiManager-2.0.3-alpha/library.json b/lib/WiFiManager-2.0.3-alpha/library.json deleted file mode 100644 index 96c4164d..00000000 --- a/lib/WiFiManager-2.0.3-alpha/library.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "WifiManager", - "keywords": "wifi,wi-fi,esp,esp8266,esp32,espressif8266,espressif32,nodemcu,wemos,arduino", - "description": "WiFi Configuration manager with web configuration portal for ESP boards", -"authors": -[ - { - "name": "tzapu", - "url": "https://github.com/tzapu" - }, - { - "name": "tablatronix", - "url": "https://github.com/tablatronix", - "maintainer": true - } -], -"repository": - { - "type": "git", - "url": "https://github.com/tzapu/WiFiManager.git" - }, - "frameworks": "arduino", - "platforms": - [ - "espressif8266", - "espressif32" - ], - "version": "2.0.3-alpha" -} diff --git a/lib/WiFiManager-2.0.3-alpha/library.properties b/lib/WiFiManager-2.0.3-alpha/library.properties deleted file mode 100644 index 9ac084b7..00000000 --- a/lib/WiFiManager-2.0.3-alpha/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=WiFiManager -version=2.0.3-alpha -author=tzapu,tablatronix -maintainer=tablatronix -sentence=WiFi Configuration manager with web configuration portal for ESP boards -paragraph=Library for configuring ESP8266/ESP32 modules WiFi credentials and custom parameters at runtime. -category=Communication -url=https://github.com/tzapu/WiFiManager.git -architectures=esp8266,esp32 diff --git a/lib/WiFiManager-2.0.3-alpha/strings_en.h b/lib/WiFiManager-2.0.3-alpha/strings_en.h deleted file mode 100644 index d56d0b12..00000000 --- a/lib/WiFiManager-2.0.3-alpha/strings_en.h +++ /dev/null @@ -1,363 +0,0 @@ -/** - * strings_en.h - * engligh strings for - * WiFiManager, a library for the ESP8266/Arduino platform - * for configuration of WiFi credentials using a Captive Portal - * - * @author Creator tzapu - * @author tablatronix - * @version 0.0.0 - * @license MIT - */ - -#ifndef _WM_STRINGS_H_ -#define _WM_STRINGS_H_ - -#ifndef WIFI_MANAGER_OVERRIDE_STRINGS -// !!! THIS DOES NOT WORK, you cannot define in a sketch, if anyone one knows how to order includes to be able to do this help! - -const char HTTP_HEAD_START[] PROGMEM = "{v}"; -const char HTTP_SCRIPT[] PROGMEM = ""; - -const char HTTP_HEAD_END[] PROGMEM = "
"; -// example of embedded logo, base64 encoded inline, No styling here -// const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

"; -const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

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

\n", // MENU_WIFI -"

\n", // MENU_WIFINOSCAN -"

\n", // MENU_INFO -"

\n",//MENU_PARAM -"

\n", // MENU_CLOSE -"

\n",// MENU_RESTART -"

\n", // MENU_EXIT -"

\n", // MENU_ERASE -"

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

"; -const char HTTP_FORM_END[] PROGMEM = "

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

"; -const char HTTP_FORM_PARAM[] PROGMEM = "
"; - -const char HTTP_SCAN_LINK[] PROGMEM = "
"; -const char HTTP_SAVED[] PROGMEM = "
Saving Credentials
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; -const char HTTP_PARAMSAVED[] PROGMEM = "
Saved
"; -const char HTTP_END[] PROGMEM = "
"; -const char HTTP_ERASEBTN[] PROGMEM = "
"; -const char HTTP_BACKBTN[] PROGMEM = "

"; - -const char HTTP_STATUS_ON[] PROGMEM = "
Connected to {v}
with IP {i}
"; -const char HTTP_STATUS_OFF[] PROGMEM = "
Not Connected to {v}{r}
"; -const char HTTP_STATUS_OFFPW[] PROGMEM = "
Authentication Failure"; // STATION_WRONG_PASSWORD, no eps32 -const char HTTP_STATUS_OFFNOAP[] PROGMEM = "
AP not found"; // WL_NO_SSID_AVAIL -const char HTTP_STATUS_OFFFAIL[] PROGMEM = "
Could not Connect"; // WL_CONNECT_FAILED -const char HTTP_STATUS_NONE[] PROGMEM = "
No AP set
"; -const char HTTP_BR[] PROGMEM = "
"; - -const char HTTP_STYLE[] PROGMEM = ""; - -const char HTTP_HELP[] PROGMEM = - "

Available Pages


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

More information about WiFiManager at https://github.com/tzapu/WiFiManager."; - -#ifdef WM_JSTEST -const char HTTP_JS[] PROGMEM = -""; -#endif - -// Info html -#ifdef ESP32 - const char HTTP_INFO_esphead[] PROGMEM = "

esp32


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

esp8266


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

WiFi


"; -const char HTTP_INFO_uptime[] PROGMEM = "
Uptime
{1} Mins {2} Secs
"; -const char HTTP_INFO_chipid[] PROGMEM = "
Chip ID
{1}
"; -const char HTTP_INFO_idesize[] PROGMEM = "
Flash Size
{1} bytes
"; -const char HTTP_INFO_sdkver[] PROGMEM = "
SDK Version
{1}
"; -const char HTTP_INFO_cpufreq[] PROGMEM = "
CPU Frequency
{1}MHz
"; -const char HTTP_INFO_apip[] PROGMEM = "
Access Point IP
{1}
"; -const char HTTP_INFO_apmac[] PROGMEM = "
Access Point MAC
{1}
"; -const char HTTP_INFO_apssid[] PROGMEM = "
SSID
{1}
"; -const char HTTP_INFO_apbssid[] PROGMEM = "
BSSID
{1}
"; -const char HTTP_INFO_staip[] PROGMEM = "
Station IP
{1}
"; -const char HTTP_INFO_stagw[] PROGMEM = "
Station Gateway
{1}
"; -const char HTTP_INFO_stasub[] PROGMEM = "
Station Subnet
{1}
"; -const char HTTP_INFO_dnss[] PROGMEM = "
DNS Server
{1}
"; -const char HTTP_INFO_host[] PROGMEM = "
Hostname
{1}
"; -const char HTTP_INFO_stamac[] PROGMEM = "
Station MAC
{1}
"; -const char HTTP_INFO_conx[] PROGMEM = "
Connected
{1}
"; -const char HTTP_INFO_autoconx[] PROGMEM = "
Autoconnect
{1}
"; -const char HTTP_INFO_temp[] PROGMEM = "
Temperature
{1} C° / {2} F°
"; - -// Strings -const char S_y[] PROGMEM = "Yes"; -const char S_n[] PROGMEM = "No"; -const char S_enable[] PROGMEM = "Enabled"; -const char S_disable[] PROGMEM = "Disabled"; -const char S_GET[] PROGMEM = "GET"; -const char S_POST[] PROGMEM = "POST"; -const char S_NA[] PROGMEM = "Unknown"; -const char S_passph[] PROGMEM = "********"; -const char S_titlewifisaved[] PROGMEM = "Credentials Saved"; -const char S_titlewifisettings[] PROGMEM = "Settings Saved"; -const char S_titlewifi[] PROGMEM = "Config ESP"; -const char S_titleinfo[] PROGMEM = "Info"; -const char S_titleparam[] PROGMEM = "Setup"; -const char S_titleparamsaved[] PROGMEM = "Setup Saved"; -const char S_titleexit[] PROGMEM = "Exit"; -const char S_titlereset[] PROGMEM = "Reset"; -const char S_titleerase[] PROGMEM = "Erase"; -const char S_titleclose[] PROGMEM = "Close"; -const char S_options[] PROGMEM = "options"; -const char S_nonetworks[] PROGMEM = "No networks found. Refresh to scan again."; -const char S_staticip[] PROGMEM = "Static IP"; -const char S_staticgw[] PROGMEM = "Static Gateway"; -const char S_staticdns[] PROGMEM = "Static DNS"; -const char S_subnet[] PROGMEM = "Subnet"; -const char S_exiting[] PROGMEM = "Exiting"; -const char S_resetting[] PROGMEM = "Module will reset in a few seconds."; -const char S_closing[] PROGMEM = "You can close the page, portal will continue to run"; -const char S_error[] PROGMEM = "An Error Occured"; -const char S_notfound[] PROGMEM = "File Not Found\n\n"; -const char S_uri[] PROGMEM = "URI: "; -const char S_method[] PROGMEM = "\nMethod: "; -const char S_args[] PROGMEM = "\nArguments: "; -const char S_parampre[] PROGMEM = "param_"; - -// debug strings -const char D_HR[] PROGMEM = "--------------------"; - -// END WIFI_MANAGER_OVERRIDE_STRINGS -#endif - -// ----------------------------------------------------------------------------------------------- -// DO NOT EDIT BELOW THIS LINE - -const uint8_t _nummenutokens = 9; -const char * const _menutokens[9] PROGMEM = { - "wifi", - "wifinoscan", - "info", - "param", - "close", - "restart", - "exit", - "erase", - "sep" -}; - -const char R_root[] PROGMEM = "/"; -const char R_wifi[] PROGMEM = "/wifi"; -const char R_wifinoscan[] PROGMEM = "/0wifi"; -const char R_wifisave[] PROGMEM = "/wifisave"; -const char R_info[] PROGMEM = "/info"; -const char R_param[] PROGMEM = "/param"; -const char R_paramsave[] PROGMEM = "/paramsave"; -const char R_restart[] PROGMEM = "/restart"; -const char R_exit[] PROGMEM = "/exit"; -const char R_close[] PROGMEM = "/close"; -const char R_erase[] PROGMEM = "/erase"; -const char R_status[] PROGMEM = "/status"; - - -//Strings -const char S_ip[] PROGMEM = "ip"; -const char S_gw[] PROGMEM = "gw"; -const char S_sn[] PROGMEM = "sn"; -const char S_dns[] PROGMEM = "dns"; - -// softap ssid default prefix -#ifdef ESP8266 - const char S_ssidpre[] PROGMEM = "ESP"; -#elif defined(ESP32) - const char S_ssidpre[] PROGMEM = "ESP32"; -#else - const char S_ssidpre[] PROGMEM = "WM"; -#endif - -//Tokens -//@todo consolidate and reduce -const char T_ss[] PROGMEM = "{"; // token start sentinel -const char T_es[] PROGMEM = "}"; // token end sentinel -const char T_1[] PROGMEM = "{1}"; // @token 1 -const char T_2[] PROGMEM = "{2}"; // @token 2 -const char T_v[] PROGMEM = "{v}"; // @token v -const char T_I[] PROGMEM = "{I}"; // @token I -const char T_i[] PROGMEM = "{i}"; // @token i -const char T_n[] PROGMEM = "{n}"; // @token n -const char T_p[] PROGMEM = "{p}"; // @token p -const char T_t[] PROGMEM = "{t}"; // @token t -const char T_l[] PROGMEM = "{l}"; // @token l -const char T_c[] PROGMEM = "{c}"; // @token c -const char T_e[] PROGMEM = "{e}"; // @token e -const char T_q[] PROGMEM = "{q}"; // @token q -const char T_r[] PROGMEM = "{r}"; // @token r -const char T_R[] PROGMEM = "{R}"; // @token R -const char T_h[] PROGMEM = "{h}"; // @token h - -// http -const char HTTP_HEAD_CL[] PROGMEM = "Content-Length"; -const char HTTP_HEAD_CT[] PROGMEM = "text/html"; -const char HTTP_HEAD_CT2[] PROGMEM = "text/plain"; -const char HTTP_HEAD_CORS[] PROGMEM = "Access-Control-Allow-Origin"; -const char HTTP_HEAD_CORS_ALLOW_ALL[] PROGMEM = "*"; - -const char * const WIFI_STA_STATUS[] PROGMEM -{ - "WL_IDLE_STATUS", // 0 STATION_IDLE - "WL_NO_SSID_AVAIL", // 1 STATION_NO_AP_FOUND - "WL_SCAN_COMPLETED", // 2 - "WL_CONNECTED", // 3 STATION_GOT_IP - "WL_CONNECT_FAILED", // 4 STATION_CONNECT_FAIL, STATION_WRONG_PASSWORD(NI) - "WL_CONNECTION_LOST", // 5 - "WL_DISCONNECTED", // 6 - "WL_STATION_WRONG_PASSWORD" // 7 KLUDGE -}; - -#ifdef ESP32 -const char * const AUTH_MODE_NAMES[] PROGMEM -{ - "OPEN", - "WEP", - "WPA_PSK", - "WPA2_PSK", - "WPA_WPA2_PSK", - "WPA2_ENTERPRISE", - "MAX" -}; -#elif defined(ESP8266) -const char * const AUTH_MODE_NAMES[] PROGMEM -{ - "", - "", - "WPA_PSK", // 2 ENC_TYPE_TKIP - "", - "WPA2_PSK", // 4 ENC_TYPE_CCMP - "WEP", // 5 ENC_TYPE_WEP - "", - "OPEN", //7 ENC_TYPE_NONE - "WPA_WPA2_PSK", // 8 ENC_TYPE_AUTO -}; -#endif - -const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; - - -#ifdef ESP32 -// as 2.5.2 -// typedef struct { -// char cc[3]; /**< country code string */ -// uint8_t schan; /**< start channel */ -// uint8_t nchan; /**< total channel number */ -// int8_t max_tx_power; /**< This field is used for getting WiFi maximum transmitting power, call esp_wifi_set_max_tx_power to set the maximum transmitting power. */ -// wifi_country_policy_t policy; /**< country policy */ -// } wifi_country_t; -const wifi_country_t WM_COUNTRY_US{"US",1,11,CONFIG_ESP32_PHY_MAX_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; -const wifi_country_t WM_COUNTRY_CN{"CN",1,13,CONFIG_ESP32_PHY_MAX_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; -const wifi_country_t WM_COUNTRY_JP{"JP",1,14,CONFIG_ESP32_PHY_MAX_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; -#elif defined(ESP8266) -// typedef struct { -// char cc[3]; /**< country code string */ -// uint8_t schan; /**< start channel */ -// uint8_t nchan; /**< total channel number */ -// uint8_t policy; /**< country policy */ -// } wifi_country_t; -const wifi_country_t WM_COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; -const wifi_country_t WM_COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; -const wifi_country_t WM_COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; -#endif - -#endif \ No newline at end of file diff --git a/lib/WiFiManager-2.0.3-alpha/travis/common.sh b/lib/WiFiManager-2.0.3-alpha/travis/common.sh deleted file mode 100644 index 4b3e6556..00000000 --- a/lib/WiFiManager-2.0.3-alpha/travis/common.sh +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/bash - -function build_examples() -{ - excludes=("$@") - # track the exit code for this platform - local exit_code=0 - # loop through results and add them to the array - examples=($(find $PWD/examples/ -name "*.pde" -o -name "*.ino")) - - # get the last example in the array - local last="${examples[@]:(-1)}" - - # loop through example sketches - for example in "${examples[@]}"; do - - # store the full path to the example's sketch directory - local example_dir=$(dirname $example) - - # store the filename for the example without the path - local example_file=$(basename $example) - - # skip files listed as excludes - for exclude in "${excludes[@]}"; do - if [ "${example_file}" == "${exclude}" ] ; then - echo ">>>>>>>>>>>>>>>>>>>>>>>> Skipping ${example_file} <<<<<<<<<<<<<<<<<<<<<<<<<<" - continue 2 - fi - done - - echo "$example_file: " - local sketch="$example_dir/$example_file" - echo "$sketch" - #arduino -v --verbose-build --verify $sketch - - # verify the example, and save stdout & stderr to a variable - # we have to avoid reading the exit code of local: - # "when declaring a local variable in a function, the local acts as a command in its own right" - local build_stdout - build_stdout=$(arduino --verify $sketch 2>&1) - - # echo output if the build failed - if [ $? -ne 0 ]; then - # heavy X - echo -e "\xe2\x9c\x96" - echo -e "----------------------------- DEBUG OUTPUT -----------------------------\n" - echo "$build_stdout" - echo -e "\n------------------------------------------------------------------------\n" - - # mark as fail - exit_code=1 - - else - # heavy checkmark - echo -e "\xe2\x9c\x93" - fi - done - - return $exit_code -} diff --git a/platformio.ini b/platformio.ini index 0646fc40..9528b346 100644 --- a/platformio.ini +++ b/platformio.ini @@ -8,17 +8,16 @@ ; Please visit documentation for the other options and examples ; http://docs.platformio.org/page/projectconf.html -[platformio] -default_envs = lolin_d32_pro +; [platformio] +; default_envs = lolin_d32_pro +; default_envs = nodemcuv2 [common] framework = arduino -platform = espressif8266@~1.8 board_f_cpu = 160000000L lib_deps_builtin = SPI - SPIFFS -lib_deps_external = +lib_deps_external = RF24@~1.3.2 ArduinoJson@~6.10.1 PubSubClient@~2.7 @@ -47,8 +46,20 @@ build_flags = # -D MILIGHT_UDP_DEBUG # -D STATE_DEBUG +[esp8266] +platform = espressif8266@~1.8 +lib_deps_external = + ${common.lib_deps_external} + sidoh/WiFiManager#cmidgley + +[esp32] +platform = espressif32 +lib_deps_external = + ${common.lib_deps_external} + https://github.com/tzapu/WiFiManager.git#2.0.3-alpha + [env:nodemcuv2] -platform = ${common.platform} +platform = ${esp8266.platform} framework = ${common.framework} upload_speed = ${common.upload_speed} board = nodemcuv2 @@ -56,11 +67,11 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D FIRMWARE_VARI extra_scripts = ${common.extra_scripts} lib_deps = ${common.lib_deps_builtin} - ${common.lib_deps_external} + ${esp8266.lib_deps_external} test_ignore = ${common.test_ignore} [env:d1_mini] -platform = ${common.platform} +platform = ${esp8266.platform} framework = ${common.framework} upload_speed = ${common.upload_speed} board = d1_mini @@ -68,11 +79,11 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D FIRMWARE_VARI extra_scripts = ${common.extra_scripts} lib_deps = ${common.lib_deps_builtin} - ${common.lib_deps_external} + ${esp8266.lib_deps_external} test_ignore = ${common.test_ignore} [env:esp12] -platform = ${common.platform} +platform = ${esp8266.platform} framework = ${common.framework} upload_speed = ${common.upload_speed} board = esp12e @@ -80,11 +91,11 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D FIRMWARE_VARI extra_scripts = ${common.extra_scripts} lib_deps = ${common.lib_deps_builtin} - ${common.lib_deps_external} + ${esp8266.lib_deps_external} test_ignore = ${common.test_ignore} [env:esp07] -platform = ${common.platform} +platform = ${esp8266.platform} framework = ${common.framework} upload_speed = ${common.upload_speed} board = esp07 @@ -92,11 +103,11 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m64.ld -D FIRMWARE_VARI extra_scripts = ${common.extra_scripts} lib_deps = ${common.lib_deps_builtin} - ${common.lib_deps_external} + ${esp8266.lib_deps_external} test_ignore = ${common.test_ignore} [env:huzzah] -platform = ${common.platform} +platform = ${esp8266.platform} framework = ${common.framework} upload_speed = ${common.upload_speed} board = huzzah @@ -104,11 +115,11 @@ build_flags = ${common.build_flags} -D FIRMWARE_VARIANT=huzzah extra_scripts = ${common.extra_scripts} lib_deps = ${common.lib_deps_builtin} - ${common.lib_deps_external} + ${esp8266.lib_deps_external} test_ignore = ${common.test_ignore} [env:d1_mini_pro] -platform = ${common.platform} +platform = ${esp8266.platform} framework = ${common.framework} upload_speed = ${common.upload_speed} board = d1_mini_pro @@ -116,17 +127,17 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D FIRMWARE_VARI extra_scripts = ${common.extra_scripts} lib_deps = ${common.lib_deps_builtin} - ${common.lib_deps_external} + ${esp8266.lib_deps_external} test_ignore = ${common.test_ignore} [env:lolin_d32_pro] -platform = espressif32 +platform = ${esp32.platform} framework = ${common.framework} upload_speed = ${common.upload_speed} board = lolin_d32_pro -build_flags = ${common.build_flags} -Wl, -D ESP32 -D FIRMWARE_VARIANT=lolin_d32_pro +build_flags = ${common.build_flags} -Wl, -D FIRMWARE_VARIANT=lolin_d32_pro extra_scripts = ${common.extra_scripts} lib_deps = ${common.lib_deps_builtin} - ${common.lib_deps_external} + ${esp32.lib_deps_external} test_ignore = ${common.test_ignore} \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 69b9c6f9..5131fd6d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -17,9 +16,6 @@ #include #include #include -// #include -#include -//#include #include #include #include @@ -29,6 +25,15 @@ #include #include #include +#include + +#ifdef ESP8266 + #include + #include +#elif ESP32 + #include + #include +#endif #include #include @@ -201,8 +206,6 @@ void onUpdateEnd() { * Apply what's in the Settings object. */ void applySettings() { - Serial.println("Applying settings..."); - if (milightClient) { delete milightClient; } @@ -223,25 +226,19 @@ void applySettings() { delete radios; } - Serial.println("Applying transitions.setDefaultPeriod..."); transitions.setDefaultPeriod(settings.defaultTransitionPeriod); - Serial.println("Applying MiLightRadioFactory..."); radioFactory = MiLightRadioFactory::fromSettings(settings); if (radioFactory == NULL) { Serial.println(F("ERROR: unable to construct radio factory")); } - Serial.println("Applying GroupStateStore..."); stateStore = new GroupStateStore(MILIGHT_MAX_STATE_ITEMS, settings.stateFlushInterval); - Serial.println("Applying RadioSwitchboard..."); radios = new RadioSwitchboard(radioFactory, stateStore, settings); - Serial.println("Applying PacketSender..."); packetSender = new PacketSender(*radios, settings, onPacketSentHandler); - Serial.println("Applying MiLightClient..."); milightClient = new MiLightClient( *radios, *packetSender, @@ -252,7 +249,6 @@ void applySettings() { milightClient->onUpdateBegin(onUpdateBegin); milightClient->onUpdateEnd(onUpdateEnd); - Serial.println("Applying MqttClient..."); if (settings.mqttServer().length() > 0) { mqttClient = new MqttClient(settings, milightClient); mqttClient->begin(); @@ -269,27 +265,22 @@ void applySettings() { bulbStateUpdater = new BulbStateUpdater(settings, *mqttClient, *stateStore); } - Serial.println("Applying initMilightUdpServers..."); initMilightUdpServers(); - Serial.println("Applying discoveryServer..."); if (discoveryServer) { - Serial.println("Applying discoveryServer... deleting"); delete discoveryServer; discoveryServer = NULL; } if (settings.discoveryPort != 0) { - Serial.println("Applying discoveryServer... cretae with port " + String(settings.discoveryPort)); discoveryServer = new MiLightDiscoveryServer(settings); - // Serial.println("Applying discoveryServer... beginning..."); +#ifdef ESP8266 + discoveryServer->begin(); +#elif ESP32 + // TODO check if valid to call this on wifi connected +#endif - Serial.println("Applying discoveryServer... TODO!"); - // ESP32: wifi needs to be connected? - // discoveryServer->begin(); - // Serial.println("Applying discoveryServer... begon"); } - Serial.println("Applying ledStatus..."); // update LED pin and operating mode if (ledStatus) { ledStatus->changePin(settings.ledPin); @@ -312,8 +303,6 @@ void applySettings() { // break; // } // WiFi.setPhyMode(wifiMode); - - Serial.println("Settings applied"); } /** @@ -355,28 +344,24 @@ void onGroupDeleted(const BulbId& id) { void setup() { Serial.begin(9600); - Serial.println("Initializing..."); - - // String ssid = "ESP" + String(ESP.getChipId()); - String ssid = "ESP" + String((uint32_t)ESP.getEfuseMac()); // lower 4 bytes (6 in total) - Serial.println("ssid=" + ssid); - - Serial.println("Initializing SPIFFS..."); + String ssid = "ESP" + String(getESPId()); // load up our persistent settings from the file system +#ifdef ESP8266 + SPIFFS.begin(); +#elif ESP32 if(!SPIFFS.begin(true)){ - Serial.println("An Error has occurred while mounting SPIFFS"); + Serial.println(F("Error while mounting SPIFFS")); } - Serial.println("Initializing settings..."); +#endif + Settings::load(settings); applySettings(); - Serial.println("Initializing ledstatus..."); // set up the LED status for wifi configuration ledStatus = new LEDStatus(settings.ledPin); ledStatus->continuous(settings.ledModeWifiConfig); - Serial.println("Initializing MDNS..."); // start up the wifi manager if (! MDNS.begin("milight-hub")) { Serial.println(F("Error setting up MDNS responder")); @@ -386,9 +371,11 @@ void setup() { // allows the "autoConnect" method to be non-blocking which can implement this same functionality. However, // that change is only on the development branch so we are going to continue to use this fork until // that is merged and ready. - // wifiManager.setSetupLoopCallback(handleLED); - Serial.println("Initializing WiFiManager..."); - wifiManager.setConfigResetCallback(handleLED); +#ifdef ESP8266 + wifiManager.setSetupLoopCallback(handleLED); +#elif ESP32 + // TODO check if the non-blocking implementation can be used or create a version with setSetupLoopCallback +#endif // Allows us to have static IP config in the captive portal. Yucky pointers to pointers, just to have the settings carry through wifiManager.setSaveConfigCallback(wifiExtraSettingsChange); @@ -439,10 +426,12 @@ void setup() { // if the config portal was started, make sure to turn off the config AP WiFi.mode(WIFI_STA); - // TODO ESP32: udp socket begin needs wifi? +#ifdef ESP32 + // TODO verify is this is correct if (discoveryServer) { discoveryServer->begin(); } +#endif } else { // set LED mode for Wifi failed ledStatus->continuous(settings.ledModeWifiFailed); @@ -452,22 +441,29 @@ void setup() { ESP.restart(); } - Serial.println("Initializing webserver..."); - MDNS.addService("http", "tcp", 80); - // SSDP.setSchemaURL("description.xml"); - // SSDP.setHTTPPort(80); - // SSDP.setName("ESP8266 MiLight Gateway"); - // SSDP.setSerialNumber(ESP.getChipId()); - // SSDP.setURL("/"); - // SSDP.setDeviceType("upnp:rootdevice"); - // SSDP.begin(); +#ifdef ESP8266 + SSDP.setSchemaURL("description.xml"); + SSDP.setHTTPPort(80); + SSDP.setName("ESP8266 MiLight Gateway"); + SSDP.setSerialNumber(ESP.getChipId()); + SSDP.setURL("/"); + SSDP.setDeviceType("upnp:rootdevice"); + SSDP.begin(); +#elif ESP32 + // TODO SSDP +#endif + httpServer = new MiLightHttpServer(settings, milightClient, stateStore, packetSender, radios, transitions); httpServer->onSettingsSaved(applySettings); httpServer->onGroupDeleted(onGroupDeleted); - // httpServer->on("/description.xml", HTTP_GET, []() { SSDP.schema(httpServer->client()); }); +#ifdef ESP8266 + httpServer->on("/description.xml", HTTP_GET, []() { SSDP.schema(httpServer->client()); }); +#elif ESP32 + // TODO SSDP +#endif httpServer->begin(); transitions.addListener( @@ -487,8 +483,6 @@ void setup() { void loop() { - Serial.println("Loop start"); - httpServer->handleClient(); if (mqttClient) { @@ -518,8 +512,6 @@ void loop() { Serial.println(F("Auto-restart triggered. Restarting...")); ESP.restart(); } - - Serial.println("Loop end"); } #endif \ No newline at end of file From 36336d7da6da82c8df8d1dcdad382534104098cb Mon Sep 17 00:00:00 2001 From: Maarten Claes Date: Sat, 15 Aug 2020 20:27:24 +0200 Subject: [PATCH 3/5] Begin discoveryServer only when connected --- src/main.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 5131fd6d..ec76ee1a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -273,11 +273,13 @@ void applySettings() { } if (settings.discoveryPort != 0) { discoveryServer = new MiLightDiscoveryServer(settings); -#ifdef ESP8266 + #ifdef ESP8266 discoveryServer->begin(); -#elif ESP32 - // TODO check if valid to call this on wifi connected -#endif + #elif ESP32 + if (WiFi.isConnected()) { + discoveryServer->begin(); + } + #endif } @@ -427,7 +429,6 @@ void setup() { WiFi.mode(WIFI_STA); #ifdef ESP32 - // TODO verify is this is correct if (discoveryServer) { discoveryServer->begin(); } From 82091d902c3b0447978535e2c8dac5a6ab8ce083 Mon Sep 17 00:00:00 2001 From: Maarten Claes Date: Sat, 15 Aug 2020 21:15:49 +0200 Subject: [PATCH 4/5] Init wifi before connecting clients (applySettings) --- src/main.cpp | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index ec76ee1a..73e1c0eb 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -273,13 +273,7 @@ void applySettings() { } if (settings.discoveryPort != 0) { discoveryServer = new MiLightDiscoveryServer(settings); - #ifdef ESP8266 discoveryServer->begin(); - #elif ESP32 - if (WiFi.isConnected()) { - discoveryServer->begin(); - } - #endif } @@ -358,7 +352,9 @@ void setup() { #endif Settings::load(settings); +#ifdef ESP8266 applySettings(); +#endif // set up the LED status for wifi configuration ledStatus = new LEDStatus(settings.ledPin); @@ -429,10 +425,8 @@ void setup() { WiFi.mode(WIFI_STA); #ifdef ESP32 - if (discoveryServer) { - discoveryServer->begin(); - } -#endif + applySettings(); +#endif } else { // set LED mode for Wifi failed ledStatus->continuous(settings.ledModeWifiFailed); From c5544e483c223b1232fc2cdc716f3098dc7cfba9 Mon Sep 17 00:00:00 2001 From: Maarten Claes Date: Tue, 29 Dec 2020 21:49:01 +0100 Subject: [PATCH 5/5] Update deps and fix ESP id --- lib/MQTT/HomeAssistantDiscoveryClient.cpp | 2 +- platformio.ini | 36 ++++++++--------------- 2 files changed, 13 insertions(+), 25 deletions(-) diff --git a/lib/MQTT/HomeAssistantDiscoveryClient.cpp b/lib/MQTT/HomeAssistantDiscoveryClient.cpp index 0b67d559..55a96048 100644 --- a/lib/MQTT/HomeAssistantDiscoveryClient.cpp +++ b/lib/MQTT/HomeAssistantDiscoveryClient.cpp @@ -37,7 +37,7 @@ void HomeAssistantDiscoveryClient::addConfig(const char* alias, const BulbId& bu DynamicJsonDocument config(1024); char uniqidBuffer[30]; - sprintf_P(uniqidBuffer, PSTR("%X-%s"), ESP.getChipId(), alias); + sprintf_P(uniqidBuffer, PSTR("%X-%s"), getESPId(), alias); config[F("schema")] = F("json"); config[F("name")] = alias; diff --git a/platformio.ini b/platformio.ini index a15eee85..35f43271 100644 --- a/platformio.ini +++ b/platformio.ini @@ -21,7 +21,7 @@ lib_deps_external = RF24@~1.3.2 ArduinoJson@~6.10.1 PubSubClient@~2.7 - https://github.com/ratkins/RGBConverter.git#07010f2 + https://github.com/ratkins/RGBConverter.git#07010f2605d9f787c6c55e62df10fec14e5894e4 WebSockets@~2.2.0 CircularBuffer@~1.2.0 PathVariableHandlers@~2.0.0 @@ -48,13 +48,15 @@ build_flags = [esp8266] platform = espressif8266@~1.8 -lib_deps_external = +lib_deps = + ${common.lib_deps_builtin} ${common.lib_deps_external} https://github.com/sidoh/WiFiManager.git#cmidgley [esp32] platform = espressif32 -lib_deps_external = +lib_deps = + ${common.lib_deps_builtin} ${common.lib_deps_external} https://github.com/tzapu/WiFiManager.git#2.0.3-alpha @@ -65,9 +67,7 @@ upload_speed = ${common.upload_speed} board = nodemcuv2 build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D FIRMWARE_VARIANT=nodemcuv2 extra_scripts = ${common.extra_scripts} -lib_deps = - ${common.lib_deps_builtin} - ${esp8266.lib_deps_external} +lib_deps = ${esp8266.lib_deps} test_ignore = ${common.test_ignore} [env:d1_mini] @@ -77,9 +77,7 @@ upload_speed = ${common.upload_speed} board = d1_mini build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D FIRMWARE_VARIANT=d1_mini extra_scripts = ${common.extra_scripts} -lib_deps = - ${common.lib_deps_builtin} - ${esp8266.lib_deps_external} +lib_deps = ${esp8266.lib_deps} test_ignore = ${common.test_ignore} [env:esp12] @@ -89,9 +87,7 @@ upload_speed = ${common.upload_speed} board = esp12e build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D FIRMWARE_VARIANT=esp12 extra_scripts = ${common.extra_scripts} -lib_deps = - ${common.lib_deps_builtin} - ${esp8266.lib_deps_external} +lib_deps = ${esp8266.lib_deps} test_ignore = ${common.test_ignore} [env:esp07] @@ -101,9 +97,7 @@ upload_speed = ${common.upload_speed} board = esp07 build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m64.ld -D FIRMWARE_VARIANT=esp07 extra_scripts = ${common.extra_scripts} -lib_deps = - ${common.lib_deps_builtin} - ${esp8266.lib_deps_external} +lib_deps = ${esp8266.lib_deps} test_ignore = ${common.test_ignore} [env:huzzah] @@ -113,9 +107,7 @@ upload_speed = ${common.upload_speed} board = huzzah build_flags = ${common.build_flags} -D FIRMWARE_VARIANT=huzzah extra_scripts = ${common.extra_scripts} -lib_deps = - ${common.lib_deps_builtin} - ${esp8266.lib_deps_external} +lib_deps = ${esp8266.lib_deps} test_ignore = ${common.test_ignore} [env:d1_mini_pro] @@ -125,9 +117,7 @@ upload_speed = ${common.upload_speed} board = d1_mini_pro build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D FIRMWARE_VARIANT=d1_mini_PRO extra_scripts = ${common.extra_scripts} -lib_deps = - ${common.lib_deps_builtin} - ${esp8266.lib_deps_external} +lib_deps = ${esp8266.lib_deps} test_ignore = ${common.test_ignore} [env:lolin_d32_pro] @@ -137,7 +127,5 @@ upload_speed = ${common.upload_speed} board = lolin_d32_pro build_flags = ${common.build_flags} -Wl, -D FIRMWARE_VARIANT=lolin_d32_pro extra_scripts = ${common.extra_scripts} -lib_deps = - ${common.lib_deps_builtin} - ${esp32.lib_deps_external} +lib_deps = ${esp32.lib_deps} test_ignore = ${common.test_ignore} \ No newline at end of file