Commit 80a71660 authored by Eric Duminil's avatar Eric Duminil
Browse files

Trying to add autoconnect libraries

parent a5807d86
/**
* AutoConnectTicker class implementation.
* Provides a service that shows the flicker signal according to WiFi
* connection status.
* @file AutoConnectTicker.cpp
* @author hieromon@gmail.com
* @version 0.9.11
* @date 2019-07-09
* @copyright MIT license.
*/
#include "AutoConnectTicker.h"
/**
* Start ticker cycle
* @param cycle Cycle time in [ms]
* @param duty Duty cycle in [ms]
*/
void AutoConnectTicker::start(const uint32_t cycle, const uint32_t duty) {
_cycle = cycle;
if (duty <= _cycle)
_duty = duty;
start();
}
/**
* Start ticker cycle
*/
void AutoConnectTicker::start(void) {
pinMode(_port, OUTPUT);
_pulse.detach();
_period.attach_ms<AutoConnectTicker*>(_cycle, AutoConnectTicker::_onPeriod, this);
}
/**
* Turn on the flicker signal and reserves a ticker to turn off the
* signal. This behavior will perform every cycle to generate the
* pseudo-PWM signal.
* If the function is registered, call the callback function at the
* end of one cycle.
* @param t Its own address
*/
void AutoConnectTicker::_onPeriod(AutoConnectTicker* t) {
digitalWrite(t->_port, t->_turnOn);
t->_pulse.once_ms<AutoConnectTicker*>(t->_duty, AutoConnectTicker::_onPulse, t);
if (t->_callback)
t->_callback();
}
/**
* Turn off the flicker signal
* @param t Its own address
*/
void AutoConnectTicker::_onPulse(AutoConnectTicker* t) {
digitalWrite(t->_port, !(t->_turnOn));
}
/**
* Declaration of AutoConnectTicker class.
* @file AutoConnectTicker.h
* @author hieromon@gmail.com
* @version 1.2.0
* @date 2020-10-30
* @copyright MIT license.
*/
#ifndef _AUTOCONNECTTICKER_H_
#define _AUTOCONNECTTICKER_H_
#include <functional>
#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#endif
#include <Ticker.h>
#include "AutoConnectDefs.h"
class AutoConnectTicker {
public:
explicit AutoConnectTicker(const uint8_t port = AUTOCONNECT_TICKER_PORT, const uint8_t active = LOW, const uint32_t cycle = 0, uint32_t duty = 0) : _cycle(cycle), _duty(duty), _port(port), _turnOn(active), _callback(nullptr) {
if (_duty > _cycle)
_duty = _cycle;
}
~AutoConnectTicker() { stop(); }
typedef std::function<void(void)> Callback_ft;
void setCycle(const uint32_t cycle) { _cycle = cycle; }
void setDuty(const uint32_t duty) { _duty = duty <= _cycle ? duty : _duty; }
void start(const uint32_t cycle, const uint32_t duty);
void start(const uint32_t cycle, const uint8_t width) { start(cycle, (uint32_t)((cycle * width) >> 8)); }
void start(void);
void stop(void) { _period.detach(); _pulse.detach(); digitalWrite(_port, !_turnOn); _cycle = 0; _duty = 0; }
void onPeriod(Callback_ft cb) { _callback = cb ;}
uint32_t getCycle(void) const { return _cycle; }
uint32_t getDuty(void) const { return _duty; }
protected:
Ticker _period; /**< Ticker for flicking cycle */
Ticker _pulse; /**< Ticker for pulse width generating */
uint32_t _cycle; /**< Cycle time in [ms] */
uint32_t _duty; /**< Pulse width in [ms] */
private:
static void _onPeriod(AutoConnectTicker* t);
static void _onPulse(AutoConnectTicker* t);
uint8_t _port; /**< Port to output signal */
uint8_t _turnOn; /**< Signal to turn on */
Callback_ft _callback; /**< An exit by every cycle */
};
#endif // !_AUTOCONNECTTICKER_H_
/**
* AutoConnect quoted type declarations.
* @file AutoConnectTypes.h
* @author hieromon@gmail.com
* @version 1.2.0
* @date 2020-04-17
* @copyright MIT license.
*/
#ifndef _AUTOCONNECTTYPES_H_
#define _AUTOCONNECTTYPES_H_
/**< A type to save established credential at WiFi.begin automatically. */
typedef enum AC_SAVECREDENTIAL {
AC_SAVECREDENTIAL_NEVER,
AC_SAVECREDENTIAL_AUTO
} AC_SAVECREDENTIAL_t;
/**< URI that can be specified to AutoConnectConfig::bootUri. */
typedef enum AC_ONBOOTURI {
AC_ONBOOTURI_ROOT,
AC_ONBOOTURI_HOME
} AC_ONBOOTURI_t;
/** WiFi connection principle, it specifies the order of WiFi connecting with saved credentials. */
typedef enum AC_PRINCIPLE {
AC_PRINCIPLE_RECENT,
AC_PRINCIPLE_RSSI
} AC_PRINCIPLE_t;
/**< An enumerated type of the designated menu items. */
typedef enum AC_MENUITEM {
AC_MENUITEM_NONE = 0x0000,
AC_MENUITEM_CONFIGNEW = 0x0001,
AC_MENUITEM_OPENSSIDS = 0x0002,
AC_MENUITEM_DISCONNECT = 0x0004,
AC_MENUITEM_RESET = 0x0008,
AC_MENUITEM_HOME = 0x0010,
AC_MENUITEM_UPDATE = 0x0020,
AC_MENUITEM_DEVINFO = 0x0040
} AC_MENUITEM_t;
/**< Specifier for using built-in OTA */
typedef enum AC_OTA {
AC_OTA_EXTRA,
AC_OTA_BUILTIN
} AC_OTA_t;
/**< Scope of certification influence */
typedef enum AC_AUTHSCOPE {
AC_AUTHSCOPE_PARTIAL = 0x0001, // Available for particular AUX-pages.
AC_AUTHSCOPE_AUX = 0x0002, // All AUX-pages are affected by an authentication.
AC_AUTHSCOPE_AC = 0x0004, // Allow authentication to AutoConnect pages.
AC_AUTHSCOPE_PORTAL = AC_AUTHSCOPE_AC | AC_AUTHSCOPE_AUX, // All AutoConnect pages are affected by an authentication.
AC_AUTHSCOPE_WITHCP = 0x8000 // Allows authenticating in the standalone state.
} AC_AUTHSCOPE_t;
/**< A type to enable authentication. */
typedef enum AC_AUTH {
AC_AUTH_NONE,
AC_AUTH_DIGEST,
AC_AUTH_BASIC
} AC_AUTH_t;
#endif // !_AUTOCONNECTTYPES_H_
/**
* AutoConnectUpdate class implementation.
* @file AutoConnectUpdate.cpp
* @author hieromon@gmail.com
* @version 1.0.2
* @date 2019-09-18
* @copyright MIT license.
*/
#include "AutoConnectDefs.h"
#ifdef AUTOCONNECT_USE_UPDATE
#include <functional>
#include <type_traits>
#include "AutoConnectUpdate.h"
#include "AutoConnectUpdatePage.h"
#include "AutoConnectJsonDefs.h"
/**
* The AutoConnectUpdateAct class inherits from the HTTPupdate class. The
* update server corresponding to this class needs a simple script
* based on an HTTP server. It is somewhat different from the advanced
* updater script offered by Arduino core of ESP8266.
* The equipment required for the update server for the
* AutoConnectUpdateAct class is as follows:
*
* The catalog script:
* The update server URI /catalog is a script process that responds to
* queries from the AutoConnectUpdateAct class. The catalog script accepts
* the queries such as '/catalog?op=list&path='.
* - op:
* An op parameter specifies the query operation. In the current
* version, available query operation is a list only.
* - list:
* The query operation list responds with a list of available sketch
* binaries. The response of list is a directory list of file paths
* on the server specified by the path parameter and describes as a
* JSON document. Its JSON document is an array of JSON objects with
* the name and the type keys. For example, it is the following
* description:
* [
* {
* "name": "somefolder",
* "type": "directory"
* },
* {
* "name": "update.ino",
* "type": "file"
* },
* {
* "name": "update.bin",
* "type": "bin"
* }
* ]
* - name:
* Name of file entry on the path.
* - type:
* The type of the file. It defines either directory, file or bin.
* The bin means that the file is a sketch binary, and the
* AutoConnectUpdateAct class recognizes only files type bin as
* available update files.
* - path:
* A path parameter specifies the path on the server storing
* available sketch binaries.
*
* Access to the path on the server:
* It should have access to the bin file. The update server needs to
* send a bin file with a content type of application/octet-stream via
* HTTP and also needs to attach an MD5 hash value to the x-MD5 header.
*/
/**
* The following two templates absorb callbacks that are enabled/disabled
* by the Update library version in the core.
* The old UpdateClass of the ESP8266/ESP32 arduino core does not have
* the onProgress function for registering callbacks. These templates
* avoid the onProgress calls on older library versions.
* In versions where the update function callback is disabled, the
* dialog on the client browser does not show the progress of the update.
*/
#if defined(ARDUINO_ARCH_ESP8266)
using UpdateVariedClass = UpdaterClass;
#elif defined(ARDUINO_ARCH_ESP32)
using UpdateVariedClass = UpdateClass;
#endif
namespace AutoConnectUtil {
AC_HAS_FUNC(onProgress);
template<typename T>
typename std::enable_if<AutoConnectUtil::has_func_onProgress<T>::value, AutoConnectUpdateAct::AC_UPDATEDIALOG_t>::type onProgress(T& updater, UpdateVariedClass::THandlerFunction_Progress fn) {
updater.onProgress(fn);
AC_DBG("Updater keeps callback\n");
return AutoConnectUpdateAct::UPDATEDIALOG_METER;
}
template<typename T>
typename std::enable_if<!AutoConnectUtil::has_func_onProgress<T>::value, AutoConnectUpdateAct::AC_UPDATEDIALOG_t>::type onProgress(T& updater, UpdateVariedClass::THandlerFunction_Progress fn) {
(void)(updater);
(void)(fn);
return AutoConnectUpdateAct::UPDATEDIALOG_LOADER;
}
}
/**
* Definitions of notification commands to synchronize update processing
* with the Web client.
*/
#define UPDATE_NOTIFY_START "#s"
#define UPDATE_NOTIFY_PROGRESS "#p"
#define UPDATE_NOTIFY_END "#e"
#define UPDATE_NOTIFY_REBOOT "#r"
/**
* A destructor. Release the update processing dialogue page generated
* as AutoConnectAux.
*/
AutoConnectUpdateAct::~AutoConnectUpdateAct() {
_auxCatalog.reset(nullptr);
_auxProgress.reset(nullptr);
_auxResult.reset(nullptr);
}
/**
* Attach the AutoConnectUpdateAct to the AutoConnect which constitutes
* the bedrock of the update process. This function creates dialog pages
* for update operation as an instance of AutoConnectAux and joins to
* the AutoConnect which is the bedrock of the process.
* @param portal A reference of AutoConnect
*/
void AutoConnectUpdateAct::attach(AutoConnect& portal) {
AutoConnectAux* updatePage;
updatePage = new AutoConnectAux(String(FPSTR(_pageCatalog.uri)), String(FPSTR(_pageCatalog.title)), _pageCatalog.menu);
_buildAux(updatePage, &_pageCatalog, lengthOf(_elmCatalog));
_auxCatalog.reset(updatePage);
updatePage = new AutoConnectAux(String(FPSTR(_pageProgress.uri)), String(FPSTR(_pageProgress.title)), _pageProgress.menu);
_buildAux(updatePage, &_pageProgress, lengthOf(_elmProgress));
_auxProgress.reset(updatePage);
updatePage = new AutoConnectAux(String(FPSTR(_pageResult.uri)), String(FPSTR(_pageResult.title)), _pageResult.menu);
_buildAux(updatePage, &_pageResult, lengthOf(_elmResult));
_auxResult.reset(updatePage);
_auxCatalog->on(std::bind(&AutoConnectUpdateAct::_onCatalog, this, std::placeholders::_1, std::placeholders::_2), AC_EXIT_AHEAD);
_auxProgress->on(std::bind(&AutoConnectUpdateAct::_onUpdate, this, std::placeholders::_1, std::placeholders::_2), AC_EXIT_AHEAD);
_auxResult->on(std::bind(&AutoConnectUpdateAct::_onResult, this, std::placeholders::_1, std::placeholders::_2), AC_EXIT_AHEAD);
portal.join(*_auxCatalog.get());
portal.join(*_auxProgress.get());
portal.join(*_auxResult.get());
// Register the callback to inform the update progress
_dialog = AutoConnectUtil::onProgress<UpdateVariedClass>(Update, std::bind(&AutoConnectUpdateAct::_inProgress, this, std::placeholders::_1, std::placeholders::_2));
// Adjust the client dialog pattern according to the callback validity
// of the UpdateClass.
AutoConnectElement* loader = _auxProgress->getElement(String(F("loader")));
AutoConnectElement* progress_meter = _auxProgress->getElement(String(F("progress_meter")));
AutoConnectElement* progress_loader = _auxProgress->getElement(String(F("progress_loader")));
AutoConnectElement* enable_loader = _auxProgress->getElement(String(F("enable_loader")));
AutoConnectElement* inprogress_meter = _auxProgress->getElement(String(F("inprogress_meter")));
switch (_dialog) {
case UPDATEDIALOG_LOADER:
progress_meter->enable =false;
inprogress_meter->enable = false;
break;
case UPDATEDIALOG_METER:
loader->enable = false;
progress_loader->enable =false;
enable_loader->enable =false;
break;
}
// Attach this to the AutoConnectUpdateAct
portal._update.reset(this);
AC_DBG("AutoConnectUpdate attached\n");
if (WiFi.status() == WL_CONNECTED)
enable();
// Attach the update progress monitoring handler
_webServer = &(portal.host());
_webServer->on(String(F(AUTOCONNECT_URI_UPDATE_PROGRESS)), HTTP_ANY, std::bind(&AutoConnectUpdateAct::_progress, this));
// Reset the update progress status
_status = UPDATE_IDLE;
}
/**
* Detach the update item from the current AutoConnect menu.
* AutoConnectUpdateAct still active.
*/
void AutoConnectUpdateAct::disable(const bool activate) {
_enable = activate;
if (_auxCatalog) {
_auxCatalog->menu(false);
AC_DBG("AutoConnectUpdate disabled\n");
}
}
/**
* Make AutoConnectUpdateAct class available by incorporating the update
* function into the menu.
*/
void AutoConnectUpdateAct::enable(void) {
_enable = true;
_status = UPDATE_IDLE;
if (_auxCatalog) {
_auxCatalog->menu(WiFi.status() == WL_CONNECTED);
AC_DBG("AutoConnectUpdate enabled\n");
}
}
/**
* An entry point of the process loop as AutoConnect::handleClient.
* The handleClient function of the AutoConnect that later accompanied
* the AutoConnectUpdate class will invoke this entry.
* This entry point will be called from the process loop of handleClient
* function only if the class is associated with the AutoConnect class.
*/
void AutoConnectUpdateAct::handleUpdate(void) {
// Activate the update menu conditional with WiFi connected.
if (!isEnabled() && _enable) {
if (WiFi.status() == WL_CONNECTED)
enable();
}
if (isEnabled()) {
if (WiFi.status() == WL_CONNECTED) {
// Evaluate the processing status of AutoConnectUpdateAct and
// execute it accordingly. It is only this process point that
// requests update processing.
if (_status == UPDATE_START) {
_status = UPDATE_PROGRESS;
update();
}
else if (_status == UPDATE_RESET) {
AC_DBG("Restart on %s updated...\n", _binName.c_str());
ESP.restart();
}
}
// If WiFi is not connected, disables the update menu.
// However, the AutoConnectUpdateAct class stills active.
else
disable(_enable);
}
}
/**
* Run the update function of HTTPUpdate that is the base class and
* fetch the result.
* @return AC_UPDATESTATUS_t
*/
AC_UPDATESTATUS_t AutoConnectUpdateAct::update(void) {
// Start update
String uriBin = uri + '/' + _binName;
if (_binName.length()) {
WiFiClient wifiClient;
AC_DBG("%s:%d/%s update in progress...", host.c_str(), port, uriBin.c_str());
t_httpUpdate_return ret = HTTPUpdateClass::update(wifiClient, host, port, uriBin);
switch (ret) {
case HTTP_UPDATE_FAILED:
_status = UPDATE_FAIL;
AC_DBG_DUMB(" %s\n", getLastErrorString().c_str());
AC_DBG("update returns HTTP_UPDATE_FAILED\n");
break;
case HTTP_UPDATE_NO_UPDATES:
_status = UPDATE_IDLE;
AC_DBG_DUMB(" No available update\n");
break;
case HTTP_UPDATE_OK:
_status = UPDATE_SUCCESS;
AC_DBG_DUMB(" completed\n");
break;
}
}
else {
AC_DBG("An update has not specified");
_status = UPDATE_NOAVAIL;
}
return _status;
}
/**
* Create the update operation pages using a predefined page structure
* with two structures as ACPage_t and ACElementProp_t which describe
* for AutoConnectAux configuration.
* This function receives instantiated AutoConnectAux, instantiates
* defined AutoConnectElements by ACPage_t, and configures it into
* received AutoConnectAux.
* @param aux An instantiated AutoConnectAux that will configure according to ACPage_t.
* @param page Pre-defined ACPage_t
* @param elementNum Number of AutoConnectElements to configure.
*/
void AutoConnectUpdateAct::_buildAux(AutoConnectAux* aux, const AutoConnectUpdateAct::ACPage_t* page, const size_t elementNum) {
for (size_t n = 0; n < elementNum; n++) {
if (page->element[n].type == AC_Element) {
AutoConnectElement* element = new AutoConnectElement;
element->name = String(FPSTR(page->element[n].name));
if (page->element[n].value)
element->value = String(FPSTR(page->element[n].value));
aux->add(reinterpret_cast<AutoConnectElement&>(*element));
}
else if (page->element[n].type == AC_Radio) {
AutoConnectRadio* element = new AutoConnectRadio;
element->name = String(FPSTR(page->element[n].name));
aux->add(reinterpret_cast<AutoConnectElement&>(*element));
}
else if (page->element[n].type == AC_Submit) {
AutoConnectSubmit* element = new AutoConnectSubmit;
element->name = String(FPSTR(page->element[n].name));
if (page->element[n].value)
element->value = String(FPSTR(page->element[n].value));
if (page->element[n].peculiar)
element->uri = String(FPSTR(page->element[n].peculiar));
aux->add(reinterpret_cast<AutoConnectElement&>(*element));
}
else if (page->element[n].type == AC_Text) {
AutoConnectText* element = new AutoConnectText;
element->name = String(FPSTR(page->element[n].name));
if (page->element[n].value)
element->value = String(FPSTR(page->element[n].value));
if (page->element[n].peculiar)
element->format = String(FPSTR(page->element[n].peculiar));
aux->add(reinterpret_cast<AutoConnectText&>(*element));
}
}
}
/**
* An update callback function in HTTPUpdate::update.
* This callback handler acts as an HTTPUpdate::update callback and
* sends the updated amount over the web socket to advance the progress
* of the progress meter displayed in the browser.
* @param amount Already transferred size.
* @param size Total size of the binary to update.
*/
void AutoConnectUpdateAct::_inProgress(size_t amount, size_t size) {
_amount = amount;
_binSize = size;
_webServer->handleClient();
}
/**
* AUTOCONNECT_URI_UPDATE page handler.
* It queries the update server for cataloged sketch binary and
* displays the result on the page as an available updater list.
* The update execution button held by this page will be enabled only
* when there are any available updaters.
* @param catalog A reference of the AutoConnectAux as AUTOCONNECT_URI_UPDATE
* @param args A reference of the PageArgument of the PageBuilder
* @return Additional string to the page but it always null.
*/
String AutoConnectUpdateAct::_onCatalog(AutoConnectAux& catalog, PageArgument& args) {
AC_UNUSED(args);
WiFiClient wifiClient;
HTTPClient httpClient;
// Reallocate available firmwares list.
_binName = String("");
AutoConnectText& caption = catalog.getElement<AutoConnectText>(String(F("caption")));
AutoConnectRadio& firmwares = catalog.getElement<AutoConnectRadio>(String(F("firmwares")));
AutoConnectSubmit& submit = catalog.getElement<AutoConnectSubmit>(String(F("update")));
firmwares.empty();
firmwares.tags.clear();
submit.enable = false;
String qs = String(F(AUTOCONNECT_UPDATE_CATALOG)) + '?' + String(F("op=list&path=")) + uri;
AC_DBG("Query %s:%d%s\n", host.c_str(), port, qs.c_str());
// Throw a query to the update server and parse the response JSON
// document. After that, display the bin type file name contained in
// its JSON document as available updaters to the page.
if (httpClient.begin(wifiClient, host, port, qs)) {
int responseCode = httpClient.GET();
if (responseCode == HTTP_CODE_OK) {
bool parse;
char beginOfList[] = "[";
char endOfEntry[] = ",";
char endOfList[] = "]";
WiFiClient& responseBody = httpClient.getStream();
// Read partially and repeatedly the responded http stream that is
// including the JSON array to reduce the buffer size for parsing
// of the firmware catalog list.
AC_DBG("Update server responded:");
responseBody.find(beginOfList);
do {
// The size of the JSON buffer is a fixed. It can be a problem
// when parsing with ArduinoJson V6. If memory insufficient has
// occurred during the parsing, increase this buffer size.
ArduinoJsonStaticBuffer<AUTOCONNECT_UPDATE_CATALOG_JSONBUFFER_SIZE> jb;
#if ARDUINOJSON_VERSION_MAJOR<=5
ArduinoJsonObject json = jb.parseObject(responseBody);
parse = json.success();
#else
DeserializationError err = deserializeJson(jb, responseBody);
ArduinoJsonObject json = jb.as<JsonObject>();
parse = (err == DeserializationError::Ok);
#endif
if (parse) {
#ifdef AC_DEBUG
AC_DBG_DUMB("\n");
ARDUINOJSON_PRINT(json, AC_DEBUG_PORT);
#endif
// Register only bin type file name as available sketch binary to
// AutoConnectRadio value based on the response from the update server.
firmwares.order = AC_Horizontal;
if (json["type"].as<String>().equalsIgnoreCase("bin")) {
firmwares.add(json[F("name")].as<String>());
String attr = String(F("<span>")) + json[F("date")].as<String>() + String(F("</span><span>")) + json[F("time")].as<String>().substring(0, 5) + String(F("</span><span>")) + String(json[F("size")].as<int>()) + String(F("</span>"));
firmwares.tags.push_back(attr);
}
}
else {
#if ARDUINOJSON_VERSION_MAJOR<=5
String errCaption = String(F("JSON parse error"));
#else
String errCaption = String(err.c_str());
#endif
caption.value = String(F("Invalid catalog list:")) + errCaption;
AC_DBG("JSON:%s\n", errCaption.c_str());
break;
}
} while (responseBody.findUntil(endOfEntry, endOfList));
AC_DBG_DUMB("\n");
if (parse) {
if (firmwares.size()) {
caption.value = String(F("<h4>Available firmwares</h4>"));
submit.enable = true;
}
else
caption.value = String(F("<h4>No available firmwares</h4>"));
}
}
else {
caption.value = String(F("Update server responds (")) + String(responseCode) + String("):");
caption.value += HTTPClient::errorToString(responseCode);
AC_DBG("%s\n", caption.value.c_str());
}
httpClient.end();
}
else {
caption.value = String(F("http failed connect to ")) + host + String(':') + String(port);
AC_DBG("%s\n", caption.value.c_str());
}
_status = UPDATE_IDLE;
return String("");
}
/**
* AUTOCONNECT_URI_UPDATE_ACT page handler
* Only display a dialog indicating that the update is in progress.
* @param progress A reference of the AutoConnectAux as AUTOCONNECT_URI_UPDATE_ACT
* @param args A reference of the PageArgument of the PageBuilder
* @return Additional string to the page but it always null.
*/
String AutoConnectUpdateAct::_onUpdate(AutoConnectAux& progress, PageArgument& args) {
AC_UNUSED(args);
// Constructs the dialog page.
AutoConnectElement* binName = progress.getElement(String(F("binname")));
_binName = _auxCatalog->getElement<AutoConnectRadio>(String(F("firmwares"))).value();
binName->value = _binName;
AutoConnectElement* url = progress.getElement(String("url"));
url->value = host + ':' + port;
return String("");
}
/**
* AUTOCONNECT_URI_UPDATE_RESULT page handler
* Display the result of the update function of HTTPUpdate class.
* @param result A reference of the AutoConnectAux as AUTOCONNECT_URI_UPDATE_RESULT
* @param args A reference of the PageArgument of the PageBuilder
* @return Additional string to the page but it always null.
*/
String AutoConnectUpdateAct::_onResult(AutoConnectAux& result, PageArgument& args) {
AC_UNUSED(args);
String resForm;
String resColor;
bool restart = false;
switch (_status) {
case UPDATE_SUCCESS:
resForm = String(F(" successfully updated. restart..."));
resColor = String(F("blue"));
restart = true;
break;
case UPDATE_FAIL:
resForm = String(F(" failed."));
resForm += String(F("<br>")) + getLastErrorString();
resColor = String(F("red"));
break;
default:
resForm = String(F("<br>No available update."));
resColor = String(F("red"));
break;
}
AutoConnectText& resultElm = result.getElement<AutoConnectText>(String(F("status")));
resultElm.value = _binName + resForm;
resultElm.style = String(F("font-size:120%;color:")) + resColor;
result.getElement<AutoConnectElement>(String(F("restart"))).enable = restart;
return String("");
}
/**
* A handler for notifying the client of the progress of update processing.
* This handler specifies the URI behavior defined as THandlerFunc of
* ESP8266 WebServer (WebServer for ESP32).
* Usually, that URI is /_ac/update_progress and will return the
* processed amount of update processing to the client.
*/
void AutoConnectUpdateAct::_progress(void) {
String reqOperation = "op";
String reqOperand;
String payload = String("");
int httpCode;
static const char reply_msg_op[] PROGMEM = "invalid operation";
static const char reply_msg_seq[] PROGMEM = "invalid sequence";
static const char reply_msg_inv[] PROGMEM = "invalid request";
static const char* content_type = "text/plain";
switch (_webServer->method()) {
case HTTP_POST:
reqOperand = _webServer->arg(reqOperation);
switch (_status) {
case UPDATE_IDLE:
if (reqOperand == String(UPDATE_NOTIFY_START)) {
httpCode = 200;
_status = UPDATE_START;
}
else {
payload = String(FPSTR(reply_msg_seq));
httpCode = 500;
}
break;
case UPDATE_SUCCESS:
if (reqOperand == String(UPDATE_NOTIFY_REBOOT)) {
_status = UPDATE_RESET;
httpCode = 200;
}
else {
payload = String(FPSTR(reply_msg_seq));
httpCode = 500;
}
break;
default:
payload = String(FPSTR(reply_msg_op));
httpCode = 500;
}
break;
case HTTP_GET:
switch (_status) {
case UPDATE_PROGRESS:
payload = String(UPDATE_NOTIFY_PROGRESS) + ',' + String(_amount) + ':' + String(_binSize);
httpCode = 200;
break;
case UPDATE_IDLE:
case UPDATE_SUCCESS:
case UPDATE_NOAVAIL:
case UPDATE_FAIL:
payload = String(UPDATE_NOTIFY_END);
httpCode = 200;
break;
default:
payload = String(FPSTR(reply_msg_seq));
httpCode = 500;
}
break;
default:
httpCode = 500;
payload = String(FPSTR(reply_msg_inv));
}
_webServer->send(httpCode, content_type, payload);
}
#endif // !AUTOCONNECT_USE_UPDATE
/**
* Declaration of AutoConnectUpdate class.
* The AutoConnectUpdate class is a class for updating sketch binary
* via OTA and inherits the HTTPUpdate class of the arduino core.
* It declares the class implementations of both core libraries as
* HTTPUpdateClass to absorb differences between ESP8266 and ESP32
* class definitions.
* The AutoConnectUpdate class add ons three features to the HTTPupdate
* class.
* 1. Dialog pages for operating the update.
* The dialog pages are all AutoConnectAux, and they select available
* sketch binary, display during update processing, and display
* update results.
* 2. Dialog pages handler
* In the dialog page, AUTOCONNECT_URI_UPDATE, AUTOCONNECT_URI_UPDATE_ACT,
* AUTOCONNECT_URI_UPDATE_RESULT are assigned and there is a page
* handler for each.
* 3. Attach to the AutoConnect.
* Attaching the AutoConnectUpdate class to AutoConnect makes the
* sketch binary update function available, and the operation dialog
* pages are incorporated into the AutoConnect menu.
* @file AutoConnectUpdate.h
* @author hieromon@gmail.com
* @version 1.0.0
* @date 2019-08-15
* @copyright MIT license.
*/
#ifndef _AUTOCONNECTUPDATE_H_
#define _AUTOCONNECTUPDATE_H_
#include "AutoConnectDefs.h"
#ifdef AUTOCONNECT_USE_UPDATE
#ifndef AUTOCONNECT_USE_JSON
#define AUTOCONNECT_USE_JSON
#endif
#include <memory>
#define NO_GLOBAL_HTTPUPDATE
#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h>
using HTTPUpdateClass = ESP8266HTTPUpdate;
#elif defined(ARDUINO_ARCH_ESP32)
#include <HTTPClient.h>
#include <HTTPUpdate.h>
using HTTPUpdateClass = HTTPUpdate;
#endif
// #include <WebSocketsServer.h>
// Quote the true AutoConnectUpdate class according to AUTOCONNECT_USE_UPDATE.
#define AutoConnectUpdate AutoConnectUpdateAct
#else // !AUTOCONNECT_USE_UPDATE!
#define AutoConnectUpdate AutoConnectUpdateVoid
#endif
#include "AutoConnect.h"
// Support LED flashing only the board with built-in LED.
#if defined(BUILTIN_LED) || defined(LED_BUILTIN)
#define AC_SETLED(s) do {setLedPin(AUTOCONNECT_TICKER_PORT, s);} while(0)
#else
#define AC_SETLED(s) do {} while(0)
#endif
// Indicate an update process loop
typedef enum AC_UPDATESTATUS {
UPDATE_RESET, /**< Update process ended, need to reset */
UPDATE_IDLE, /**< Update process has not started */
UPDATE_START, /**< Update process has been started */
UPDATE_PROGRESS, /**< Update process in progress */
UPDATE_SUCCESS, /**< Update successfully completed */
UPDATE_NOAVAIL, /**< No available update */
UPDATE_FAIL /**< Update fails */
} AC_UPDATESTATUS_t;
class AutoConnectUpdateVoid {
public:
explicit AutoConnectUpdateVoid(const String& host = String(""), const uint16_t port = AUTOCONNECT_UPDATE_PORT, const String& uri = String("."), const int timeout = AUTOCONNECT_UPDATE_TIMEOUT, const uint8_t ledOn = LOW) {
AC_UNUSED(host);
AC_UNUSED(port);
AC_UNUSED(uri);
AC_UNUSED(timeout);
AC_UNUSED(ledOn);
}
AutoConnectUpdateVoid(AutoConnect& portal, const String& host = String(""), const uint16_t port = AUTOCONNECT_UPDATE_PORT, const String& uri = String("."), const int timeout = AUTOCONNECT_UPDATE_TIMEOUT, const uint8_t ledOn = LOW) {
AC_UNUSED(portal);
AC_UNUSED(host);
AC_UNUSED(port);
AC_UNUSED(uri);
AC_UNUSED(timeout);
AC_UNUSED(ledOn);
}
virtual ~AutoConnectUpdateVoid() {}
virtual void attach(AutoConnect& portal) { AC_UNUSED(portal); }
virtual void enable(void) {}
virtual void disable(const bool activate = false) { AC_UNUSED(activate); }
virtual void handleUpdate(void) {}
virtual bool isEnabled(void) { return false; }
virtual AC_UPDATESTATUS_t status(void) { return UPDATE_IDLE; }
virtual AC_UPDATESTATUS_t update(void) { return UPDATE_IDLE; }
};
#ifdef AUTOCONNECT_USE_UPDATE
class AutoConnectUpdateAct : public AutoConnectUpdateVoid, public HTTPUpdateClass {
public:
explicit AutoConnectUpdateAct(const String& host = String(""), const uint16_t port = AUTOCONNECT_UPDATE_PORT, const String& uri = String("."), const int timeout = AUTOCONNECT_UPDATE_TIMEOUT, const uint8_t ledOn = AUTOCONNECT_UPDATE_LEDON)
: HTTPUpdateClass(timeout), host(host), port(port), uri(uri), _amount(0), _binSize(0), _enable(false), _dialog(UPDATEDIALOG_LOADER), _status(UPDATE_IDLE), _binName(String()), _webServer(nullptr) {
AC_SETLED(ledOn); /**< LED blinking during the update that is the default. */
rebootOnUpdate(false); /**< Default reboot mode */
}
AutoConnectUpdateAct(AutoConnect& portal, const String& host = String(""), const uint16_t port = AUTOCONNECT_UPDATE_PORT, const String& uri = String("."), const int timeout = AUTOCONNECT_UPDATE_TIMEOUT, const uint8_t ledOn = AUTOCONNECT_UPDATE_LEDON)
: HTTPUpdateClass(timeout), host(host), port(port), uri(uri), _amount(0), _binSize(0), _enable(false), _dialog(UPDATEDIALOG_LOADER), _status(UPDATE_IDLE), _binName(String()), _webServer(nullptr) {
AC_SETLED(ledOn);
rebootOnUpdate(false);
attach(portal);
}
~AutoConnectUpdateAct();
void attach(AutoConnect& portal) override; /**< Attach the update class to AutoConnect */
void enable(void) override; /**< Enable the AutoConnectUpdateAct */
void disable(const bool activate = false) override; /**< Disable the AutoConnectUpdateAct */
void handleUpdate(void) override; /**< Behaves the update process */
bool isEnabled(void) override { return _auxCatalog ? _auxCatalog->isMenu() : false; } /**< Returns current updater effectiveness */
AC_UPDATESTATUS_t status(void) override { return _status; } /**< reports the current update behavior status */
AC_UPDATESTATUS_t update(void) override; /**< behaves update */
String host; /**< Available URL of Update Server */
uint16_t port; /**< Port number of the update server */
String uri; /**< The path on the update server that contains the sketch binary to be updated */
// Indicate the type of progress dialog
typedef enum {
UPDATEDIALOG_LOADER, /**< Cyclic loader icon */
UPDATEDIALOG_METER /**< Progress meter */
} AC_UPDATEDIALOG_t;
protected:
// Attribute definition of the element to be placed on the update page.
typedef struct {
const ACElement_t type;
const char* name; /**< Name to assign to AutoConnectElement */
const char* value; /**< Value owned by an element */
const char* peculiar; /**< Specific ornamentation for the element */
} ACElementProp_t;
// Attributes to treat included update pages as AutoConnectAux.
typedef struct {
const char* uri; /**< URI for the page */
const char* title; /**< Menu title of update page */
const bool menu; /**< Whether to display in menu */
const ACElementProp_t* element;
} ACPage_t;
template<typename T, size_t N> constexpr
size_t lengthOf(T(&)[N]) noexcept { return N; }
void _buildAux(AutoConnectAux* aux, const AutoConnectUpdateAct::ACPage_t* page, const size_t elementNum);
String _onCatalog(AutoConnectAux& catalog, PageArgument& args);
String _onUpdate(AutoConnectAux& update, PageArgument& args);
String _onResult(AutoConnectAux& result, PageArgument& args);
void _inProgress(size_t amount, size_t size); /**< UpdateClass::THandlerFunction_Progress */
std::unique_ptr<AutoConnectAux> _auxCatalog; /**< A catalog page for internally generated update binaries */
std::unique_ptr<AutoConnectAux> _auxProgress; /**< An update in-progress page */
std::unique_ptr<AutoConnectAux> _auxResult; /**< A update result page */
size_t _amount; /**< Received amount bytes */
size_t _binSize; /**< Updater binary size */
private:
void _progress(void); /**< A Handler that returns progress status to the web client */
bool _enable; /**< Validation status of the Update class */
AC_UPDATEDIALOG_t _dialog; /**< The type of updating dialog displayed on the client */
AC_UPDATESTATUS_t _status; /**< Status of update processing during the cycle of receiving a request */
String _binName; /**< .bin name to update */
WebServerClass* _webServer; /**< Hosted WebServer for XMLHttpRequest */
static const ACPage_t _pageCatalog PROGMEM;
static const ACElementProp_t _elmCatalog[] PROGMEM;
static const ACPage_t _pageProgress PROGMEM;
static const ACElementProp_t _elmProgress[] PROGMEM;
static const ACPage_t _pageResult PROGMEM;
static const ACElementProp_t _elmResult[] PROGMEM;
#if defined(ARDUINO_ARCH_ESP8266)
friend ESP8266WebServer;
#elif defined(ARDUINO_ARCH_ESP32)
friend class WebServer;
#endif
};
#endif // !AUTOCONNECT_USE_UPDATE
#endif // _AUTOCONNECTUPDATE_H_
/**
* Define dialogs to operate sketch binary updates operated by the
* AutoConnectUpdate class.
* @file AutoConnectUpdatePage.h
* @author hieromon@gmail.com
* @version 1.0.0
* @date 2019-08-15
* @copyright MIT license.
*/
#ifndef _AUTOCONNECTUPDATEPAGE_H_
#define _AUTOCONNECTUPDATEPAGE_H_
// Define the AUTOCONNECT_URI_UPDATE page to select the sketch binary
// for update and order update execution.
const AutoConnectUpdateAct::ACElementProp_t AutoConnectUpdateAct::_elmCatalog[] PROGMEM = {
{ AC_Element, "binSty", "<style type=\"text/css\">.bins{display:grid;font-size:14px;grid-gap:10px 0;grid-template-columns:1em repeat(4,max-content);overflow-x:auto}.bins input[type=radio]{-moz-appearance:radio;-webkit-appearance:radio;margin:0;vertical-align:middle}.noorder .bins label,.bins span{margin:0 .5em 0 .5em;padding:0;text-align:left}</style>", nullptr },
{ AC_Text, "caption", nullptr, nullptr },
{ AC_Element, "c1", "<div class=\"bins\">", nullptr },
{ AC_Radio, "firmwares", nullptr, nullptr },
{ AC_Element, "c1", "</div>", nullptr },
{ AC_Submit, "update", AUTOCONNECT_BUTTONLABEL_UPDATE, AUTOCONNECT_URI_UPDATE_ACT }
};
const AutoConnectUpdateAct::ACPage_t AutoConnectUpdateAct::_pageCatalog PROGMEM = {
AUTOCONNECT_URI_UPDATE, AUTOCONNECT_MENULABEL_UPDATE, false, AutoConnectUpdateAct::_elmCatalog
};
// Define the AUTOCONNECT_URI_UPDATE_ACT page to display during the
// update process.
const AutoConnectUpdateAct::ACElementProp_t AutoConnectUpdateAct::_elmProgress[] PROGMEM = {
{ AC_Element, "loader", "<style>.loader{border:2px solid #f3f3f3;border-radius:50%;border-top:2px solid #555;width:12px;height:12px;-webkit-animation:spin 1s linear infinite;animation:spin 1s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style>", nullptr },
{ AC_Element, "c1", "<div style=\"display:inline-block\">", nullptr },
{ AC_Element, "binname", nullptr, nullptr },
{ AC_Element, "c2", "&ensp;from&ensp;", nullptr },
{ AC_Element, "url", "</dv>", nullptr },
{ AC_Element, "c3", "<div id=\"progress\">Updating...<span style=\"display:inline-block;vertical-align:middle;margin-left:7px\">", nullptr },
{ AC_Element, "progress_meter", "<meter min=\"0\" />", nullptr },
{ AC_Element, "progress_loader", "<div id=\"ld\" />", nullptr },
{ AC_Element, "c4", "</span></div>", nullptr },
{ AC_Text, "status", nullptr, nullptr },
{ AC_Element, "c5", "<script type=\"text/javascript\">var lap,cls;function rd(){clearInterval(lap),location.href=\"" AUTOCONNECT_URI_UPDATE_RESULT "\"}function bar(){var t=new FormData;t.append(\"op\",\"#s\");var e=new XMLHttpRequest;e.timeout=" AUTOCONNECT_STRING_DEPLOY(AUTOCONNECT_UPDATE_TIMEOUT) ",e.open(\"POST\",\"" AUTOCONNECT_URI_UPDATE_PROGRESS "\",!0),e.onreadystatechange=function(){4==e.readyState&&(200==e.status?(cls=!1,lap=setInterval(upd," AUTOCONNECT_STRING_DEPLOY(AUTOCONNECT_UPDATE_INTERVAL) ")):document.getElementById(\"status\").textContent=\"Could not start (\"+e.status+\"): \"+e.responseText)},e.send(t)}function upd(){if(!cls){var t=new XMLHttpRequest;t.onload=function(){var t=this.responseText.split(\",\");\"#s\"==t[0]?(window.setTimeout(rd()," AUTOCONNECT_STRING_DEPLOY(AUTOCONNECT_UPDATE_DURATION) ")", nullptr },
{ AC_Element, "enable_loader", ",document.getElementById(\"ld\").className=\"loader\"", nullptr },
{ AC_Element, "c6", "):\"#e\"==t[0]?(cls=!0,rd()):\"#p\"==t[0]&&incr(t[1])},t.onerror=function(){console.log(\"http err:%d %s\",t.status,t.responseText)},t.open(\"GET\",\"" AUTOCONNECT_URI_UPDATE_PROGRESS "\",!0),t.send()}}function incr(t){", nullptr },
{ AC_Element, "inprogress_meter", "var e=t.split(\":\"),n=document.getElementById(\"progress\").getElementsByTagName(\"meter\");n[0].setAttribute(\"value\",e[0]),n[0].setAttribute(\"max\",e[1])", nullptr },
{ AC_Element, "c7", "}window.onload=bar;</script>", nullptr }
};
const AutoConnectUpdateAct::ACPage_t AutoConnectUpdateAct::_pageProgress PROGMEM = {
AUTOCONNECT_URI_UPDATE_ACT, AUTOCONNECT_MENULABEL_UPDATE, false, AutoConnectUpdateAct::_elmProgress
};
// Definition of the AUTOCONNECT_URI_UPDATE_RESULT page to notify update results
const AutoConnectUpdateAct::ACElementProp_t AutoConnectUpdateAct::_elmResult[] PROGMEM = {
{ AC_Text, "status", nullptr, nullptr },
{ AC_Element, "restart", "<script type=\"text/javascript\">window.onload=function(){var e=new FormData;e.append(\"op\",\"#r\");var o=new XMLHttpRequest;o.timeout=" AUTOCONNECT_STRING_DEPLOY(AUTOCONNECT_UPDATE_TIMEOUT) ",o.onloadend=function(){setTimeout(\"location.href='" AUTOCONNECT_HOMEURI "'\"," AUTOCONNECT_STRING_DEPLOY(AUTOCONNECT_UPDATE_WAITFORREBOOT) ")},o.open(\"POST\",\"" AUTOCONNECT_URI_UPDATE_PROGRESS "\",!0),o.send(e)};</script>", nullptr }
};
const AutoConnectUpdateAct::ACPage_t AutoConnectUpdateAct::_pageResult PROGMEM = {
AUTOCONNECT_URI_UPDATE_RESULT, AUTOCONNECT_MENULABEL_UPDATE, false, AutoConnectUpdateAct::_elmResult
};
#endif // _AUTOCONNECTUPDATEPAGE_H
/**
* The upload wrapper base class definition and the default up-loader
* class declarations.
* @file AutoConnectUpload.h
* @author hieromon@gmail.com
* @version 0.9.8
* @date 2019-03-19
* @copyright MIT license.
*/
#ifndef _AUTOCONNECTUPLOAD_H_
#define _AUTOCONNECTUPLOAD_H_
#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#include <WebServer.h>
#endif
/**
* Uploader base class. This class is a wrapper for the AutoConnectUpload
* class, and only the upload member function is implemented.
*/
class AutoConnectUploadHandler {
public:
explicit AutoConnectUploadHandler() {}
virtual ~AutoConnectUploadHandler() {}
virtual void upload(const String& requestUri, const HTTPUpload& upload);
protected:
virtual bool _open(const char* filename, const char* mode) = 0;
virtual size_t _write(const uint8_t *buf, const size_t size) = 0;
virtual void _close(const HTTPUploadStatus status) = 0;
};
#endif // !_AUTOCONNECTUPLOAD_H_
/**
* The default upload handler implementation.
* @file AutoConnectUploadImpl.h
* @author hieromon@gmail.com
* @version 1.2.0
* @date 2020-05-29
* @copyright MIT license.
*/
#ifndef _AUTOCONNECTUPLOADIMPL_H_
#define _AUTOCONNECTUPLOADIMPL_H_
#if defined(ARDUINO_ARCH_ESP8266)
#include <core_version.h>
#include <ESP8266WiFi.h>
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#include <SPIFFS.h>
#endif
#include <SPI.h>
#include <SD.h>
#define FS_NO_GLOBALS
#ifdef AUTOCONNECT_USE_SPIFFS
#include <FS.h>
#else
#include <LittleFS.h>
#endif
// Types branching to be code commonly for the file system classes with
// ESP8266 and ESP32.
#if defined(ARDUINO_ARCH_ESP8266)
typedef fs::FS SPIFFST; // SPIFFS:File system class
typedef fs::File SPIFileT; // SPIFFS:File class
typedef SDClass SDClassT; // SD:File system class
typedef File SDFileT; // SD:File class
#elif defined(ARDUINO_ARCH_ESP32)
typedef fs::SPIFFSFS SPIFFST;
typedef fs::File SPIFileT;
typedef fs::SDFS SDClassT;
typedef SDFile SDFileT;
#endif
#include "AutoConnectDefs.h"
#include "AutoConnectUpload.h"
namespace AutoConnectUtil {
AC_HAS_FUNC(end);
template<typename T>
typename std::enable_if<AutoConnectUtil::has_func_end<T>::value, void>::type end(T* media) {
media->end();
}
template<typename T>
typename std::enable_if<!AutoConnectUtil::has_func_end<T>::value, void>::type end(T* media) {
(void)(media);
}
}
/**
* Handles the default upload process depending on the upload status.
* This handler function supports the status of UPLOAD_FILE_START,
* UPLOAD_FILE_WRITE, UPLOAD_FILE_END and calls open, write and
* close processing respectively.
* @param requestUri A reference to the upload request uri.
* @param upload A reference of HTTPUpload entity.
*/
void AutoConnectUploadHandler::upload(const String& requestUri, const HTTPUpload& upload) {
AC_UNUSED(requestUri);
switch (upload.status) {
case UPLOAD_FILE_START: {
String absFilename = "/" + upload.filename;
(void)_open(absFilename.c_str(), "w");
break;
}
case UPLOAD_FILE_WRITE:
(void)_write(upload.buf, (const size_t)upload.currentSize);
break;
case UPLOAD_FILE_ABORTED:
case UPLOAD_FILE_END:
_close(upload.status);
break;
}
}
// Default handler for uploading to the standard SPIFFS class embedded in the core.
class AutoConnectUploadFS : public AutoConnectUploadHandler {
public:
explicit AutoConnectUploadFS(SPIFFST& media) : _media(&media) {}
~AutoConnectUploadFS() { _close(HTTPUploadStatus::UPLOAD_FILE_END); }
protected:
bool _open(const char* filename, const char* mode) override {
#if defined(ARDUINO_ARCH_ESP8266)
if (_media->begin()) {
#elif defined(ARDUINO_ARCH_ESP32)
if (_media->begin(true)) {
#endif
_file = _media->open(filename, mode);
return _file != false;
}
AC_DBG("SPIFFS mount failed\n");
return false;
}
size_t _write(const uint8_t* buf, const size_t size) override {
if (_file)
return _file.write(buf, size);
else
return -1;
}
void _close(const HTTPUploadStatus status) override {
AC_UNUSED(status);
if (_file)
_file.close();
_media->end();
}
private:
SPIFFST* _media;
SPIFileT _file;
};
// Fix to be compatibility with backward for ESP8266 core 2.5.1 or later
// SD pin assignment for AutoConnectFile
#ifndef AUTOCONNECT_SD_CS
#if defined(ARDUINO_ARCH_ESP8266)
#ifndef SD_CHIP_SELECT_PIN
#define SD_CHIP_SELECT_PIN SS
#endif
#define AUTOCONNECT_SD_CS SD_CHIP_SELECT_PIN
#elif defined(ARDUINO_ARCH_ESP32)
#define AUTOCONNECT_SD_CS SS
#endif
#endif // !AUTOCONNECT_SD_CS
// Derivation of SCK frequency and ensuring SD.begin compatibility
#ifdef ARDUINO_ARCH_ESP8266
#if defined(SD_SCK_HZ)
#define AC_SD_SPEED(s) SD_SCK_HZ(s)
#else
#define AC_SD_SPEED(s) s
#endif
#endif
// Default handler for uploading to the standard SD class embedded in the core.
class AutoConnectUploadSD : public AutoConnectUploadHandler {
public:
explicit AutoConnectUploadSD(SDClassT& media, const uint8_t cs = AUTOCONNECT_SD_CS, const uint32_t speed = AUTOCONNECT_SD_SPEED) : _media(&media), _cs(cs), _speed(speed) {}
~AutoConnectUploadSD() { _close(HTTPUploadStatus::UPLOAD_FILE_END); }
protected:
bool _open(const char* filename, const char* mode) override {
const char* sdVerify;
#if defined(ARDUINO_ARCH_ESP8266)
if (_media->begin(_cs, AC_SD_SPEED(_speed))) {
uint8_t oflag = *mode == 'w' ? FILE_WRITE : FILE_READ;
uint8_t sdType = _media->type();
switch (sdType) {
case 1: // SD_CARD_TYPE_SD1
sdVerify = (const char*)"MMC";
break;
case 2: // SD_CARD_TYPE_SD2
sdVerify = (const char*)"SDSC";
break;
case 3: // SD_CARD_TYPE_SDHC
sdVerify = (const char*)"SDHC";
break;
default:
sdVerify = (const char*)"UNKNOWN";
break;
}
#elif defined(ARDUINO_ARCH_ESP32)
if (_media->begin(_cs, SPI, _speed)) {
const char* oflag = mode;
uint8_t sdType = _media->cardType();
switch (sdType) {
case CARD_NONE:
sdVerify = (const char*)"No card";
break;
case CARD_MMC:
sdVerify = (const char*)"MMC";
break;
case CARD_SD:
sdVerify = (const char*)"SDSC";
break;
case CARD_SDHC:
sdVerify = (const char*)"SDHC";
break;
default:
sdVerify = (const char*)"UNKNOWN";
break;
}
#endif
#ifndef AC_DEBUG
AC_UNUSED(sdVerify);
#endif
AC_DBG("%s mounted\n", sdVerify);
_file = _media->open(filename, oflag);
return _file != false;
}
AC_DBG("SD mount failed\n");
return false;
}
size_t _write(const uint8_t* buf, const size_t size) override {
if (_file)
return _file.write(buf, size);
else
return -1;
}
void _close(const HTTPUploadStatus status) override {
AC_UNUSED(status);
if (_file)
_file.close();
AutoConnectUtil::end<SDClassT>(_media);
}
private:
SDClassT* _media;
SDFileT _file;
uint8_t _cs;
uint32_t _speed;
};
#endif // !_AUTOCONNECTUPLOADIMPL_H_
## OTA Updates with AutoConnect using an updateserver.py
Since AutoConnect v1.0.0 release provides a new function for updating the sketch firmware of ESP8266 or ESP32 module via OTA assisted with AutoConnectUpdate class. The [AutoConnectUpdate](https://hieromon.github.io/AutoConnect/apiupdate.html) class is an implementation of the binary sketch updater using the HTTP server mentioned in the OTA Updates of the [ESP8266 Arduino Core documentation](https://arduino-esp8266.readthedocs.io/en/latest/ota_updates/readme.html#ota-updates), which inherits from the ESP8266 HTTPUpdate class (HTTPUpdate class in the case of ESP32). It acts as a client agent for a series of update operations.
<img src="../../mkdocs/images/updatemodel.png" width="540" />
## A simple update server for the AutoConnectUpdate class
The [updateserver.py](https://hieromon.github.io/AutoConnect/otaserver.html#update-server-for-the-autoconnectupdate-class) script is a simple server implemented in Python for OTA updates communicated with the AutoConnectUpdate class and can serve in Python 2 or 3 environment.
### Supported Python environment
* Python 2.7 for [python2/updateserver.py](./python2/updateserver.py)
* Python 3.6 or higher for [python3/updateserver.py](./python3/updateserver.py)
### updateserver.py command line options
```bash
updateserver.py [-h] [--port PORT] [--bind IP_ADDRESS] [--catalog CATALOG] [--log LOG_LEVEL]
```
<dl>
<dt>--help | -h</dt>
<dd>Show help message and exit.</dd>
<dt>--port | -p</dt><dd>Specifies **PORT** number (Default: 8000)</dd>
<dt>--bind | -b</dt><dd>Specifies the IP address to which the update server binds. Usually, it is the host address of the update server. When multiple NICs configured, specify one of the IP addresses. (Default: HOST IP or 127.0.0.0)</dd>
<dt>--catalog | -d</dt>
<dd>Specifies the directory path on the update server that contains the binary sketch files. (Default: The current directory)</dd>
<dt>--log | -l</dt>
<dd>Specifies the level of logging output. It accepts the <a href="https://docs.python.org/3/library/logging.html?highlight=logging#logging-levels">Logging Levels</a> specified in the Python logging module.</dd>
</dl>
### Usage updateserver.py
1. Python
First, prepare a Python environment. It is also possible with a tiny single-board computer like the [raspberry pi](https://www.raspberrypi.org/). Popular distributions such as Ubuntu for Linux include Python. You can easily set up a Python 2 or 3 environment. If you are using a Mac, you already have the Python 2 environment. macOS is equipped with Python 2.7 by default. In the case of Windows OS, it is necessary to install the Python environment intentionally. Please refer to the [Python official page](https://wiki.python.org/moin/BeginnersGuide/Download) to install Python in your environment.
2. Deploy the binary sketch files
Use the Arduino IDE to output a binary file of sketches and deploy it under the update server. The path which specifies for the **--catalog** option of updateServer.py is the path of the binary sketch files you deployed.
3. Start updateserver.py
For example, to start the update server on the host with IP address 172.16.1.10 using 8080 port, execute the following command:
```bash
python updateserver.py --port 8080 --bind 172.16.1.10 --catalog bin --log debug
```
In this example assumes that the binary sketch files are deployed under the path `bin` from the current directory.
Details for the [AutoConnect documentation](https://hieromon.github.io/AutoConnect/otaserver.html).
#!python2.*
"""update server.
"""
from __future__ import absolute_import
import argparse
import hashlib
import httplib
import CGIHTTPServer, SimpleHTTPServer, BaseHTTPServer
import json
import logging
import os
import re
import socket
import time
import urllib2, urllib, urlparse
from itertools import imap
from io import open
class UpdateHttpServer(object):
def __init__(self, port, bind, catalog_dir):
def handler(*args):
UpdateHTTPRequestHandler(catalog_dir, *args)
httpd = BaseHTTPServer.HTTPServer((bind, port), handler)
sa = httpd.socket.getsockname()
logger.info('http server starting {0}:{1} {2}'.format(sa[0], sa[1], catalog_dir))
try:
httpd.serve_forever()
except KeyboardInterrupt:
logger.info('Shutting down...')
httpd.socket.close()
class UpdateHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def __init__(self, catalog_dir, *args):
self.catalog_dir = catalog_dir
BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args)
def do_GET(self):
request_path = urlparse.urlparse(self.path)
if request_path.path == '/_catalog':
err = ''
query = urlparse.urlparse(self.path).query
try:
op = urlparse.parse_qs(query)['op'][0]
if op == 'list':
try:
path = urlparse.parse_qs(query)['path'][0]
except KeyError:
path = '.'
self.__send_dir(path)
result = True
else:
err = '{0} unknown operation'.format(op)
result = False
except KeyError:
err = '{0} invaid catalog request'.format(self.path)
result = False
if not result:
logger.info(err)
self.send_response(httplib.FORBIDDEN, err)
self.end_headers()
else:
self.__send_file(self.path)
def __check_header(self):
ex_headers_templ = ['x-*-STA-MAC', 'x-*-AP-MAC', 'x-*-FREE-SPACE', 'x-*-SKETCH-SIZE', 'x-*-SKETCH-MD5', 'x-*-CHIP-SIZE', 'x-*-SDK-VERSION']
ex_headers = []
ua = re.match('(ESP8266|ESP32)-http-Update', self.headers.get('User-Agent'))
if ua:
arch = ua.group().split('-')[0]
ex_headers = list(imap(lambda x: x.replace('*', arch), ex_headers_templ))
else:
logger.info('User-Agent {0} is not HTTPUpdate'.format(ua))
return False
for ex_header in ex_headers:
if ex_header not in self.headers:
logger.info('Missing header {0} to identify a legitimate request'.format(ex_header))
return False
return True
def __send_file(self, path):
if not self.__check_header():
self.send_response(httplib.FORBIDDEN, 'The request available only from ESP8266 or ESP32 http updater.')
self.end_headers()
return
filename = os.path.join(self.catalog_dir, path.lstrip('/'))
logger.debug('Request file:{0}'.format(filename))
try:
fsize = os.path.getsize(filename)
self.send_response(httplib.OK)
self.send_header('Content-Type', 'application/octet-stream')
self.send_header('Content-Disposition', 'attachment; filename=' + os.path.basename(filename))
self.send_header('Content-Length', fsize)
self.send_header('x-MD5', get_MD5(filename))
self.end_headers()
f = open(filename, 'rb')
self.wfile.write(f.read())
f.close()
except Exception, e:
err = unicode(e)
logger.error(err)
self.send_response(httplib.INTERNAL_SERVER_ERROR, err)
self.end_headers()
def __send_dir(self, path):
content = dir_json(path)
d = json.dumps(content).encode('UTF-8', 'replace')
logger.debug(d)
self.send_response(httplib.OK)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', unicode(len(d)))
self.end_headers()
self.wfile.write(d)
def dir_json(path):
d = list()
for entry in os.listdir(path):
e = {'name': entry}
if os.path.isdir(entry):
e['type'] = "directory"
else:
e['type'] = "file"
if os.path.splitext(entry)[1] == '.bin':
fn = os.path.join(path, entry)
try:
f = open(fn, 'rb')
c = f.read(1)
f.close()
except Exception, e:
logger.info(unicode(e))
c = '\x00'
if c == '\xe9':
e['type'] = "bin"
mtime = os.path.getmtime(fn)
e['date'] = time.strftime('%x', time.localtime(mtime))
e['time'] = time.strftime('%X', time.localtime(mtime))
e['size'] = os.path.getsize(fn)
d.append(e)
return d
def get_MD5(filename):
try:
f = open(filename, 'rb')
bin_file = f.read()
f.close()
md5 = hashlib.md5(bin_file).hexdigest()
return md5
except Exception, e:
logger.error(unicode(e))
return None
def run(port=8000, bind='127.0.0.1', catalog_dir='', log_level=logging.INFO):
logging.basicConfig(level=log_level)
UpdateHttpServer(port, bind, catalog_dir)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--port', '-p', action='store', default=8000, type=int,
help='Port number [default:8000]')
parser.add_argument('--bind', '-b', action='store', default=socket.gethostbyname(socket.gethostname()),
help='Specifies address to which it should bind. [default:HOST IP or 127.0.0.1]')
parser.add_argument('--catalog', '-d', action='store', default=os.getcwdu(),
help='Catalog directory')
parser.add_argument('--log', '-l', action='store', default='INFO',
help='Logging level')
args = parser.parse_args()
loglevel = getattr(logging, args.log.upper(), None)
if not isinstance(loglevel, int):
raise ValueError('Invalid log level: %s' % args.log)
logger = logging.getLogger(__name__)
run(args.port, args.bind, args.catalog, loglevel)
#!python3.*
"""update server.
"""
import argparse
import hashlib
import http.server
import json
import logging
import os
import re
import socket
import time
import urllib.parse
class UpdateHttpServer:
def __init__(self, port, bind, catalog_dir):
def handler(*args):
UpdateHTTPRequestHandler(catalog_dir, *args)
httpd = http.server.HTTPServer((bind, port), handler)
sa = httpd.socket.getsockname()
logger.info('http server starting {0}:{1} {2}'.format(sa[0], sa[1], catalog_dir))
try:
httpd.serve_forever()
except KeyboardInterrupt:
logger.info('Shutting down...')
httpd.socket.close()
class UpdateHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
def __init__(self, catalog_dir, *args):
self.catalog_dir = catalog_dir
http.server.BaseHTTPRequestHandler.__init__(self, *args)
def do_GET(self):
request_path = urllib.parse.urlparse(self.path)
if request_path.path == '/_catalog':
err = ''
query = urllib.parse.urlparse(self.path).query
try:
op = urllib.parse.parse_qs(query)['op'][0]
if op == 'list':
try:
path = urllib.parse.parse_qs(query)['path'][0]
except KeyError:
path = '.'
self.__send_dir(path)
result = True
else:
err = '{0} unknown operation'.format(op)
result = False
except KeyError:
err = '{0} invaid catalog request'.format(self.path)
result = False
if not result:
logger.info(err)
self.send_response(http.HTTPStatus.FORBIDDEN, err)
self.end_headers()
else:
self.__send_file(self.path)
def __check_header(self):
ex_headers_templ = ['x-*-STA-MAC', 'x-*-AP-MAC', 'x-*-FREE-SPACE', 'x-*-SKETCH-SIZE', 'x-*-SKETCH-MD5', 'x-*-CHIP-SIZE', 'x-*-SDK-VERSION']
ex_headers = []
ua = re.match('(ESP8266|ESP32)-http-Update', self.headers.get('User-Agent'))
if ua:
arch = ua.group().split('-')[0]
ex_headers = list(map(lambda x: x.replace('*', arch), ex_headers_templ))
else:
logger.info('User-Agent {0} is not HTTPUpdate'.format(ua))
return False
for ex_header in ex_headers:
if ex_header not in self.headers:
logger.info('Missing header {0} to identify a legitimate request'.format(ex_header))
return False
return True
def __send_file(self, path):
if not self.__check_header():
self.send_response(http.HTTPStatus.FORBIDDEN, 'The request available only from ESP8266 or ESP32 http updater.')
self.end_headers()
return
filename = os.path.join(self.catalog_dir, path.lstrip('/'))
logger.debug('Request file:{0}'.format(filename))
try:
fsize = os.path.getsize(filename)
self.send_response(http.HTTPStatus.OK)
self.send_header('Content-Type', 'application/octet-stream')
self.send_header('Content-Disposition', 'attachment; filename=' + os.path.basename(filename))
self.send_header('Content-Length', fsize)
self.send_header('x-MD5', get_MD5(filename))
self.end_headers()
f = open(filename, 'rb')
self.wfile.write(f.read())
f.close()
except Exception as e:
err = str(e)
logger.error(err)
self.send_response(http.HTTPStatus.INTERNAL_SERVER_ERROR, err)
self.end_headers()
def __send_dir(self, path):
content = dir_json(path)
d = json.dumps(content).encode('UTF-8', 'replace')
logger.debug(d)
self.send_response(http.HTTPStatus.OK)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(d)))
self.end_headers()
self.wfile.write(d)
def dir_json(path):
d = list()
for entry in os.listdir(path):
e = {'name': entry}
if os.path.isdir(entry):
e['type'] = "directory"
else:
e['type'] = "file"
if os.path.splitext(entry)[1] == '.bin':
fn = os.path.join(path, entry)
try:
f = open(fn, 'rb')
c = f.read(1)
f.close()
except Exception as e:
logger.info(str(e))
c = b'\x00'
if c == b'\xe9':
e['type'] = "bin"
mtime = os.path.getmtime(fn)
e['date'] = time.strftime('%x', time.localtime(mtime))
e['time'] = time.strftime('%X', time.localtime(mtime))
e['size'] = os.path.getsize(fn)
d.append(e)
return d
def get_MD5(filename):
try:
f = open(filename, 'rb')
bin_file = f.read()
f.close()
md5 = hashlib.md5(bin_file).hexdigest()
return md5
except Exception as e:
logger.error(str(e))
return None
def run(port=8000, bind='127.0.0.1', catalog_dir='', log_level=logging.INFO):
logging.basicConfig(level=log_level)
UpdateHttpServer(port, bind, catalog_dir)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--port', '-p', action='store', default=8000, type=int,
help='Port number [default:8000]')
parser.add_argument('--bind', '-b', action='store', default=socket.gethostbyname(socket.gethostname()),
help='Specifies address to which it should bind. [default:HOST IP or 127.0.0.1]')
parser.add_argument('--catalog', '-d', action='store', default=os.getcwd(),
help='Catalog directory')
parser.add_argument('--log', '-l', action='store', default='INFO',
help='Logging level')
args = parser.parse_args()
loglevel = getattr(logging, args.log.upper(), None)
if not isinstance(loglevel, int):
raise ValueError('Invalid log level: %s' % args.log)
logger = logging.getLogger(__name__)
run(args.port, args.bind, args.catalog, loglevel)
/**
* PageBuilder class implementation which includes the class methods of
* PageElement.
* @file PageBuilder.cpp
* @author hieromon@gmail.com
* @version 1.4.2
* @date 2020-05-25
* @copyright MIT license.
*/
#include "PageBuilder.h"
#include "PageStream.h"
#if defined(ARDUINO_ARCH_ESP8266)
#ifdef PB_USE_SPIFFS
#include <FS.h>
namespace PageBuilderFS { FS& flash = SPIFFS; };
#else
#include <LittleFS.h>
namespace PageBuilderFS { FS& flash = LittleFS; };
#endif
#elif defined(ARDUINO_ARCH_ESP32)
#include <FS.h>
#include <SPIFFS.h>
namespace PageBuilderFS { fs::SPIFFSFS& flash = SPIFFS; };
#endif
// A maximum length of the content block to switch to chunked transfer.
#define MAX_CONTENTBLOCK_SIZE 1270
/**
* HTTP header structure.
*/
typedef struct {
const char* _field; /**< HTTP header field */
const char* _directives; /**< HTTP header directives */
} HTTPHeaderS;
/**
* No cache control http response headers.
* The definition of the response header of this fixed character string is
* used in the sendNocacheHeader method.
*/
static const HTTPHeaderS _HttpHeaderNocache[] PROGMEM = {
{ "Cache-Control", "no-cache, no-store, must-revalidate" },
{ "Pragma", "no-cache" },
{ "Expires", "-1" }
};
// PageBuilder class methods
/**
* Returns whether this page handle HTTP request.<br>
* Matches HTTP methods and uri defined in the PageBuilder constructor and
* returns whether this page should handle the request. This function
* overrides the canHandle method of the RequestHandler class.
* @param requestMethod The http method that caused this http request.
* @param requestUri The uri of this http request.
* @retval true This page can handle this request.
* @retval false This page does not correspond to this request.
*/
bool PageBuilder::canHandle(HTTPMethod requestMethod, String requestUri) {
if (_canHandle) {
return _canHandle(requestMethod, requestUri);
}
else {
if (_method != HTTP_ANY && _method != requestMethod)
return false;
else if (requestUri != _uri)
return false;
return true;
}
}
/**
* Returns whether the page can be uploaded.<br>
* However, since the PageBuilder class does not support uploading, it always
* returns false. This function overrides the canUpload method of the
* RequestHandler class.
* @param requestUri The uri of this upload request.
* @retval false This page cannot receive the upload request.
*/
bool PageBuilder::canUpload(String uri) {
PB_DBG("%s upload request\n", uri.c_str());
if (!_upload || !canHandle(HTTP_POST, uri))
return false;
return true;
}
/**
* Invokes a user sketch function which would be registered by the
* onUpload function to process the received upload data.
* @param server A reference of ESP8266WebServer.
* @param requestUri Request uri of this time.
* @param upload A reference of the context of the HTTPUpload structure.
*/
void PageBuilder::upload(WebServerClass& server, String requestUri, HTTPUpload& upload) {
(void)server;
if (canUpload(requestUri))
_upload(requestUri, upload);
}
/**
* Save the parameters for authentication.
* @param username A user name for authentication.
* @param password A password
* @param mode Authentication method
* @param realm A realm
* @param authFail Message string for authentication failed
*/
void PageBuilder::authentication(const char* username, const char* password, HTTPAuthMethod mode, const char* realm, const String& authFail) {
_auth = mode;
_username.reset(_digestKey(username));
_password.reset(_digestKey(password));
_realm.reset(_digestKey(realm));
_fails = String(authFail.c_str());
}
/**
* Hold an authentication parameter
* @param key Authentication parameter string
* @return A pointer of a held string
*/
char* PageBuilder::_digestKey(const char* key) {
if (key && strlen(key)) {
char* cb = new char[strlen(key) + sizeof('\0')];
strcpy(cb, key);
return cb;
}
return nullptr;
}
/**
* Generates HTML content and sends it to the client in response.<br>
* This function overrides the handle method of the RequestHandler class.
* @param server A reference of ESP8266WebServer.
* @param requestMethod Method of http request that originated this response.
* @param requestUri Request uri of this time.
* @retval true A response send.
* @retval false This request could not handled.
*/
bool PageBuilder::_sink(int code, WebServerClass& server) { //, HTTPMethod requestMethod, String requestUri) {
// Retrieve request arguments
PageArgument args;
for (uint8_t i = 0; i < server.args(); i++)
args.push(server.argName(i), server.arg(i));
// Invoke page building function
_cancel = false;
// If the page is must-revalidate, send a header
if (_noCache)
sendNocacheHeader(server);
// send http content to client
if (!_cancel) {
String content; // Content is available only in a NOT _cancel block
size_t contLen = 0;
bool _chunked = (_sendEnc == PB_Chunk);
if (_sendEnc == PB_ByteStream || _sendEnc == PB_Auto) {
// Build the content, and determine the transfer mode by
// the length of the built content.
content = build(args);
contLen = content.length();
if (_sendEnc == PB_Auto && contLen >= MAX_CONTENTBLOCK_SIZE)
_chunked = true;
}
PB_DBG("Free heap:%d, content len.:", ESP.getFreeHeap());
if (_chunked)
PB_DBG_DUMB("%s\n", "unknown");
else
PB_DBG_DUMB("%d\n", contLen);
PB_DBG("Res:%d, Chunked:%d\n", code, _sendEnc);
// Start content transfer, switch the transfer method depending
// on whether it is chunked transfer or byte stream.
if (_chunked) {
PB_DBG("Transfer-Encoding:chunked\n");
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
server.send(code, F("text/html"), _emptyString);
if (_sendEnc == PB_Chunk) {
// Chunk block is a PageElement unit.
for (uint8_t i = 0; i < _element.size(); i++) {
PageElement& element = _element[i].get();
content = PageElement::build(element.mold(), element.source(), args);
if (content.length())
server.sendContent(content);
}
}
else {
// Here, PB_Auto turned to chunk mode.
size_t pos = 0;
while (pos < contLen) {
String contBuffer = content.substring(pos, pos + MAX_CONTENTBLOCK_SIZE);
server.sendContent(contBuffer);
pos += MAX_CONTENTBLOCK_SIZE;
}
}
server.sendContent(_emptyString);
}
else {
if (_sendEnc == PB_ByteStream || contLen > MAX_CONTENTBLOCK_SIZE) {
PageStream contStream(content);
server.streamFile(contStream, F("text/html"));
server.client().flush();
} else {
server.setContentLength(contLen);
server.send(code, F("text/html"), content);
}
}
}
return true;
}
/**
* The page builder handler generates HTML based on PageElement and sends
* it to the client.
* @param server A reference of ESP8266WebServer.
* @param requestMethod Method of http request that originated this response.
* @param requestUri Request uri of this time.
* @retval true A response send.
* @retval false This request could not handled.
*/
bool PageBuilder::handle(WebServerClass& server, HTTPMethod requestMethod, String requestUri) {
// Screening the available request
if (!canHandle(requestMethod, requestUri))
return false;
if (_username) {
// Should be able to authenticate with the specified username.
if (!server.authenticate(_username.get(), _password.get())) {
PB_DBG("failed to authenticate\n");
server.requestAuthentication(_auth, _realm.get(), _fails);
return true;
}
}
// Throw with 200 response
return _sink(200, server);
}
/**
* Send a 404 response.
*/
void PageBuilder::exit404(void) {
if (_server != nullptr) {
_noCache = true;
// Throw with 404 response
_sink(404, *_server);
}
}
/**
* Dispose collection for cataloged PageElement.
*/
void PageBuilder::clearElement() {
_element.clear();
PageElementVT().swap(_element);
}
/**
* Send a http header for the page to be must-revalidate on the client.
* @param server A reference of ESP8266WebServer.
*/
void PageBuilder::sendNocacheHeader(WebServerClass& server) {
for (uint8_t i = 0; i < sizeof(_HttpHeaderNocache) / sizeof(HTTPHeaderS); i++)
server.sendHeader(_HttpHeaderNocache[i]._field, _HttpHeaderNocache[i]._directives);
}
/**
* Register the not found page to ESP8266Server.
* @param server A reference of ESP8266WebServer.
*/
void PageBuilder::atNotFound(WebServerClass& server) {
_server = &server;
server.onNotFound(std::bind(&PageBuilder::exit404, this));
}
/**
* A wrapper function for making response content without specifying the
* parameter of http request.
* This function is called from other than the On handle action of
* ESP8266WebServer and assumes execution of content creation only by PageElement.
* @retval String of content built by the instance of PageElement.
*/
String PageBuilder::build(void) {
PageArgument args;
return build(args);
}
/**
* Build html content with handling the PageElement elements.<br>
* Assemble the content by calling the build method of all owning PageElement
* and concatenating the returned string.
* @param args URI parameter when this page is requested.
* @retval A html content string.
*/
String PageBuilder::build(PageArgument& args) {
String content = String("");
if (_rSize > 0) {
if (content.reserve(_rSize)) {
PB_DBG("Content buffer %ld reserved\n", (long)_rSize);
}
else {
PB_DBG("Content buffer cannot reserve(%ld)\n", (long)_rSize);
}
}
for (uint8_t i = 0; i < _element.size(); i++) {
PageElement& element = _element[i].get();
String segment = PageElement::build(element.mold(), element.source(), args);
if (segment.length()) {
if (!content.concat(segment)) {
PB_DBG("Content lost, length:%d, free heap:%ld\n", segment.length(), (long)ESP.getFreeHeap());
}
}
}
return content;
}
/**
* Initialize an empty string to allow returning const String& with nothing.
*/
const String PageBuilder::_emptyString = String("");
// PageElement class methods.
/**
* PageElement destructor
*/
PageElement::~PageElement() {
_source.clear();
TokenVT().swap(_source);
_mold = nullptr;
}
/***
* Add new token to the page element.
* A token is pare of a token string and handler function.
* @param token A token string.
* @param handler A handler function.
*/
void PageElement::addToken(const String& token, HandleFuncT handler) {
TokenSourceST source = TokenSourceST();
source._token = token;
source._builder = handler;
_source.push_back(source);
}
/***
* @brief Build html source.<br>
* It is a wrapper entry for calling the static PageElement::build method.
* @retval A string generated from the mold of this instance.
*/
String PageElement::build() {
PageArgument args;
return String(PageElement::build(_mold, _source, args));
}
/**
* Generate a actual string from the mold including the token. also, this
* function is static to reduce the heap size.
* @param mold A pointer of constant mold character array. A string
* following the "file:" prefix indicates the filename of the SPIFFS file system.
* @param tokenSource A structure that anchors user functions which processes
* tokens defined in the mold.
* @param args PageArgument instance when this handler requested.
* @retval A string containing the content of the token actually converted
* by the user function.
*/
String PageElement::build(const char* mold, TokenVT tokenSource, PageArgument& args) {
int contextLength;
int scanIndex = 0;
String templ = FPSTR(mold);
String content = String("");
// Determining the origin of the mold.
// When the mold parameter has the prefix "file:", read the mold source
// from the file.
if (templ.startsWith(PAGEELEMENT_FILE)) {
File mf = PageBuilderFS::flash.open(templ.substring(strlen(PAGEELEMENT_FILE)), "r");
if (mf) {
templ = mf.readString();
mf.close();
}
else
templ = String("");
}
contextLength = templ.length();
while (contextLength > 0) {
String token;
int tokenStart, tokenEnd;
// Extract the braced token
if ((tokenStart = templ.indexOf("{{", scanIndex)) >= 0) {
tokenEnd = templ.indexOf("}}", tokenStart);
if (tokenEnd > tokenStart)
token = templ.substring(tokenStart + 2, tokenEnd);
else
tokenStart = tokenEnd = templ.length();
}
else {
tokenStart = tokenEnd = templ.length();
}
// Materialize the template which would be stored to content
// content += templ.substring(scanIndex, tokenStart);
bool grown = content.concat(templ.substring(scanIndex, tokenStart));
if (grown) {
scanIndex = tokenEnd + 2;
contextLength = templ.length() - scanIndex;
// Invoke the callback function corresponding to the extracted token
for (uint8_t i = 0; i < tokenSource.size(); ++i)
if (tokenSource[i]._token == token) {
grown = content.concat(tokenSource[i]._builder(args));
break;
}
}
if (!grown) {
PB_DBG("Failed building, free heap:%ld\n", (long)ESP.getFreeHeap());
break;
}
}
PB_DBG("at leaving build: %ld free\n", (long)ESP.getFreeHeap());
return content;
}
// PageArgument class methods.
/**
* Returns a parameter string specified argument name.
* @param name A parameter argument name.
* @retval A parameter value string.
*/
String PageArgument::arg(const String& name) {
for (uint8_t i = 0; i < size(); i++) {
RequestArgument* argItem = item(i);
if (argItem->_key == name)
return argItem->_value;
}
return String();
}
/**
* Returns a parameter string specified index of arguments array.
* @param i Index of argument array.
* @retval A parameter value string.
*/
String PageArgument::arg(int i) {
if ((size_t)i < size()) {
RequestArgument* argItem = item(i);
return argItem->_value;
}
return String();
}
/**
* Returns a argument string specified index of arguments array.
* @param i Index of argument array.
* @retval A string of argument name.
*/
String PageArgument::argName(int i) {
if ((size_t)i < size()) {
RequestArgument* argItem = item(i);
return argItem->_key;
}
return String();
}
/**
* Returns number of parameters of this http request.
* @retval Number of parameters.
*/
int PageArgument::args() {
int size = 0;
RequestArgumentSL* argList = _arguments.get();
while (argList != nullptr) {
size++;
argList = argList->_next.get();
}
return size;
}
/**
* Returns whether the http request to PageBuilder that invoked this PageElement
* contained parameters.
* @retval true This http request contains parameter(s).
* @retval false This http request has no parameter.
*/
bool PageArgument::hasArg(const String& name) {
for (uint8_t i = 0; i < size(); i++) {
RequestArgument* argument = item(i);
if (argument == nullptr)
return false;
if (argument->_key == name)
return true;
}
return false;
}
/**
* Append argument of http request consisting of parameter name and
* argument pair.
* @param key A parameter name string.
* @param value A parameter value string.
*/
void PageArgument::push(const String& key, const String& value) {
RequestArgument* newArg = new RequestArgument();
newArg->_key = key;
newArg->_value = value;
RequestArgumentSL* newList = new RequestArgumentSL();
newList->_argument.reset(newArg);
newList->_next.reset(nullptr);
RequestArgumentSL* argList = _arguments.get();
if (argList == nullptr) {
_arguments.reset(newList);
}
else {
while (argList->_next.get() != nullptr)
argList = argList->_next.get();
argList->_next.reset(newList);
}
}
/**
* Returns a pointer to RequestArgument instance specified index of
* parameters array.
* @param index A index of parameter arguments array.
* @retval A pointer to RequestArgument.
*/
RequestArgument* PageArgument::item(int index) {
RequestArgumentSL* argList = _arguments.get();
while (index--) {
if (argList == nullptr)
break;
argList = argList->_next.get();
}
if (argList != nullptr)
return argList->_argument.get();
else
return nullptr;
}
/**
* Declaration of PageBuilder class and accompanying PageElement, PageArgument class.
* @file PageBuilder.h
* @author hieromon@gmail.com
* @version 1.4.2
* @date 2020-05-25
* @copyright MIT license.
*/
#ifndef _PAGEBUILDER_H
#define _PAGEBUILDER_H
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <functional>
#include <vector>
#include <memory>
#include <Stream.h>
#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
using WebServerClass = ESP8266WebServer;
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#include <WebServer.h>
using WebServerClass = WebServer;
#endif
// Uncomment the following PB_DEBUG to enable debug output.
// #define PB_DEBUG
// SPIFFS has deprecated on EP8266 core. This flag indicates that
// the migration to LittleFS has not completed.
// Uncomment the following PB_USE_SPIFFS to enable SPIFFS.
// #define PB_USE_SPIFFS
// Debug output destination can be defined externally with PB_DEBUG_PORT
#ifndef PB_DEBUG_PORT
#define PB_DEBUG_PORT Serial
#endif // !PB_DEBUG_PORT
#ifdef PB_DEBUG
#define PB_DBG_DUMB(fmt, ...) do {PB_DEBUG_PORT.printf(PSTR(fmt), ## __VA_ARGS__ );} while (0)
#define PB_DBG(fmt, ...) do {PB_DEBUG_PORT.printf(PSTR("[PB] " fmt), ## __VA_ARGS__ );} while (0)
#else
#define PB_DBG_DUMB(...) do {} while (0)
#define PB_DBG(...) do {} while (0)
#endif // !PB_DEBUG
#define PAGEELEMENT_FILE "file:"
/** HTTP get or post method argument pair structure. */
typedef struct _RequestArgumentS {
String _key; /**< Parameter name */
String _value; /**< Parameter value */
} RequestArgument;
/** Transfer encoding type with ESP8266WebSever::sendcontent */
typedef enum {
PB_Auto, /**< Use chunked transfer */
PB_ByteStream, /**< Specify content length */
PB_Chunk /**< Dynamically change the transfer encoding according to the content length. */
} TransferEncoding_t;
/**
* Stores the uri parameter or POST argument that occurred in the http request.
*/
class PageArgument {
public:
PageArgument() : _arguments(nullptr) {}
PageArgument(const String& key, const String& value) : _arguments(nullptr) { push(key, value); }
~PageArgument() {}
String arg(const String& name);
String arg(int i);
String argName(int i);
int args(void);
size_t size(void) { return (size_t)args(); }
bool hasArg(const String& name);
void push(const String& key, const String& value);
protected:
/** RequestArgument element list structure */
typedef struct _RequestArgumentSL {
std::unique_ptr<RequestArgument> _argument; /**< A unique pointer to a RequestArgument */
std::unique_ptr<_RequestArgumentSL> _next; /**< Pointer to the next element */
} RequestArgumentSL;
/** Root element of the list of RequestArgument */
std::unique_ptr<RequestArgumentSL> _arguments;
private:
RequestArgument* item(int index);
};
/** Wrapper type definition of handler function to handle token. */
typedef std::function<String(PageArgument&)> HandleFuncT;
/** Structure with correspondence of token and handler defined in PageElement. */
typedef struct {
String _token; /**< Token string */
HandleFuncT _builder; /**< correspondence handler function */
} TokenSourceST;
/** TokenSourceST linear container type.
* Elements of tokens and handlers usually contained in PageElement are
* managed linearly as a container using std::vector.
*/
typedef std::vector<TokenSourceST> TokenVT;
/**
* PageElement class have parts of a HTML page and the components of the part
* to be processed at specified position in the HTML as the token.
*/
class PageElement {
public:
PageElement() : _mold(nullptr) {}
explicit PageElement(const char* mold) : _mold(mold), _source(std::vector<TokenSourceST>()) {}
PageElement(const char* mold, TokenVT source) : _mold(mold), _source(source) {}
virtual ~PageElement();
const char* mold(void) { return _mold; }
TokenVT source(void) { return _source; }
String build(void);
static String build(const char* mold, TokenVT tokenSource, PageArgument& args);
void setMold(const char* mold) { _mold = mold; }
void addToken(const String& token, HandleFuncT handler);
protected:
const char* _mold; //*< A pointer to HTML model string(char array). */
TokenVT _source; //*< Container of processable token and handler function. */
};
/**
* PageElement container.
* The PageBuilder class treats multiple PageElements constituting a html
* page as a reference container as std::reference_wrapper.*/
typedef std::vector<std::reference_wrapper<PageElement>> PageElementVT;
/** The type of user-owned function for preparing the handling of current URI. */
typedef std::function<bool(HTTPMethod, String)> PrepareFuncT;
/**
* PageBuilder class is to make easy to assemble and output html stream
* of web page. The page builder class includes the uri of the page,
* the PageElement indicating the HTML model constituting the page, and
* the on handler called from the ESP8266WebServer class.
* This class inherits the RequestHandler class of the ESP8266WebServer class.
*/
class PageBuilder : public RequestHandler {
public:
PageBuilder() : _method(HTTP_ANY), _upload(nullptr), _noCache(true), _cancel(false), _sendEnc(PB_Auto), _rSize(0), _server(nullptr), _canHandle(nullptr) {}
explicit PageBuilder(PageElementVT element, HTTPMethod method = HTTP_ANY, bool noCache = true, bool cancel = false, TransferEncoding_t chunked = PB_Auto) :
_element(element),
_method(method),
_upload(nullptr),
_noCache(noCache),
_cancel(cancel),
_sendEnc(chunked),
_rSize(0),
_server(nullptr),
_canHandle(nullptr) {}
PageBuilder(const char* uri, PageElementVT element, HTTPMethod method = HTTP_ANY, bool noCache = true, bool cancel = false, TransferEncoding_t chunked = PB_Auto) :
_uri(String(uri)),
_element(element),
_method(method),
_upload(nullptr),
_noCache(noCache),
_cancel(cancel),
_sendEnc(chunked),
_rSize(0),
_server(nullptr),
_canHandle(nullptr) {}
virtual ~PageBuilder() { _server = nullptr; clearElement(); _username.reset(); _password.reset(); _realm.reset(); }
/** The type of user-owned function for uploading. */
typedef std::function<void(const String&, const HTTPUpload&)> UploadFuncT;
virtual bool canHandle(HTTPMethod requestMethod, String requestUri) override;
virtual bool canUpload(String uri) override;
bool handle(WebServerClass& server, HTTPMethod requestMethod, String requestUri) override;
virtual void upload(WebServerClass& server, String requestUri, HTTPUpload& upload) override;
void setUri(const char* uri) { _uri = String(uri); }
const char* uri() { return _uri.c_str(); }
void insert(WebServerClass& server) { server.addHandler(this); }
void addElement(PageElement& element) { _element.push_back(element); }
void clearElement();
static void sendNocacheHeader(WebServerClass& server);
String build(void);
String build(PageArgument& args);
void atNotFound(WebServerClass& server);
void exit404(void);
void exitCanHandle(PrepareFuncT prepareFunc) { _canHandle = prepareFunc; }
virtual void onUpload(UploadFuncT uploadFunc) { _upload = uploadFunc; }
void cancel() { _cancel = true; }
void chunked(const TransferEncoding_t devid) { _sendEnc = devid; }
void reserve(size_t size) { _rSize = size; }
void authentication(const char* username, const char* password, HTTPAuthMethod mode = BASIC_AUTH, const char* realm = NULL, const String& authFail = String(""));
protected:
String _uri; /**< uri of this page */
PageElementVT _element; /**< PageElement container */
HTTPMethod _method; /**< Method of http request to which this page applies. */
UploadFuncT _upload; /**< 'upload' user owned function */
private:
bool _sink(int code, WebServerClass& server); /**< send Content */
char* _digestKey(const char* key); /**< save authentication parameter */
bool _noCache; /**< A flag for must-revalidate cache control response */
bool _cancel; /**< Automatic send cancellation */
TransferEncoding_t _sendEnc; /**< Use chunked sending */
HTTPAuthMethod _auth; /**< Authentication method */
size_t _rSize; /**< Reserved buffer size for content building */
WebServerClass* _server;
PrepareFuncT _canHandle; /**< 'canHandle' user owned function */
std::unique_ptr<char[]> _username; /**< A user name for authentication */
std::unique_ptr<char[]> _password; /**< A password for authentication */
std::unique_ptr<char[]> _realm; /**< realm for DIGEST */
String _fails; /**< A message for authentication failed */
static const String _emptyString;
};
#endif
/**
* An implementation of a actual function of PageStream class.
* @file PageStream.cpp
* @author hieromon@gmail.com
* @version 1.2.0
* @date 2018-12-01
* @copyright MIT license.
*/
#include "PageStream.h"
/**
* Read into the buffer from the String.
* @param buffer A pointer of the buffer to be read string.
* @param length Maximum reading size.
* @return Number of bytes readed.
*/
size_t PageStream::readBytes(char *buffer, size_t length) {
size_t count = 0;
while (count < length) {
if (_pos >= _content.length())
break;
*buffer++ = _content[_pos++];
count++;
}
return count;
}
/**
* Declaration of PaguStream class.
* @file PageStream.h
* @author hieromon@gmail.com
* @version 1.3.2
* @date 2019-02-07
* @copyright MIT license.
*/
#ifndef _PAGESTREAM_H
#define _PAGESTREAM_H
#include <Stream.h>
//#include <StreamString.h>
/**
* An implementation of a class with a Stream interface to pass an
* instance of that class to ESP8266WebServer::streamFile.
* @param content A reference of String which contains sending HTML.
*/
class PageStream : public Stream {
public:
explicit PageStream(String& str) : _content(str), _pos(0) {}
virtual ~PageStream() {}
virtual int available() { return _content.length() - _pos; }
virtual void flush() {}
virtual const String& name() const { static const String _empty; return _empty; }
virtual int peek() { return _pos < _content.length() ? _content[_pos] : -1; }
virtual int read() { return _pos < _content.length() ? _content[_pos++] : -1; }
virtual size_t readBytes(char* buffer, size_t length);
virtual size_t size() const { return _content.length(); }
virtual size_t write(uint8_t c) { _content += static_cast<char>(c); return 1; }
private:
String& _content;
size_t _pos;
};
#endif // !_PAGESTREAM_H
/**
* 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
// "<br/><input id='{i}' name='{n}' maxlength='{l}' value='{v}' {c}>";
// 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<infos;i++){
if(infoids[i] != NULL) page += getInfoData(infoids[i]);
}
page += F("</dl>");
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+"<br/>"+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 <rom/rtc.h>
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<void(WiFiManager*)> 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<void()> 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<void()> 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<void()> 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<void()> 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<void()> 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<const char *> 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<const char *>& menu [description]
*/
void WiFiManager::setMenu(std::vector<const char *>& 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 <typename Generic>
void WiFiManager::DEBUG_WM(Generic text) {
DEBUG_WM(DEBUG_NOTIFY,text,"");
}
template <typename Generic>
void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text) {
if(_debugLevel >= level) DEBUG_WM(level,text,"");
}
template <typename Generic, typename Genericb>
void WiFiManager::DEBUG_WM(Generic text,Genericb textb) {
DEBUG_WM(DEBUG_NOTIFY,text,textb);
}
template <typename Generic, typename Genericb>
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("&","&amp;");
str.replace("<","&lt;");
str.replace(">","&gt;");
// str.replace("'","&#39;");
// str.replace("\"","&quot;");
// str.replace("/": "&#x2F;");
// str.replace("`": "&#x60;");
// str.replace("=": "&#x3D;");
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<char*>(tmp));
#elif defined(ESP32)
if(persistent){
wifi_config_t conf;
esp_wifi_get_config(WIFI_IF_STA, &conf);
return String(reinterpret_cast<const char*>(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<char*>(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<char*>(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<char*>(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
/**
* 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 <core_version.h>
#endif
#include <vector>
// #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 <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#ifdef WM_MDNS
#include <ESP8266mDNS.h>
#endif
#define WIFI_getChipId() ESP.getChipId()
#define WM_WIFIOPEN ENC_TYPE_NONE
#elif defined(ESP32)
#include <WiFi.h>
#include <esp_wifi.h>
#define WIFI_getChipId() (uint32_t)ESP.getEfuseMac()
#define WM_WIFIOPEN WIFI_AUTH_OPEN
#ifndef WEBSERVER_H
#ifdef WM_WEBSERVERSHIM
#include <WebServer.h>
#else
#include <ESP8266WebServer.h>
// Forthcoming official ? probably never happening
// https://github.com/esp8266/ESPWebServer
#endif
#endif
#ifdef WM_ERASE_NVS
#include <nvs.h>
#include <nvs_flash.h>
#endif
#ifdef WM_MDNS
#include <ESPmDNS.h>
#endif
#ifdef WM_RTC
#include <rom/rtc.h>
#endif
#else
#endif
#include <DNSServer.h>
#include <memory>
#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<void(WiFiManager*)> func );
//called after webserver has started
void setWebServerCallback( std::function<void()> func );
//called when settings reset have been triggered
void setConfigResetCallback( std::function<void()> func );
//called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) )
void setSaveConfigCallback( std::function<void()> func );
//called when settings have been changed and connection was successful
void setSaveParamsCallback( std::function<void()> func );
//called when settings before have been changed and connection was successful
void setPreSaveConfigCallback( std::function<void()> 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<const char*>& 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> dnsServer;
#if defined(ESP32) && defined(WM_WEBSERVERSHIM)
using WM_WebServer = WebServer;
#else
using WM_WebServer = ESP8266WebServer;
#endif
std::unique_ptr<WM_WebServer> server;
private:
std::vector<uint8_t> _menuIds;
std::vector<const char *> _menuIdsParams = {"wifi","param","info","exit"};
std::vector<const char *> _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 <typename Generic>
void DEBUG_WM(Generic text);
template <typename Generic>
void DEBUG_WM(wm_debuglevel_t level,Generic text);
template <typename Generic, typename Genericb>
void DEBUG_WM(Generic text,Genericb textb);
template <typename Generic, typename Genericb>
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<void(WiFiManager*)> _apcallback;
std::function<void()> _webservercallback;
std::function<void()> _savewificallback;
std::function<void()> _presavecallback;
std::function<void()> _saveparamscallback;
std::function<void()> _resetcallback;
template <class T>
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
/**
* 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 = "<!DOCTYPE html><html lang='en'><head><meta name='format-detection' content='telephone=no'><meta charset='UTF-8'><meta name='viewport' content='width=device-width,initial-scale=1,user-scalable=no'/><title>{v}</title>";
const char HTTP_SCRIPT[] PROGMEM = "<script>function c(l){"
"document.getElementById('s').value=l.innerText||l.textContent;"
"p = l.nextElementSibling.classList.contains('l');"
"document.getElementById('p').disabled = !p;"
"if(p)document.getElementById('p').focus();}</script>";
const char HTTP_HEAD_END[] PROGMEM = "</head><body class='{c}'><div class='wrap'>";
// example of embedded logo, base64 encoded inline, No styling here
// const char HTTP_ROOT_MAIN[] PROGMEM = "<img title=' alt=' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAADQElEQVRoQ+2YjW0VQQyE7Q6gAkgFkAogFUAqgFQAVACpAKiAUAFQAaECQgWECggVGH1PPrRvn3dv9/YkFOksoUhhfzwz9ngvKrc89JbnLxuA/63gpsCmwCADWwkNEji8fVNgotDM7osI/x777x5l9F6JyB8R4eeVql4P0y8yNsjM7KGIPBORp558T04A+CwiH1UVUItiUQmZ2XMReSEiAFgjAPBeVS96D+sCYGaUx4cFbLfmhSpnqnrZuqEJgJnd8cQplVLciAgX//Cf0ToIeOB9wpmloLQAwpnVmAXgdf6pwjpJIz+XNoeZQQZlODV9vhc1Tuf6owrAk/8qIhFbJH7eI3eEzsvydQEICqBEkZwiALfF70HyHPpqScPV5HFjeFu476SkRA0AzOfy4hYwstj2ZkDgaphE7m6XqnoS7Q0BOPs/sw0kDROzjdXcCMFCNwzIy0EcRcOvBACfh4k0wgOmBX4xjfmk4DKTS31hgNWIKBCI8gdzogTgjYjQWFMw+o9LzJoZ63GUmjWm2wGDc7EvDDOj/1IVMIyD9SUAL0WEhpriRlXv5je5S+U1i2N88zdPuoVkeB+ls4SyxCoP3kVm9jsjpEsBLoOBNC5U9SwpGdakFkviuFP1keblATkTENTYcxkzgxTKOI3jyDxqLkQT87pMA++H3XvJBYtsNbBN6vuXq5S737WqHkW1VgMQNXJ0RshMqbbT33sJ5kpHWymzcJjNTeJIymJZtSQd9NHQHS1vodoFoTMkfbJzpRnLzB2vi6BZAJxWaCr+62BC+jzAxVJb3dmmiLzLwZhZNPE5e880Suo2AZgB8e8idxherqUPnT3brBDTlPxO3Z66rVwIwySXugdNd+5ejhqp/+NmgIwGX3Py3QBmlEi54KlwmjkOytQ+iJrLJj23S4GkOeecg8G091no737qvRRdzE+HLALQoMTBbJgBsCj5RSWUlUVJiZ4SOljb05eLFWgoJ5oY6yTyJp62D39jDANoKKcSocPJD5dQYzlFAFZJflUArgTPZKZwLXAnHmerfJquUkKZEgyzqOb5TuDt1P3nwxobqwPocZA11m4A1mBx5IxNgRH21ti7KbAGiyNn3HoF/gJ0w05A8xclpwAAAABJRU5ErkJggg==' /><h1>{v}</h1><h3>WiFiManager</h3>";
const char HTTP_ROOT_MAIN[] PROGMEM = "<h1>{v}</h1><h3>WiFiManager</h3>";
const char * const HTTP_PORTAL_MENU[] PROGMEM = {
"<form action='/wifi' method='get'><button>Configure WiFi</button></form><br/>\n", // MENU_WIFI
"<form action='/0wifi' method='get'><button>Configure WiFi (No Scan)</button></form><br/>\n", // MENU_WIFINOSCAN
"<form action='/info' method='get'><button>Info</button></form><br/>\n", // MENU_INFO
"<form action='/param' method='get'><button>Setup</button></form><br/>\n",//MENU_PARAM
"<form action='/close' method='get'><button>Close</button></form><br/>\n", // MENU_CLOSE
"<form action='/restart' method='get'><button>Restart</button></form><br/>\n",// MENU_RESTART
"<form action='/exit' method='get'><button>Exit</button></form><br/>\n", // MENU_EXIT
"<form action='/erase' method='get'><button class='D'>Erase</button></form><br/>\n", // MENU_ERASE
"<hr><br/>" // 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 = "<div role='img' aria-label='{r}%' title='{r}%' class='q q-{q} {i} {h}'></div>"; // rssi icons
const char HTTP_ITEM_QP[] PROGMEM = "<div class='q {h}'>{r}%</div>"; // rssi percentage
const char HTTP_ITEM[] PROGMEM = "<div><a href='#p' onclick='c(this)'>{v}</a>{qi}{qp}</div>"; // {q} = HTTP_ITEM_QI, {r} = HTTP_ITEM_QP
// const char HTTP_ITEM[] PROGMEM = "<div><a href='#p' onclick='c(this)'>{v}</a> {R} {r}% {q} {e}</div>"; // test all tokens
const char HTTP_FORM_START[] PROGMEM = "<form method='POST' action='{v}'>";
const char HTTP_FORM_WIFI[] PROGMEM = "<label for='s'>SSID</label><input id='s' name='s' maxlength='32' autocorrect='off' autocapitalize='none' placeholder='{v}'><br/><label for='p'>Password</label><input id='p' name='p' maxlength='64' type='password' placeholder='{p}'>";
const char HTTP_FORM_WIFI_END[] PROGMEM = "";
const char HTTP_FORM_STATIC_HEAD[] PROGMEM = "<hr><br/>";
const char HTTP_FORM_END[] PROGMEM = "<br/><br/><button type='submit'>Save</button></form>";
const char HTTP_FORM_LABEL[] PROGMEM = "<label for='{i}'>{t}</label>";
const char HTTP_FORM_PARAM_HEAD[] PROGMEM = "<hr><br/>";
const char HTTP_FORM_PARAM[] PROGMEM = "<br/><input id='{i}' name='{n}' maxlength='{l}' value='{v}' {c}>";
const char HTTP_SCAN_LINK[] PROGMEM = "<br/><form action='/wifi?refresh=1' method='POST'><button name='refresh' value='1'>Refresh</button></form>";
const char HTTP_SAVED[] PROGMEM = "<div class='msg'>Saving Credentials<br/>Trying to connect ESP to network.<br />If it fails reconnect to AP to try again</div>";
const char HTTP_PARAMSAVED[] PROGMEM = "<div class='msg S'>Saved<br/></div>";
const char HTTP_END[] PROGMEM = "</div></body></html>";
const char HTTP_ERASEBTN[] PROGMEM = "<br/><form action='/erase' method='get'><button class='D'>Erase WiFi Config</button></form>";
const char HTTP_BACKBTN[] PROGMEM = "<hr><br/><form action='/' method='get'><button>Back</button></form>";
const char HTTP_STATUS_ON[] PROGMEM = "<div class='msg S'><strong>Connected</strong> to {v}<br/><em><small>with IP {i}</small></em></div>";
const char HTTP_STATUS_OFF[] PROGMEM = "<div class='msg {c}'><strong>Not Connected</strong> to {v}{r}</div>";
const char HTTP_STATUS_OFFPW[] PROGMEM = "<br/>Authentication Failure"; // STATION_WRONG_PASSWORD, no eps32
const char HTTP_STATUS_OFFNOAP[] PROGMEM = "<br/>AP not found"; // WL_NO_SSID_AVAIL
const char HTTP_STATUS_OFFFAIL[] PROGMEM = "<br/>Could not Connect"; // WL_CONNECT_FAILED
const char HTTP_STATUS_NONE[] PROGMEM = "<div class='msg'>No AP set</div>";
const char HTTP_BR[] PROGMEM = "<br/>";
const char HTTP_STYLE[] PROGMEM = "<style>"
".c,body{text-align:center;font-family:verdana}div,input{padding:5px;font-size:1em;margin:5px 0;box-sizing:border-box;}"
"input,button,.msg{border-radius:.3rem;width: 100%}"
"button,input[type='button'],input[type='submit']{cursor:pointer;border:0;background-color:#1fa3ec;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%}"
"input[type='file']{border:1px solid #1fa3ec}"
".wrap {text-align:left;display:inline-block;min-width:260px;max-width:500px}"
// links
"a{color:#000;font-weight:700;text-decoration:none}a:hover{color:#1fa3ec;text-decoration:underline}"
// quality icons
".q{height:16px;margin:0;padding:0 5px;text-align:right;min-width:38px;float:right}.q.q-0:after{background-position-x:0}.q.q-1:after{background-position-x:-16px}.q.q-2:after{background-position-x:-32px}.q.q-3:after{background-position-x:-48px}.q.q-4:after{background-position-x:-64px}.q.l:before{background-position-x:-80px;padding-right:5px}.ql .q{float:left}.q:after,.q:before{content:'';width:16px;height:16px;display:inline-block;background-repeat:no-repeat;background-position: 16px 0;"
"background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAAAQCAMAAADeZIrLAAAAJFBMVEX///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADHJj5lAAAAC3RSTlMAIjN3iJmqu8zd7vF8pzcAAABsSURBVHja7Y1BCsAwCASNSVo3/v+/BUEiXnIoXkoX5jAQMxTHzK9cVSnvDxwD8bFx8PhZ9q8FmghXBhqA1faxk92PsxvRc2CCCFdhQCbRkLoAQ3q/wWUBqG35ZxtVzW4Ed6LngPyBU2CobdIDQ5oPWI5nCUwAAAAASUVORK5CYII=');}"
// icons @2x media query (32px rescaled)
"@media (-webkit-min-device-pixel-ratio: 2),(min-resolution: 192dpi){.q:before,.q:after {"
"background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALwAAAAgCAMAAACfM+KhAAAALVBMVEX///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAOrOgAAAADnRSTlMAESIzRGZ3iJmqu8zd7gKjCLQAAACmSURBVHgB7dDBCoMwEEXRmKlVY3L//3NLhyzqIqSUggy8uxnhCR5Mo8xLt+14aZ7wwgsvvPA/ofv9+44334UXXngvb6XsFhO/VoC2RsSv9J7x8BnYLW+AjT56ud/uePMdb7IP8Bsc/e7h8Cfk912ghsNXWPpDC4hvN+D1560A1QPORyh84VKLjjdvfPFm++i9EWq0348XXnjhhT+4dIbCW+WjZim9AKk4UZMnnCEuAAAAAElFTkSuQmCC');"
"background-size: 95px 16px;}}"
// msg callouts
".msg{padding:20px;margin:20px 0;border:1px solid #eee;border-left-width:5px;border-left-color:#777}.msg h4{margin-top:0;margin-bottom:5px}.msg.P{border-left-color:#1fa3ec}.msg.P h4{color:#1fa3ec}.msg.D{border-left-color:#dc3630}.msg.D h4{color:#dc3630}.msg.S{border-left-color: #5cb85c}.msg.S h4{color: #5cb85c}"
// lists
"dt{font-weight:bold}dd{margin:0;padding:0 0 0.5em 0;min-height:12px}"
"td{vertical-align: top;}"
".h{display:none}"
"button.D{background-color:#dc3630}"
// invert
"body.invert,body.invert a,body.invert h1 {background-color:#060606;color:#fff;}"
"body.invert .msg{color:#fff;background-color:#282828;border-top:1px solid #555;border-right:1px solid #555;border-bottom:1px solid #555;}"
"body.invert .q[role=img]{-webkit-filter:invert(1);filter:invert(1);}"
"input:disabled {opacity: 0.5;}"
"</style>";
const char HTTP_HELP[] PROGMEM =
"<br/><h3>Available Pages</h3><hr>"
"<table class='table'>"
"<thead><tr><th>Page</th><th>Function</th></tr></thead><tbody>"
"<tr><td><a href='/'>/</a></td>"
"<td>Menu page.</td></tr>"
"<tr><td><a href='/wifi'>/wifi</a></td>"
"<td>Show WiFi scan results and enter WiFi configuration.(/0wifi noscan)</td></tr>"
"<tr><td><a href='/wifisave'>/wifisave</a></td>"
"<td>Save WiFi configuration information and configure device. Needs variables supplied.</td></tr>"
"<tr><td><a href='/param'>/param</a></td>"
"<td>Parameter page</td></tr>"
"<tr><td><a href='/info'>/info</a></td>"
"<td>Information page</td></tr>"
"<tr><td><a href='/close'>/close</a></td>"
"<td>Close the captiveportal popup,configportal will remain active</td></tr>"
"<tr><td><a href='/exit'>/exit</a></td>"
"<td>Exit Config Portal, configportal will close</td></tr>"
"<tr><td><a href='/restart'>/restart</a></td>"
"<td>Reboot the device</td></tr>"
"<tr><td><a href='/erase'>/erase</a></td>"
"<td>Erase WiFi configuration and reboot Device. Device will not reconnect to a network until new WiFi configuration data is entered.</td></tr>"
"</table>"
"<p/>More information about WiFiManager at <a href='https://github.com/tzapu/WiFiManager'>https://github.com/tzapu/WiFiManager</a>.";
#ifdef WM_JSTEST
const char HTTP_JS[] PROGMEM =
"<script>function postAjax(url, data, success) {"
" var params = typeof data == 'string' ? data : Object.keys(data).map("
" function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }"
" ).join('&');"
" var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(\"Microsoft.XMLHTTP\");"
" xhr.open('POST', url);"
" xhr.onreadystatechange = function() {"
" if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }"
" };"
" xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');"
" xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');"
" xhr.send(params);"
" return xhr;}"
"postAjax('/status', 'p1=1&p2=Hello+World', function(data){ console.log(data); });"
"postAjax('/status', { p1: 1, p2: 'Hello World' }, function(data){ console.log(data); });"
"</script>";
#endif
// Info html
#ifdef ESP32
const char HTTP_INFO_esphead[] PROGMEM = "<h3>esp32</h3><hr><dl>";
const char HTTP_INFO_chiprev[] PROGMEM = "<dt>Chip Rev</dt><dd>{1}</dd>";
const char HTTP_INFO_lastreset[] PROGMEM = "<dt>Last reset reason</dt><dd>CPU0: {1}<br/>CPU1: {2}</dd>";
const char HTTP_INFO_aphost[] PROGMEM = "<dt>Acccess Point Hostname</dt><dd>{1}</dd>";
#else
const char HTTP_INFO_esphead[] PROGMEM = "<h3>esp8266</h3><hr><dl>";
const char HTTP_INFO_flashsize[] PROGMEM = "<dt>Real Flash Size</dt><dd>{1} bytes</dd>";
const char HTTP_INFO_fchipid[] PROGMEM = "<dt>Flash Chip ID</dt><dd>{1}</dd>";
const char HTTP_INFO_corever[] PROGMEM = "<dt>Core Version</dt><dd>{1}</dd>";
const char HTTP_INFO_bootver[] PROGMEM = "<dt>Boot Version</dt><dd>{1}</dd>";
const char HTTP_INFO_memsketch[] PROGMEM = "<dt>Memory - Sketch Size</dt><dd>Used / Total bytes<br/>{1} / {2}";
const char HTTP_INFO_memsmeter[] PROGMEM = "<br/><progress value='{1}' max='{2}'></progress></dd>";
const char HTTP_INFO_lastreset[] PROGMEM = "<dt>Last reset reason</dt><dd>{1}</dd>";
#endif
const char HTTP_INFO_freeheap[] PROGMEM = "<dt>Memory - Free Heap</dt><dd>{1} bytes available</dd>";
const char HTTP_INFO_wifihead[] PROGMEM = "<br/><h3>WiFi</h3><hr>";
const char HTTP_INFO_uptime[] PROGMEM = "<dt>Uptime</dt><dd>{1} Mins {2} Secs</dd>";
const char HTTP_INFO_chipid[] PROGMEM = "<dt>Chip ID</dt><dd>{1}</dd>";
const char HTTP_INFO_idesize[] PROGMEM = "<dt>Flash Size</dt><dd>{1} bytes</dd>";
const char HTTP_INFO_sdkver[] PROGMEM = "<dt>SDK Version</dt><dd>{1}</dd>";
const char HTTP_INFO_cpufreq[] PROGMEM = "<dt>CPU Frequency</dt><dd>{1}MHz</dd>";
const char HTTP_INFO_apip[] PROGMEM = "<dt>Access Point IP</dt><dd>{1}</dd>";
const char HTTP_INFO_apmac[] PROGMEM = "<dt>Access Point MAC</dt><dd>{1}</dd>";
const char HTTP_INFO_apssid[] PROGMEM = "<dt>SSID</dt><dd>{1}</dd>";
const char HTTP_INFO_apbssid[] PROGMEM = "<dt>BSSID</dt><dd>{1}</dd>";
const char HTTP_INFO_staip[] PROGMEM = "<dt>Station IP</dt><dd>{1}</dd>";
const char HTTP_INFO_stagw[] PROGMEM = "<dt>Station Gateway</dt><dd>{1}</dd>";
const char HTTP_INFO_stasub[] PROGMEM = "<dt>Station Subnet</dt><dd>{1}</dd>";
const char HTTP_INFO_dnss[] PROGMEM = "<dt>DNS Server</dt><dd>{1}</dd>";
const char HTTP_INFO_host[] PROGMEM = "<dt>Hostname</dt><dd>{1}</dd>";
const char HTTP_INFO_stamac[] PROGMEM = "<dt>Station MAC</dt><dd>{1}</dd>";
const char HTTP_INFO_conx[] PROGMEM = "<dt>Connected</dt><dd>{1}</dd>";
const char HTTP_INFO_autoconx[] PROGMEM = "<dt>Autoconnect</dt><dd>{1}</dd>";
const char HTTP_INFO_temp[] PROGMEM = "<dt>Temperature</dt><dd>{1} C&deg; / {2} F&deg;</dd>";
// 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
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment