Compare commits

..

No commits in common. "master" and "v5.4" have entirely different histories.
master ... v5.4

12 changed files with 1169 additions and 1597 deletions

View File

@ -1,5 +1,3 @@
# WiFiConfig
![Screenshot](doc/images/Screenshot_20180507-100906.png)
Knihovna pro konfiguraci WiFi rozhraní modulu ESP8266 a ESP32, obsahující Captive portal.
Knihovna pro konfiguraci WiFi rozhraní modulu ESP8266

782
WiFiConfig.cpp Normal file
View File

@ -0,0 +1,782 @@
/*
* V5.4 - 9.1.2018 - na titulni stranku pridan duvod, proc je spusteny konfiguracni AP. Usnadni to diagnostiku pripadu, kdy se ESP nechce pripojit k AP.
*
* V5.3 - 8.12.2017 - prepracovano presmerovani v Captive portalu, DEBUG_MSG makro upraveno na posledni pouzivanou verzi, scitani retezcu prepracovano na .concat. Pripsany Informace o modulu, reakce na Reset
*
* V5.2 - 20.4.2017 - Pokud je pouzite v timeoutu EC_DONT_RUN_CONFIGAP tak se vracime okamzite a necekame na pripojeni k WiFi (take nevolame zadnou callback metodu).
* Navratovy kod je pak WCR_CONFIGAP_NOT_STARTED .
*
* V5.1 - 3.4.2017 - Webove rozhrani upravene pro snadnejsi ovladani na telefonu/tabletu, sila signalu AP zobrazena jako barevne odliseny indikator.
*
* V5.0 - 29.10.2016- Vyuziti vlastnosti ESP, ktere si uklada wifi konfiguraci do sve vlastni flash oblasti, takze nemusim vse konfigurovat znovu po startu - doufam, ze se tim zrychli asociace s AP
* kvuli bateriove napajenym pristrojum.
*
* V4.7 - 30.8.2016 - Metody .begin se nyni vraci s wificonfigresult_t (podarilo se pripojit k AP, nepodarilo se pripojit a vyprsel timeout pro konfiguracni AP, nepodarilo se pripojit, ale je zakazane spousteni konfiguracniho AP).
* ESP NYNI NENI RESETOVAN PO VYPRSENI TIMEOUTU!!!! Je to kvuli bateriovym cidlum a DeepSleep rezimu v situaci, kdy zmizi AP, ke kteremu se bezne pripojujeme
* Odstraneno odesilani reakce na generate_204 (viz. https://github.com/tzapu/WiFiManager/issues/114)
* Zbytek MAC adresy v pripadnem SSID je nyni vzdy velkymi pismeny (UAA Unique Address Assignment)
* Kvalita signalu jednotlivych AP je nyni uvadena v % namisto uzivatelum nic nerikajicich -dBm
* Pokud do polozky timeout v .begin() metode zadame hodnotu WC_DONT_RUN_CONFIGAP, tak i po neuspesnem pokusu o pripojeni do site NENI spusteny konfiguracni AP (bateriove pristroje, stale bezici pristroje)
*
* V4.6 - 26.7.2016 - Moznost nastavit cislo kanalu pro rezim AP, nove eye-candy rozhrani.
*
* V4.5 - 20.7.2016 - Moznost konfigurovat cislo kanalu pro nastavovaci AP (default je 3), po nacteni konfiguracni stranky je nastaveny timeout na 6 minut, pokud je ve jmenu SSID pro konfiguracni
* AP znak ? (otaznik), tak je tento nahrazen HEXASCII reprezentaci 3 poslednich bytu MAC adresy AP (POZOR!!! je jina, nez STA!!!)
*
* V4.4 - 10.7.2016 - Zmena nazvu vsech privatnich metod (doplnene uvodni podtrzitko _). Pokud tam nebylo, tak napriklad nesel prelozit skript s handleNotFound pokud nebyl dopredne deklarovany (asi zmatek v Arduino preprocesoru)
*
* V4.3 - 23.6.2016 - Kazde nacteni webove stranky prodluzuje pripadny timeout pro restart zarizeni.
*
* V4.2 - 10.6.2016 - DNSServer a WebServer ukazatele jsou nyni staticke primo v modulu WiFiConfig. Predchozi verze neumoznila soucasne pouziti s knihovnami ESPAsyncWebServer z duvodu kolize nekterych definic HTTP metod
*
* V4.1 - 18.5.2016 - Nenechame SDK ukladat WiFi konfiguraci do Flash (setrime prepisy)
*
* V4.0 - 10.4.2016 - pridana moznost staticke konfigurace ip parametru. POZOR!!!! ukladani dat do EEPROM (verejne funkce) nyni nevolaji automaticky commit() kvuli snizeni poctu prepisu Flash EEPROM
* pridana moznost timeoutu pro konfiguracni AP. Pokud timeout vyprsi, tak se zarizeni automaticky restartuje, coz vyvola novy pokus o pripojeni.
*
* V3.0 - 27.2.2016 - pridana presmerovavaci stranka kvuli Captive portalu, doplneno servirovani favicon.ico, doplnena moznost zadavani uzivatelskych parametru, www server a DNS server jsou dynamicky vytvareny
*
* V2.4 - 7.2.2016 - upraveno casovani pri pripojovani k AP (zmizel delay(100))
*
* V2.3 - 5.2.2016 - pridano zverejneni jmena hosta a nastaveni tohoto jmena pro DHCP apod.
*
* V2.2 - 19.1.2016 - pridan Captive portal pri konfiguracnim AP.
*
* V2.1 - 20.9.2015 - pridano zadavani jmena zarizeni. Modul ho sice nevyuziva, ale aplikace ano a v pripade DHCP se dost hodi.
*
* V2.0 - 30.8.2015 - Podstatnym zpusobem vylepsena signalizace vnitrniho stavu, presunuto ulozeni rezimu (commit je uz zbytecny - udela se pri ukladani retezcu - uspora kodu/setreni prepisu pameti Flash)
*
* V1.2 - 23.8.2015 - BugFix - pridan chybejici eeprom.commit() po ulozeni rezimu prace
*
* V1.1 - 5.8.2015 - pridana moznost volani callback metody pri behu konfiguracniho AP (signalizace stavu uzivatelskym zpusobem)
*
* V1.0 - publikace na www.xpablo.cz
*
* TODO:
* Prejit na pripojovani pomoci vnitrnich mechanizmu SDK ESP - zvysi se tim rychlost pripojeni kvuli bateriovym zarizenim
*/
#include "WiFiConfig.h"
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <EEPROM.h>
#include <Ticker.h>
#include "embHTML.h"
#ifdef DEBUG_ESP_PORT
#define DEBUG_MSG(_1, ...) DEBUG_ESP_PORT.printf_P(PSTR(_1), ##__VA_ARGS__)
#else
#define DEBUG_MSG(...)
#endif
extern "C" {
#include "user_interface.h"
}
#define DNS_PORT 53
char WiFiDeviceName[elementSize(wificonfigarea_t, devname)]; // misto pro jmeno zarizeni (dodane do DNS, DHCP NBNS apod...)
enum
{
WIFIMODE_AP = WIFI_AP, // rezim prace jako pristupovy bod (AP)
WIFIMODE_STA = WIFI_STA, // rezim prace jako klient
WIFIMODE_AP_STA = WIFI_AP_STA // rezim prace jako klient i pristupovy bod
};
enum
{
IPCONFIG_DHCP = 0x55, // DHCP konfigurace ip adres (default)
IPCONFIG_STATIC = 0xaa // staticka konfigurace ip adres
};
static int configBase; // musi byt trvale ulozene, aby fungovaly metody pro ziskani retezcu z EEPROM
static std::unique_ptr<DNSServer> dnsServer;
static std::unique_ptr<ESP8266WebServer> server;
static std::unique_ptr<Ticker> rsttick;
const char VALUE[] PROGMEM = "value='";
const char CHECKED[] PROGMEM = "checked='checked'";
IPAddress getOurIP(void)
{
IPAddress ipa;
WiFiMode_t wm = WiFi.getMode();
switch (wm)
{
case WIFI_STA:
ipa = WiFi.localIP();
break;
case WIFI_AP:
ipa = WiFi.softAPIP();
break;
default:
ipa = IPAddress(0,0,0,0); // nelze urcit ip adresu (bud je AP + STA aktivni, nebo je vypnute WiFi)
break;
}
return ipa;
}
uint8_t * getOurMAC(uint8_t *mac)
{
if (WIFIMODE_STA == EEPROM.read(configBase + offsetof(wificonfigarea_t, mode)))
return WiFi.macAddress(mac);
else
return WiFi.softAPmacAddress(mac);
}
uint32_t getEEPROMuint32(int start)
{
uint32_t result = 0;
for (int i=0; i<4; ++i)
{
result <<= 8;
result += EEPROM.read(start);
++start;
}
return result;
}
void setEEPROMuint32(int start, uint32_t val)
{
for (int i=0; i<4; ++i)
{
EEPROM.write(start + 3 - i, (uint8_t)val);
val >>= 8;
}
}
String getEEPROMString(int start, int len)
{
String string = "";
for (int i = start; i < + start + len; ++i)
{
uint8_t b = EEPROM.read(i);
if ((0xff == b) || (0 == b))
break;
string.concat(char(b));
}
return string;
}
void setEEPROMString(int start, int len, String string)
{
unsigned int si = 0;
for (int i = start; i < start + len; ++i)
{
char c;
if (si < string.length())
{
c = string[si];
}
else
{
c = 0;
}
EEPROM.write(i, c);
++si;
}
}
WiFiConfigUsrParameter::WiFiConfigUsrParameter(const char *id, const char *label, const char *defaultValue, int length, storeparam_cb cb)
{
_next = NULL;
_cb = cb;
_id = id;
_label = label;
_length = length;
_value = new char[length + 1];
for (int i = 0; i < length; i++)
{
_value[i] = 0;
}
if (defaultValue != NULL)
{
strncpy(_value, defaultValue, length);
}
}
const char* WiFiConfigUsrParameter::getValue()
{
return _value;
}
const char* WiFiConfigUsrParameter::getID()
{
return _id;
}
const char* WiFiConfigUsrParameter::getLabel()
{
return _label;
}
int WiFiConfigUsrParameter::getValueLength()
{
return _length;
}
void WiFiConfigUsrParameter::setNext(WiFiConfigUsrParameter *n)
{
_next = n;
}
WiFiConfigUsrParameter *WiFiConfigUsrParameter::getNext()
{
return _next;
}
void WiFiConfigUsrParameter::setNewValue(const char *newval)
{
if (0 != strcmp(_value, newval))
_cb(newval);
}
WiFiConfigUsrParameter *WiFiConfig::_searchUsrParameter(const char *name)
{
WiFiConfigUsrParameter *ptr = _params;
while (NULL != ptr)
{
if (0 == strcmp(name, ptr->getID()))
break;
ptr = ptr->getNext();
}
return ptr;
}
void WiFiConfig::addParameter(WiFiConfigUsrParameter *p)
{
p->setNext(_params);
_params = p;
}
void WiFiConfig::_handleNotFound(void)
{
// _time = millis() + (_timeout * 1000); // spocitame si novy cas, kdy budeme modul restartovat
DEBUG_MSG("Requested URI: %s\r\n", server->uri().c_str());
if (server->uri().endsWith(String(F("favicon.ico"))))
{
server->send(404, F("text/plain"), F("Err"));
}
else
{
server->sendHeader(F("Location"), String(F("http://")) + server->client().localIP().toString() + String(F("/index.htm")), true);
// server->sendHeader(F("Location"), String(F("http://")) + WiFi.softAPIP().toString() + String(F("/index.htm")), true);
server->send (302, F("text/plain"), F("Redirect"));
}
}
void WiFiConfig::_handleReset(void)
{
rsttick.reset(new(Ticker));
rsttick->once_ms(700, []()
{
ESP.restart();
});
server->send_P(200, TEXTHTML, PAGE_RESTART);
}
void WiFiConfig::_handleInfo(void)
{
String reply;
reply.reserve(3000);
reply = FPSTR(PAGE_INDEX1);
reply.concat(F("<form><table><TR><TH>System Info<TH>"));
reply.concat(F("<TR><TD>Core Version:<TD>"));
reply.concat(ESP.getCoreVersion());
reply.concat(F("<TR><TD>Flash Size:<TD>"));
reply.concat(ESP.getFlashChipRealSize() / 1024);
reply.concat(F(" kB"));
reply.concat(F("<TR><TD>Sketch Size/Free:<TD>"));
reply.concat(ESP.getSketchSize() / 1024);
reply.concat(F(" kB / "));
reply.concat(ESP.getFreeSketchSpace() / 1024);
reply.concat(F(" kB"));
reply.concat(F("<TR><TD>STA MAC:<TD>"));
uint8_t mac[] = {0, 0, 0, 0, 0, 0};
uint8_t* macread = WiFi.macAddress(mac);
char macaddress[20];
sprintf_P(macaddress, PSTR("%02x:%02x:%02x:%02x:%02x:%02x"), macread[0], macread[1], macread[2], macread[3], macread[4], macread[5]);
reply.concat(macaddress);
reply.concat(F("<TR><TD>AP MAC:<TD>"));
macread = WiFi.softAPmacAddress(mac);
sprintf_P(macaddress, PSTR("%02x:%02x:%02x:%02x:%02x:%02x"), macread[0], macread[1], macread[2], macread[3], macread[4], macread[5]);
reply.concat(macaddress);
reply.concat(F("<TR><TD>ESP Chip ID:<TD>"));
reply.concat(ESP.getChipId());
reply.concat(F("<TR><TD>Flash Chip ID:<TD>"));
reply.concat(ESP.getFlashChipId());
reply.concat(F("</table></form>"));
server->send(200, TEXTHTML, reply);
}
void WiFiConfig::_handleRoot(void)
{
String content;
content.reserve(3000);
content = FPSTR(PAGE_CAPTIVEPORTALCATCH); // 1. cast stranky
// pridame informaci o stavu pokusu o pripojeni
content.concat(F("<div class=\"vl-info\">Pokus o připojení: "));
switch (_status)
{
case STATION_IDLE:
content.concat(F("Klid"));
break;
case STATION_CONNECTING:
content.concat(F("Připojování"));
break;
case STATION_WRONG_PASSWORD:
content.concat(F("Špatné heslo"));
break;
case STATION_NO_AP_FOUND:
content.concat(F("AP nenalezen"));
break;
case STATION_CONNECT_FAIL:
content.concat(F("Připojení selhalo"));
break;
case STATION_GOT_IP:
content.concat(F("Získaná ip"));
break;
case 0xfe:
content.concat(F("Špatná EEPROM"));
break;
case 0xff:
content.concat(F("Vynucená konfigurace"));
break;
default:
content.concat(F("Neznámého"));
break;
}
content.concat(F("</div>"));
content.concat(FPSTR(PAGE_CAPTIVEPORTALCATCH2)); // 2. cast stranky (ukonceni)
server->send(200, TEXTHTML, content);
_time = millis() + (_timeout * 1000); // spocitame si novy cas, kdy budeme modul restartovat
}
void WiFiConfig::_handleDisplayAP(void)
{
String s;
String v;
String content;
_time = millis() + (360 * 1000); // spocitame si novy cas, kdy budeme modul restartovat (6 minut)
content.reserve(3000);
content = FPSTR(PAGE_INDEX1);
int n = WiFi.scanNetworks();
if (0 == n)
{
content.concat(FPSTR(PAGE_NO_SSID));
}
else
{
for (int i = 0; i < n; ++i)
{
int quality;
if (WiFi.RSSI(i) <= -100)
quality = 0;
else if (WiFi.RSSI(i) >= -50)
quality = 100;
else
quality = 2 * (WiFi.RSSI(i) + 100);
s = FPSTR(SSID_ITEM);
s.replace(F("{v}"), WiFi.SSID(i));
s.replace(F("{a}"), String(quality));
s.replace(F("{s}"), (ENC_TYPE_NONE == WiFi.encryptionType(i)) ? F("") : F("l"));
content.concat(s);
}
}
s = FPSTR(PAGE_INDEX2);
v = getEEPROMString(configBase + offsetof(wificonfigarea_t, ssid), elementSize(wificonfigarea_t, ssid));
if (v.length())
s.replace(F("{s}"), String(FPSTR(VALUE)) + v + F("'"));
else
s.replace(F("{s}"), F("placeholder='SSID'"));
v = getEEPROMString(configBase + offsetof(wificonfigarea_t, pass), elementSize(wificonfigarea_t, pass));
if (v.length())
s.replace(F("{p}"), String(FPSTR(VALUE)) + v + F("'"));
else
s.replace(F("{p}"), F("placeholder='password'"));
v = getEEPROMString(configBase + offsetof(wificonfigarea_t, devname), elementSize(wificonfigarea_t, devname));
if (v.length())
s.replace(F("{n}"), String(FPSTR(VALUE)) + v + F("'"));
else
s.replace(F("{n}"), F("placeholder='name'"));
if (EEPROM.read(configBase + offsetof(wificonfigarea_t, mode)) == WIFIMODE_AP)
s.replace(F("{a}"), FPSTR(CHECKED));
else
s.replace(F("{a}"), F(""));
if (EEPROM.read(configBase + offsetof(wificonfigarea_t, ip)) == IPCONFIG_STATIC)
s.replace(F("{c}"), FPSTR(CHECKED));
else
s.replace(F("{c}"), F(""));
s.replace(F("{i}"), IPAddress(getEEPROMuint32(configBase + offsetof(wificonfigarea_t, ipaddr))).toString());
s.replace(F("{m}"), IPAddress(getEEPROMuint32(configBase + offsetof(wificonfigarea_t, netmask))).toString());
s.replace(F("{g}"), IPAddress(getEEPROMuint32(configBase + offsetof(wificonfigarea_t, gateway))).toString());
s.replace(F("{d}"), IPAddress(getEEPROMuint32(configBase + offsetof(wificonfigarea_t, dns))).toString());
uint8_t chan = EEPROM.read(configBase + offsetof(wificonfigarea_t, apchannel));
if ((chan < 1) || (chan > 13))
chan = 1; // neplatne cislo kanalu nahradime nejnizsim
s.replace(F("{ch}"), String(chan));
content.concat(s);
// Uzivatelske parametry
if (_params)
{
content.concat(FPSTR(PAGE_PARAM_HDR));
}
WiFiConfigUsrParameter *up = _params;
while (NULL != up)
{
s = FPSTR(PAGE_PARAM);
s.replace(F("{t}"), up->getLabel());
s.replace(F("{n}"), up->getID());
s.replace(F("{l}"), String(up->getValueLength()));
s.replace(F("{v}"), up->getValue());
content.concat(s);
up = up->getNext();
}
content.concat(FPSTR(PAGE_END));
server->send(200, TEXTHTML, content);
}
// Deal with (potentially) plus-encoded ssid/pass
void WiFiConfig::_plusDecode(String &s)
{
for (unsigned int i = 0; i < s.length(); i++)
s[i] = (s[i] == '+' ? ' ' : s[i]);
}
void WiFiConfig::_handleSetAP(void)
{
uint8_t mode;
String str;
str.reserve(128);
str = server->arg(F("_s"));
if (str.length() > 0)
{
_plusDecode(str);
setEEPROMString(configBase + offsetof(wificonfigarea_t, ssid), elementSize(wificonfigarea_t, ssid), str);
str = server->arg(F("_p"));
_plusDecode(str);
setEEPROMString(configBase + offsetof(wificonfigarea_t, pass), elementSize(wificonfigarea_t, pass), str);
str = server->arg(F("_n"));
setEEPROMString(configBase + offsetof(wificonfigarea_t, devname), elementSize(wificonfigarea_t, devname), str);
str = server->arg(F("_a"));
if (str.length() > 0)
{
mode = WIFIMODE_AP; // rezim AP
str = server->arg(F("_ch")); // kanal AP
EEPROM.write(configBase + offsetof(wificonfigarea_t, apchannel), (uint8_t)str.toInt());
}
else
mode = WIFIMODE_STA; // rezim STA
EEPROM.write(configBase + offsetof(wificonfigarea_t, mode), mode);
str = server->arg(F("_st"));
if (0 == str.length())
EEPROM.write(configBase + offsetof(wificonfigarea_t, ip), IPCONFIG_DHCP); // mame DHCP dynamickou konfiguraci
else
{ // staticka ip konfigurace
IPAddress ipa;
EEPROM.write(configBase + offsetof(wificonfigarea_t, ip), IPCONFIG_STATIC);
str = server->arg(F("_i"));
ipa.fromString(str);
setEEPROMuint32(configBase + offsetof(wificonfigarea_t, ipaddr), (uint32_t) ipa);
str = server->arg(F("_m"));
ipa.fromString(str);
setEEPROMuint32(configBase + offsetof(wificonfigarea_t, netmask), (uint32_t) ipa);
str = server->arg(F("_g"));
ipa.fromString(str);
setEEPROMuint32(configBase + offsetof(wificonfigarea_t, gateway), (uint32_t) ipa);
str = server->arg(F("_d"));
ipa.fromString(str);
setEEPROMuint32(configBase + offsetof(wificonfigarea_t, dns), (uint32_t) ipa);
}
// Uzivatelske parametry
for (int i = 0; i < server->args(); i++)
{
if (!server->argName(i).startsWith(F("_"))) // vnitrni parametry WiFiConfig modulu zacinaji _, takze ty muzeme ignorovat
{
WiFiConfigUsrParameter *up = _searchUsrParameter(server->argName(i).c_str());
if (NULL != up)
up->setNewValue(server->arg(i).c_str());
}
}
EEPROM.commit(); // skutecne ulozime data
}
server->send(200, F("text/html"), FPSTR(PAGE_SAVED));
delay(2000); // cekame na odeslani dat
// nakonfigurujeme ESP dle nove nastavenych parametru
WiFi.disconnect(); // vsechno odpojime
WiFi.persistent(true); // chceme, aby si modul zapamatoval konfiguraci
String s = getEEPROMString(configBase + offsetof(wificonfigarea_t, devname), elementSize(wificonfigarea_t, devname));
strcpy(WiFiDeviceName, s.c_str());
s = getEEPROMString(configBase + offsetof(wificonfigarea_t, ssid), elementSize(wificonfigarea_t, ssid));
String pass = getEEPROMString(configBase + offsetof(wificonfigarea_t, pass), elementSize(wificonfigarea_t, pass));
switch (EEPROM.read(configBase + offsetof(wificonfigarea_t, mode)))
{
case WIFIMODE_STA:
{
DEBUG_MSG("STA mode.\r\n");
WiFi.mode(WIFI_STA); // startujeme WiFi v rezimu klienta
if (strlen(WiFiDeviceName))
WiFi.hostname(WiFiDeviceName); // nastavime jmeno zarizeni
WiFi.begin(s.c_str(), pass.c_str());
if (IPCONFIG_STATIC == EEPROM.read(configBase + offsetof(wificonfigarea_t, ip)))
{
DEBUG_MSG("Static configuration.\r\n");
WiFi.config(IPAddress(getEEPROMuint32(configBase + offsetof(wificonfigarea_t, ipaddr))), IPAddress(getEEPROMuint32(configBase + offsetof(wificonfigarea_t, gateway))),
IPAddress(getEEPROMuint32(configBase + offsetof(wificonfigarea_t, netmask))), IPAddress(getEEPROMuint32(configBase + offsetof(wificonfigarea_t, dns))));
}
wifi_station_set_auto_connect(true);
}
break;
case WIFIMODE_AP:
DEBUG_MSG("AP mode.\r\n");
WiFi.mode(WIFI_AP); // startujeme AP
if (pass.length())
// je zadane heslo do AP
WiFi.softAP(s.c_str(), pass.c_str(), EEPROM.read(configBase + offsetof(wificonfigarea_t, apchannel)));
else
// otevreny AP
WiFi.softAP(s.c_str(), NULL, EEPROM.read(configBase + offsetof(wificonfigarea_t, apchannel)));
if (IPCONFIG_STATIC == EEPROM.read(configBase + offsetof(wificonfigarea_t, ip)))
WiFi.softAPConfig(IPAddress(getEEPROMuint32(configBase + offsetof(wificonfigarea_t, ipaddr))), IPAddress(getEEPROMuint32(configBase + offsetof(wificonfigarea_t, gateway))),
IPAddress(getEEPROMuint32(configBase + offsetof(wificonfigarea_t, netmask))));
break;
default: // jakykoliv neznamy rezim (mozna zavada na EEPROM???)
DEBUG_MSG("Mode Error!!\r\n");
break;
}
delay(1000); // cekame XX sekund na ulozeni atd...
ESP.restart();
}
// Start WiFi v rezimu AP pro nastaveni modulu
wificonfigresult_t WiFiConfig::_setupAP(wificonfig_cb cb)
{
String ssid = SETUP_SSID;
WiFi.persistent(false); // chranime flash pred zbytecnymi prepisy
dnsServer.reset(new DNSServer());
server.reset(new ESP8266WebServer(80));
/* Soft AP network parameters */
IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);
WiFi.disconnect(); // pro jistotu se odpojime
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, netMsk);
if (ssid.endsWith(F("?")))
{
//uint8_t amac[6];
char lmac[16];
//WiFi.softAPmacAddress(amac);
//sprintf_P(lmac, PSTR("%02X%02X%02X"), amac[3], amac[4], amac[5]);
sprintf_P(lmac, PSTR("%06X"), ESP.getChipId());
ssid.replace(F("?"), String(lmac));
}
WiFi.softAP(ssid.c_str(), NULL, SETUP_CHANNEL);
delay(500); // dulezite - jinak se nevraci spravna IP adresa !!! (udajne od verze 2.3.0 uz neni nutne)
dnsServer->setErrorReplyCode(DNSReplyCode::NoError);
dnsServer->start(DNS_PORT, "*", WiFi.softAPIP()); // spustime tzv. Captive portal - vsechny DNS dotazy jsou smerovany na nasi ip adresu
if (cb)
cb(WCS_CONFIGSTART); // signalizujeme start konfiguracniho serveru
// Nastavime handlery weboveho serveru pro konfiguraci
server->onNotFound(std::bind(&WiFiConfig::_handleNotFound, this));
server->on(F("/config"), std::bind(&WiFiConfig::_handleDisplayAP, this));
server->on(F("/s"), std::bind(&WiFiConfig::_handleSetAP, this));
server->on(F("/r"), std::bind(&WiFiConfig::_handleReset, this));
server->on(F("/i"), std::bind(&WiFiConfig::_handleInfo, this));
server->on(F("/index.htm"), std::bind(&WiFiConfig::_handleRoot, this));
server->begin(); // startujeme webovy server
while (1)
{
server->handleClient(); // osetrujeme praci serveru
if (cb)
cb(WCS_CONFIGWAIT); // volame uzivatelsky callback (napr. signalizace)
dnsServer->processNextRequest();
yield(); // procesy uvnitr systemu ESP potrebuji take svuj cas
if (_timeout)
{
if (millis() > _time)
{
DEBUG_MSG("AP timeout\r\n");
if (cb)
cb(WCS_CONFIGTIMEOUT); // signalizujeme timeout
break; // ukoncime cekani a vracime se
}
}
}
// tady by asi melo byt zastaveni weboveho a dns serveru...
dnsServer->stop();
server->stop();
return WCR_TIMEOUT; // nepripojeno, vyprsel timeout konfiguracniho AP
}
// Testovani, zda se modul pripojil k AP
bool WiFiConfig::_testWifi(wificonfig_cb cb)
{
uint32_t startt = millis();
DEBUG_MSG("Trying to connect.\r\n");
while ((millis() - startt) < WIFI_STA_CONNECT_TIMEOUT)
{
if (WL_CONNECTED == WiFi.status())
{
DEBUG_MSG("Connected...\r\n");
if (cb)
cb(WCS_CONNECTED);
return true; // jsme pripojeni
}
yield();
if (cb)
cb(WCS_CONNECTING); // signalizujeme pokracujici pokus o spojeni
}
DEBUG_MSG("Not connected!\r\n");
_status = wifi_station_get_connect_status();
return false; // pripojeni se nezdarilo
}
wificonfigresult_t WiFiConfig::begin(int configarea, uint8_t forceConfigure, wificonfig_cb cb)
{
wificonfigresult_t result = WCR_OK; // predpokladame, ze se pripojeni podari
DEBUG_MSG("\r\n\r\n"); // oddeleni vypisu
configBase = configarea; // pocatek konfigurace v EEPROM
if (0 == forceConfigure)
{
DEBUG_MSG("Force config.\r\n");
_status = 0xff;
result = _setupAP(cb);
}
else
{
if (EEPROM.read(configBase + offsetof(wificonfigarea_t, mode)) != WiFi.getMode())
{ // neshoduje se rezim - musime spustit konfiguracni AP (poskozena konfigurace)
DEBUG_MSG("Wrong config\r\n");
_status = 0xfe;
result = _setupAP(cb);
}
else
{
String s = getEEPROMString(configBase + offsetof(wificonfigarea_t, devname), elementSize(wificonfigarea_t, devname));
strcpy(WiFiDeviceName, s.c_str());
switch (EEPROM.read(configBase + offsetof(wificonfigarea_t, mode)))
{
case WIFIMODE_STA:
{
WiFi.hostname(WiFiDeviceName); // nastavime jmeno zarizeni
DEBUG_MSG("STA mode.\r\n");
if (WC_DONT_RUN_CONFIGAP == _timeout)
result = WCR_CONFIGAP_NOT_STARTED; // nemame spoustet konfiguracni AP - vracime se hned
else
{
if (cb)
cb(WCS_CONNECTSTART); // signalizujeme zacatek pokusu o pripojeni
if (!_testWifi(cb))
{
result = _setupAP(cb); // modul se nepripojil - startujeme AP rezim
}
}
}
break;
case WIFIMODE_AP:
DEBUG_MSG("AP mode.\r\n");
if (cb)
cb(WCS_CONNECTSTART); // signalizujeme zacatek pokusu o pripojeni (zde se nic jineho stejne nestane...)
break;
}
}
}
return result; // mame vyreseno
}
wificonfigresult_t WiFiConfig::begin(int configarea, uint8_t forceConfigure, int timeout, wificonfig_cb cb = NULL)
{
if (forceConfigure)
{ // pouze pokud nemame vynucenou konfiguraci merime cas - to nam umozni dostat se ze spatne zadaneho timeoutu, ktery se neda zvladnout
if ((timeout > 0) && (40 > timeout))
timeout = 40; // timeout musi byt minimalne 40 sekund
_timeout = timeout;
if (_timeout > 0)
_time = millis() + (_timeout * 1000); // spocitame si novy cas, kdy budeme modul restartovat
}
else
_timeout = 0; // pri vynucene konfiguraci se parametr timeout neuplatni
return begin(configarea, forceConfigure, cb); // spustime WiFi
}
// EOF

178
WiFiConfig.h Normal file
View File

@ -0,0 +1,178 @@
/**
* @file WiFiConfig.h
* @author Pavel Brychta, http://www.xpablo.cz
*
* Copyright (c) 2015,16,17 Pavel Brychta. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/* Nastaveni ESP modulu, ktere pracuje takto:
* 1. Pokud je forceConfigure ==0, tak se aktivuje WiFi v rezimu AP a cele ESP je mozne nastavit webovym rozhranim (pocitam s prenosem hodnoty nouzoveho tlacitka pri startu).
* 2. Neni-li tlacitko stisknute, tak se vezme rezim prace a AP se nastavi dle nej (WIFI_STA a WIFI_AP)
* 3. Pokud byl rezim prace WIFI_STA a ESP se nepripoji k zadne siti do casu WIFI_STA_CONNECT_TIMEOUT, tak se pokracuje jako kdyby bylo stisknute rekonfiguracni tlacitko
*/
#ifndef __WiFiConfig_h__
#define __WiFiConfig_h__
#include <ESP8266WiFi.h>
#include <memory>
#define elementSize(type, element) sizeof(((type *)0)->element)
#define WC_DONT_RUN_CONFIGAP -1 // priznak, ze si neprejeme spoustet konfiguracni AP (uziva se misto parametru timeout). Urceno pro bateriove napajene pristroje
// Struktura konfigurace, ulozena v EEPROM
typedef struct
{
uint8_t mode; // rezim prace AP/STA
uint8_t ip; // konfigurace ip (staticka/DHCP)
char ssid[32]; // SSID site
char pass[64]; // heslo
char devname[32]; // jmeno zarizeni (pro NBNS plati jen 16 znaku)
uint32_t ipaddr; // ip adresa v pripade staticke konfigurace
uint32_t netmask; // sitova maska v pripade staticke konfigurace
uint32_t gateway; // sitova brana v pripade staticke konfigurace
uint32_t dns; // ip adresa DNS serveru v pripade staticke konfigurace
uint8_t apchannel; // kanal, na kterem pracuje AP (pokud je zapnuty rezim AP)
} wificonfigarea_t;
// Parametr, predany uzivatelske callback funkci, urceny pro aplikacni vizualizaci stavu konfigurace a pripojeni
typedef enum
{
WCS_CONNECTSTART = 0, // zacatek pokusu o pripojeni k ulozene konfiguraci
WCS_CONNECTING = 1, // probiha pokus o pripojeni
WCS_CONNECTED = 2, // pripojeni bylo uspesne
WCS_CONFIGSTART = 3, // zacatek startu konfiguracniho AP
WCS_CONFIGWAIT = 4, // cekame na nastaveni konfigurace pres web
WCS_CONFIGTIMEOUT = 5, // doslo k vyprseni timeoutu konfigurace, budeme se vracet s False jako vysledek z .begin(...)
}wificonfigstate_t;
// Navratovy parametr z volani begin() - udava, jak se podarilo WiFiConfig modulu pripojit k AP
typedef enum
{
WCR_OK = 0, // wifi pripojena/AP nastartovane (dle parametru v EEPROM)
WCR_TIMEOUT = 1, // wifi neni pripojena a vyprsel zadany timeout
WCR_CONFIGAP_NOT_STARTED = 2, // wifi neni pripojena a spusteni konfiguracniho AP bylo zakazane parametrem timeout (WC_DONT_RUN_CONFIGAP)
}wificonfigresult_t;
typedef void (*wificonfig_cb)(wificonfigstate_t state); // definice callbacku
typedef void (*storeparam_cb)(const char *newvalue); // callback pro ulozeni uzivatelskeho parametru
#ifndef WIFI_STA_CONNECT_TIMEOUT
#define WIFI_STA_CONNECT_TIMEOUT 15000UL // delka cekani na pripojeni k AP [ms]
#endif
#ifndef SETUP_SSID
#define SETUP_SSID "ESPPBSetup_?"
#endif
#ifndef SETUP_CHANNEL
#define SETUP_CHANNEL 3
#endif
/**
* \brief Ziskani retezce z EEPROM ze zadaneho offsetu
*
* \param [in] start Ofset zacatku retezce
* \param [in] len Delka retezce
* \return Vycteny retezec
*/
String getEEPROMString(int start, int len);
/**
* \brief Ulozeni retezce do EEPROM
*
* \param [in] start Ofset zacatku ukladani
* \param [in] len Maximalni delka ulozeneho retezce
* \param [in] string Ukladany retezec
*/
void setEEPROMString(int start, int len, String string);
/**
* \brief Ziskani nasi ip adresy
*
* \return Nase ip adresa, ziskana dle rezimu prace modulu
*/
IPAddress getOurIP(void);
/**
* \brief Ziskani nasi MAC adresy
*
* \param [in] mac kam ma byt MAC adresa ulozena
* \return Ukazatel na ulozenou MAC adresu (vraci parametr mac)
*
* \details Details
*/
uint8_t * getOurMAC(uint8_t *mac);
uint32_t getEEPROMuint32(int start);
void setEEPROMuint32(int start, uint32_t val);
extern char WiFiDeviceName[]; // jmeno zarizeni, pouzivane i pro DHCP
class WiFiConfigUsrParameter
{
public:
WiFiConfigUsrParameter(const char *id, const char *label, const char *defaultValue, int length, storeparam_cb cb);
const char *getID();
const char *getValue();
const char *getLabel();
int getValueLength();
void setNext(WiFiConfigUsrParameter *n);
WiFiConfigUsrParameter *getNext();
void setNewValue(const char *newval);
private:
const char *_id;
const char *_label;
char *_value;
int _length;
storeparam_cb _cb;
WiFiConfigUsrParameter *_next;
friend class WiFiConfig;
};
class WiFiConfig
{
public:
WiFiConfig(): _params(NULL), _timeout(0) {}
wificonfigresult_t begin(int configarea, uint8_t forceConfigure, wificonfig_cb cb);
wificonfigresult_t begin(int configarea, uint8_t forceConfigure, int timeout, wificonfig_cb cb);
void addParameter(WiFiConfigUsrParameter *p);
private:
wificonfigresult_t _setupAP(wificonfig_cb cb);
void _handleDisplayAP(void);
void _handleSetAP(void);
void _handleInfo(void);
void _handleReset(void);
void _handleNotFound(); // CaptivePortal redirector
void _handleRoot(); // jen jednoducha stranka kvuli CaptivePortalu umoznuje prejit na spravnou stranku (ale nedela to...)
bool _testWifi(wificonfig_cb cb);
WiFiConfigUsrParameter *_searchUsrParameter(const char *name);
void _plusDecode(String &s);
WiFiConfigUsrParameter *_params; // ukazatel na posledni zadany uzivatelsky parametr
int _timeout; // timeout pri cekani na konfiguraci
uint32_t _time; // hodnota, po ktere bude ESP restartovano (pokud je _timeout != 0)
uint8_t _status; // stav pripojeni - je pouzity pro signalizaci duvodu, proc se nepripoji k AP
};
#endif

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

121
embHTML.h Normal file
View File

@ -0,0 +1,121 @@
// file:///I:/MyProjects/PB_ESP8266_WiFiConfig_Vyvoj/doc/_testy/s?_s=SSID1&_p=heslo&_n=jmeno_zarizeni&_a=on&_st=on&_i=192.168.1.1&_m=255.255.255.0&_g=192.168.1.3&_d=192.168.1.3&{n}={v}
static const char TEXTHTML[] PROGMEM = "text/html";
static const char PAGE_INDEX1[] PROGMEM = R"=====(
<!DOCTYPE html><html lang="en"><head><meta charset= "utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>xPablo.cz Setup</title>
<style>
.c{text-align: center;}
div,input{padding:5px;font-size:1em;}
input{width:95%;}
body{text-align: center;font-family:verdana;}
button{border:0;border-radius:0.3rem;background-color:#1fa3ec;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;}
.q{float: right;width: 64px;text-align: right;}
.l{background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAALVBMVEX///8EBwfBwsLw8PAzNjaCg4NTVVUjJiZDRUUUFxdiZGSho6OSk5Pg4eFydHTCjaf3AAAAZElEQVQ4je2NSw7AIAhEBamKn97/uMXEGBvozkWb9C2Zx4xzWykBhFAeYp9gkLyZE0zIMno9n4g19hmdY39scwqVkOXaxph0ZCXQcqxSpgQpONa59wkRDOL93eAXvimwlbPbwwVAegLS1HGfZAAAAABJRU5ErkJggg==") no-repeat left center;background-size: 1em;}
#rssiBar{width: 100px;height: 15px;background: #fff;}
#rssiBar > div{width: 52px;height: 15px;background: #c20000;}
</style>
<script>
function c(l){document.getElementById('_s').value=l.innerText||l.textContent;document.getElementById('_p').focus();}
function hAP(){if (document.getElementById('_a').checked){document.getElementById('apconfig').style.display = 'block';}else{document.getElementById('apconfig').style.display = 'none';}}
function hSC(){if (document.getElementById('_st').checked){document.getElementById('staticip').style.display = 'block';}else{document.getElementById('staticip').style.display = 'none';}}
</script>
</head><body><h1>ESP8266 WiFiConfig</h1><div style='text-align:left;display:inline-block;min-width:260px;'>
)=====";
/* Polozky nalezenych SSID
{v} - SSID
{a} - RSSI (primo v dBm)
{s} - bud nic, nebo 'l'>
*/
static const char SSID_ITEM[] PROGMEM = R"=====(
<div><a href='#p' onclick='c(this)'>{v}</a>&nbsp;<span class='q {s}'><meter value="{a}" min="0" max="100" low="30" high="80" optimum="50" style="width: 70%;"></meter></span></div>
)=====";
/* Zacatek formulare pro vyplneni
{s} - SSID
{p} - password
{n} - Netbios name
{a} - AP mode (checkbox)
{ch}- cislo kanalu AP
{c} - staticka IP konfigurace (checkbox)
{i} - ip adresa
{m} - maska
{g} - brana
{d} - dns server
*/
static const char PAGE_INDEX2[] PROGMEM = R"=====(
<form method='post' action='s'>
<label>SSID<br><input id='_s' name='_s' maxlength=32 required {s}></label><br>
<label>Heslo<br><input id='_p' name='_p' maxlength=64 {p} type='password'></label><br>
<label>Jméno zařízení<br><input name='_n' maxlength=32 pattern='^[a-zA-Z][a-zA-Z0-9-_\\.]{1,32}$' title='Jméno dle NetBios konvence (max. 16 znaků písmena, čísla a znaky "_.")' {n}></label><br>
<div>
<label><input id='_a' name='_a' type='checkbox' style="width: 10%; float: left; margin-top: 5px;" onclick='hAP();' {a}>Režim AP</label>
<div id="apconfig">
<label>Kanál<br><input type="number" name="_ch" min="1" max="13" title='cislo kanalu v intervalu 1-13' value='{ch}'></label><br>
</div>
</div>
<div>
<label><input id='_st' name='_st' type='checkbox' style="width: 10%; float: left; margin-top: 5px;" onclick='hSC();' {a}>Staticka IP konfigurace</label>
<div id="staticip">
<label>IP adresa<br><input type="text" name="_i" pattern='((^|\.)((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?\d))){4}$' title='ip adresa ve formatu <cislo>.<cislo>.<cislo>.<cislo>' value='{i}'></label><br>
<label>Síťová maska<br><input type="text" name="_m" pattern='((^|\.)((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?\d))){4}$' title='ip adresa ve formatu <cislo>.<cislo>.<cislo>.<cislo>' value='{m}'></label><br>
<label>Síťová brána<br><input type="text" name="_g" pattern='((^|\.)((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?\d))){4}$' title='ip adresa ve formatu <cislo>.<cislo>.<cislo>.<cislo>' value='{g}'></label><br>
<label>Server DNS<br><input type="text" name="_d" pattern='((^|\.)((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?\d))){4}$' title='ip adresa ve formatu <cislo>.<cislo>.<cislo>.<cislo>' value='{d}'></label><br>
</div>
</div>
<script>hAP();hSC();</script>
)=====";
// Uzivatelsky pridane polozky
static const char PAGE_PARAM_HDR[] PROGMEM = R"=====(
<hr>
<h2>Uživatelské položky</h2>
)=====";
static const char PAGE_PARAM[] PROGMEM = R"=====(
<label>{t}<br><input name='{n}' maxlength='{l}' value='{v}'></label><br>
)=====";
// Konec formulare a stranky
static const char PAGE_END[] PROGMEM = R"=====(
<br>
<button type='submit'>Uložit a restartovat</button></form>
</div></body></html>
)=====";
// Nenalezeno zadne SSID
static const char PAGE_NO_SSID[] PROGMEM = R"=====(
<div>Nenalezená žádná síť. Občerstvi stránku pro nové hledání.</div>
)=====";
// Konfigurace ulozena - restartuji...
static const char PAGE_SAVED[] PROGMEM = R"=====(
<!DOCTYPE html><html lang="cs"><head><meta http-equiv="refresh" content="10;url=/"/>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1"/>
<title>xPablo Setup - Konfigurace uložena</title>
<style>div,input {margin-bottom: 5px;}body{width:200px;display:block;margin-left:auto;margin-right:auto;}</style>
</head><body>
Uloženo do EEPROM...<br/>
Restart za 10 sekund.
</body></html>
)=====";
static const char PAGE_CAPTIVEPORTALCATCH[] PROGMEM = R"=====(
<!DOCTYPE html><html lang="cs"><head><meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/><title>xPablo.cz Setup</title>
<style>.c{text-align: center;} div,input{padding:5px;font-size:1em;} input{width:95%;} body{text-align: center;font-family:verdana;} button{border:0;border-radius:0.3rem;background-color:#1fa3ec;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;} .q{float: right;width: 64px;text-align: right;}
.vl-info {border-left: thick solid #1fa3ec;background: #cee6ff; text-align:left; display:inline-block; min-width:260px; margin-top:15px}
.red { background-color: #ff0000;}
</style>
</head><body><div style='text-align:left;display:inline-block;min-width:260px;'>
<form action="/config" method="get"><button>Konfigurace WiFi</button></form><br/><form action="/i" method="get"><button>Informace o modulu</button></form><br/><form action="/r" method="post"><button class="red">Reset</button></form><br>
)=====";
// druha cast (mezi 1. a druhou cast muzeme doplnit dodatecne informace)
static const char PAGE_CAPTIVEPORTALCATCH2[] PROGMEM = R"=====(
</div></body></html>
)=====";
static const char PAGE_RESTART[] PROGMEM = R"=====(
Restartuji...
)=====";

View File

@ -1,143 +1,129 @@
#if defined(ARDUINO_ARCH_ESP8266)
# include <ESP8266WiFi.h>
# include <ESP8266WebServer.h>
# include <ESP8266NetBIOS.h>
#else
# include <WiFi.h>
# include <WebServer.h>
# include <NetBIOS.h>
#endif
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ArduinoOTA.h>
#include <WiFiConfig.h>
#include <sysvars.hpp>
#include <EEPROM.h>
#include "src/espnbns/espnbns.h"
#include "src/WiFiConfig/WiFiConfig.h"
// Plati pro desticku Witty s modulem ESP-12E
#define PIN_FORCE_CONFIG 4
#define PIN_LED_RED 15
#define PIN_LED_GREEN 12
#define PIN_LED_BLUE 13
//#define DEBUG_OUT(a) {}
#define DEBUG_OUT(a) Serial.print(a)
char WiFiDeviceName[32]; // misto pro jmeno zarizeni (dodane do DNS, DHCP NBNS apod...)
#if defined(ARDUINO_ARCH_ESP8266)
ESP8266WebServer wwwserver(80); // webovy server
#else
WebServer wwwserver(80); // webovy server
#endif
static char MAINPAGE[] PROGMEM = R"=====(<!DOCTYPE HTML>
<html>
Hello world from ESP8266
<p>
</html>
)=====";
String content;
NBNS nbns; // Netbios (xPablo.cz)
static void handleRoot(void)
{
wwwserver.send_P(200, "text/html", MAINPAGE);
content = F("<!DOCTYPE HTML>\n<html>Hello world from ESP8266");
content += F("<p>");
content += F("</html>");
wwwserver.send(200, "text/html", content);
}
void ICACHE_FLASH_ATTR wcb(wificonfigstate_t state)
{
switch (state) {
switch (state)
{
case WCS_CONNECTSTART:
DEBUG_OUT(F("Starting connect...\r\n"));
break;
DEBUG_OUT(F("Starting connect...\r\n"));
break;
case WCS_CONNECTING:
break;
break;
case WCS_CONNECTED:
DEBUG_OUT(F("Connected.\r\n"));
break;
DEBUG_OUT(F("Connected.\r\n"));
break;
case WCS_CONFIGSTART:
DEBUG_OUT(F("Starting config...\r\n"));
break;
DEBUG_OUT(F("Starting config...\r\n"));
break;
case WCS_CONFIGWAIT:
break;
case WCS_CONFIGTIMEOUT:
DEBUG_OUT(F("Config timeout...\r\n"));
break;
}
break;
}
}
void ICACHE_FLASH_ATTR saveDevname(const char *param)
void saveServer(const char *param)
{
String p = param;
svSetV(F("devname"), p);
DEBUG_OUT(param);
}
void ICACHE_FLASH_ATTR setup()
{
WiFiConfig wifi; // konfigurace ESP modulu
WiFiConfigUsrParameter devname("devname", "Jméno zařízení", (const char *)WiFiDeviceName, 32, saveDevname);
WiFiConfig wifi; // konfigurace ESP modulu
WiFiConfigUsrParameter testOnly("server", "adresa serveru", "Default server", 32, saveServer);
LittleFS.begin();
EEPROM.begin(512); // zahajujeme praci s EEPROM
pinMode(PIN_FORCE_CONFIG, INPUT_PULLUP); // pin, co slouzi jako vstup tlacitka
int fc = digitalRead(PIN_FORCE_CONFIG); // pozadavek na vynucene vyvolani konfigurace
Serial.begin(9600);
wifi.addParameter(&testOnly);
if (WCR_OK != wifi.begin(0, fc, wcb)) // startujeme pripojeni
ESP.restart();
pinMode(PIN_FORCE_CONFIG, INPUT_PULLUP); // pin, co slouzi jako vstup tlacitka
int fc = digitalRead(PIN_FORCE_CONFIG); // pozadavek na vynucene vyvolani konfigurace
Serial.begin(115200);
String dn = svGetV<String>(F("devname"));
strcpy(WiFiDeviceName, dn.c_str());
wifi.addParameter(&devname);
wwwserver.on("/", handleRoot);
wwwserver.begin(); // startujeme webovy server
if (WCR_OK != wifi.begin(fc, wcb)) // startujeme pripojeni
ESP.restart();
if (strlen(WiFiDeviceName) > 0)
{
nbns.begin(WiFiDeviceName);
ArduinoOTA.setHostname(WiFiDeviceName);
}
wwwserver.on("/", handleRoot);
wwwserver.begin(); // startujeme webovy server
ArduinoOTA.onStart([]() {
DEBUG_OUT(F("Start\r\n"));
});
ArduinoOTA.onEnd([]() {
DEBUG_OUT(F("End\r\n"));
});
ArduinoOTA.onError([](ota_error_t error) {
DEBUG_OUT(F("Error["));
DEBUG_OUT(error);
DEBUG_OUT(F("]: "));
switch (error)
{
case OTA_AUTH_ERROR:
DEBUG_OUT(F("Auth Failed\r\n"));
break;
if (strlen(WiFiDeviceName) > 0) {
NBNS.begin(WiFiDeviceName);
ArduinoOTA.setHostname(WiFiDeviceName);
case OTA_BEGIN_ERROR:
DEBUG_OUT(F("Begin Failed\r\n"));
break;
case OTA_CONNECT_ERROR:
DEBUG_OUT(F("Connect Failed\r\n"));
break;
case OTA_RECEIVE_ERROR:
DEBUG_OUT(F("Receive Failed\r\n"));
break;
case OTA_END_ERROR:
DEBUG_OUT(F("End Failed\r\n"));
break;
default:
DEBUG_OUT(F("\r\n"));
}
ArduinoOTA.onStart([]() {
DEBUG_OUT(F("Start\r\n"));
});
ArduinoOTA.onEnd([]() {
DEBUG_OUT(F("End\r\n"));
});
ArduinoOTA.onError([](ota_error_t error) {
DEBUG_OUT(F("Error["));
DEBUG_OUT(error);
DEBUG_OUT(F("]: "));
switch (error) {
case OTA_AUTH_ERROR:
DEBUG_OUT(F("Auth Failed\r\n"));
break;
case OTA_BEGIN_ERROR:
DEBUG_OUT(F("Begin Failed\r\n"));
break;
case OTA_CONNECT_ERROR:
DEBUG_OUT(F("Connect Failed\r\n"));
break;
case OTA_RECEIVE_ERROR:
DEBUG_OUT(F("Receive Failed\r\n"));
break;
case OTA_END_ERROR:
DEBUG_OUT(F("End Failed\r\n"));
break;
default:
DEBUG_OUT(F("\r\n"));
}
});
ArduinoOTA.begin();
});
ArduinoOTA.begin();
}
void loop()
{
wwwserver.handleClient(); // osetrujeme praci serveru
ArduinoOTA.handle();
wwwserver.handleClient(); // osetrujeme praci serveru
ArduinoOTA.handle();
nbns.poll();
}

View File

@ -1,91 +0,0 @@
/*
* v7.0.0- 4.3.2021 - verze s konfiguraci v JSON na souborovem systemu
*
* v6.4.0- 27.2.2021 - funkcni inicializace konfigurace
*
* v6.3.5-28.11.2020 - moznost nadefinovat titulek webove stranky a popisek okna v prohlizeci pomoci WIFICONFIG_TITLE a WIFICONFIG_WEBTITLE
*
* v6.3.4-23.3.2020 - staticka konfigurace v AP rezimu funkcni
*
* v6.3.3-27.10.2019 - volani WS_CONNECTED i v pripade, ze bezi AP
*
* v6.3.2- 4.10.2019 - Informace o aplikaci a jeji verzi do footeru, zrychlen restart z 10 na 5 sekund, vylepsena stranka pro reset
* verze pro ESP32 zobrazuje neco malo informaci o stavu pripojeni a duvodu vstupu do WifiConfig
*
* V6.3.1- 1.9.2019 - Odstraneni HTML5 validatoru - delaly akorat problemy a nedala se ulozit konfigurace i kdyz byly polozky skryty
*
* V6.3 - 12.8.2019 - IP adresa Captive portalu je zmenena na 172.217.28.1 kvuli funkcnosti na Android zarizenich (viz. zmena zde https://github.com/esp8266/Arduino/blob/master/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino)
* ladici vypis pri zachyceni presmerovani v Captive portalu.
*
* V6.2 - 12.12.2018- Nastaveni jmena zarizeni nadale NENI soucasti WiFiConfig a je treba ho pridat jako uzivatelsky parametr. Je to proto, protoze
* se ukazalo, ze neni dobre z externiho kodu sahat do vnitrni struktury WiFiConfig (napr. pri ukladani noveho jmena).
*
* V6.1 - 11.12.2018- Sifrovani retezcu vytazeno mimo WiFiConfig do knihovny encipheredEEPROMStrings (dostupna na gitu) kvuli pristupu i jinych modulu
*
* V6.0 - 20.11.2018- Verze i pro ESP32
*
* V5.9 - 18.7.2018 - Retezce, ukladane do EEPROM jsou primitivnim zpusobem sifrovany pro ztizeni odhaleni SSID a hesla pri dumpu pameti
*
* V5.8 - 5.7.2018 - Opraveno spatne zobrazovani sily signalu v prehledu WiFi siti (spatne barvy)
*
* V5.7 - 4.7.2018 - BugFix - staticka konfigurace ip adresy se neuplatnila - vypada to, jako kdyby SDK ukladalo SSID a Password, ale uz neuklada
* konfiguraci ip adres, takze je treba je vzdycky nastavit znovu
*
* V5.6 - 1.7.2018 - BugFix - odstraneno volani _plusDecode, protoze parametry jsou nyni predavany v 'ciste' forme uz z weboveho serveru a tato metoda znehodnotila retezce, ktere obsahovaly ynak '+'
*
* V5.5 - 3.6.2018 - Flash Chip ID a ESP Chip ID jsou zobrazeny hexadecimalne v prehledove strance
*
* V5.4 - 9.1.2018 - na titulni stranku pridan duvod, proc je spusteny konfiguracni AP. Usnadni to diagnostiku pripadu, kdy se ESP nechce pripojit k AP.
*
* V5.3 - 8.12.2017 - prepracovano presmerovani v Captive portalu, DEBUG_MSG makro upraveno na posledni pouzivanou verzi, scitani retezcu prepracovano na .concat. Pripsany Informace o modulu, reakce na Reset
*
* V5.2 - 20.4.2017 - Pokud je pouzite v timeoutu WC_DONT_RUN_CONFIGAP tak se vracime okamzite a necekame na pripojeni k WiFi (take nevolame zadnou callback metodu).
* Navratovy kod je pak WCR_CONFIGAP_NOT_STARTED .
*
* V5.1 - 3.4.2017 - Webove rozhrani upravene pro snadnejsi ovladani na telefonu/tabletu, sila signalu AP zobrazena jako barevne odliseny indikator.
*
* V5.0 - 29.10.2016- Vyuziti vlastnosti ESP, ktere si uklada wifi konfiguraci do sve vlastni flash oblasti, takze nemusim vse konfigurovat znovu po startu - doufam, ze se tim zrychli asociace s AP
* kvuli bateriove napajenym pristrojum.
*
* V4.7 - 30.8.2016 - Metody .begin se nyni vraci s wificonfigresult_t (podarilo se pripojit k AP, nepodarilo se pripojit a vyprsel timeout pro konfiguracni AP, nepodarilo se pripojit, ale je zakazane spousteni konfiguracniho AP).
* ESP NYNI NENI RESETOVAN PO VYPRSENI TIMEOUTU!!!! Je to kvuli bateriovym cidlum a DeepSleep rezimu v situaci, kdy zmizi AP, ke kteremu se bezne pripojujeme
* Odstraneno odesilani reakce na generate_204 (viz. https://github.com/tzapu/WiFiManager/issues/114)
* Zbytek MAC adresy v pripadnem SSID je nyni vzdy velkymi pismeny (UAA Unique Address Assignment)
* Kvalita signalu jednotlivych AP je nyni uvadena v % namisto uzivatelum nic nerikajicich -dBm
* Pokud do polozky timeout v .begin() metode zadame hodnotu WC_DONT_RUN_CONFIGAP, tak i po neuspesnem pokusu o pripojeni do site NENI spusteny konfiguracni AP (bateriove pristroje, stale bezici pristroje)
*
* V4.6 - 26.7.2016 - Moznost nastavit cislo kanalu pro rezim AP, nove eye-candy rozhrani.
*
* V4.5 - 20.7.2016 - Moznost konfigurovat cislo kanalu pro nastavovaci AP (default je 3), po nacteni konfiguracni stranky je nastaveny timeout na 6 minut, pokud je ve jmenu SSID pro konfiguracni
* AP znak ? (otaznik), tak je tento nahrazen HEXASCII reprezentaci 3 poslednich bytu MAC adresy AP (POZOR!!! je jina, nez STA!!!)
*
* V4.4 - 10.7.2016 - Zmena nazvu vsech privatnich metod (doplnene uvodni podtrzitko _). Pokud tam nebylo, tak napriklad nesel prelozit skript s handleNotFound pokud nebyl dopredne deklarovany (asi zmatek v Arduino preprocesoru)
*
* V4.3 - 23.6.2016 - Kazde nacteni webove stranky prodluzuje pripadny timeout pro restart zarizeni.
*
* V4.2 - 10.6.2016 - DNSServer a WebServer ukazatele jsou nyni staticke primo v modulu WiFiConfig. Predchozi verze neumoznila soucasne pouziti s knihovnami ESPAsyncWebServer z duvodu kolize nekterych definic HTTP metod
*
* V4.1 - 18.5.2016 - Nenechame SDK ukladat WiFi konfiguraci do Flash (setrime prepisy)
*
* V4.0 - 10.4.2016 - pridana moznost staticke konfigurace ip parametru. POZOR!!!! ukladani dat do EEPROM (verejne funkce) nyni nevolaji automaticky commit() kvuli snizeni poctu prepisu Flash EEPROM
* pridana moznost timeoutu pro konfiguracni AP. Pokud timeout vyprsi, tak se zarizeni automaticky restartuje, coz vyvola novy pokus o pripojeni.
*
* V3.0 - 27.2.2016 - pridana presmerovavaci stranka kvuli Captive portalu, doplneno servirovani favicon.ico, doplnena moznost zadavani uzivatelskych parametru, www server a DNS server jsou dynamicky vytvareny
*
* V2.4 - 7.2.2016 - upraveno casovani pri pripojovani k AP (zmizel delay(100))
*
* V2.3 - 5.2.2016 - pridano zverejneni jmena hosta a nastaveni tohoto jmena pro DHCP apod.
*
* V2.2 - 19.1.2016 - pridan Captive portal pri konfiguracnim AP.
*
* V2.1 - 20.9.2015 - pridano zadavani jmena zarizeni. Modul ho sice nevyuziva, ale aplikace ano a v pripade DHCP se dost hodi.
*
* V2.0 - 30.8.2015 - Podstatnym zpusobem vylepsena signalizace vnitrniho stavu, presunuto ulozeni rezimu (commit je uz zbytecny - udela se pri ukladani retezcu - uspora kodu/setreni prepisu pameti Flash)
*
* V1.2 - 23.8.2015 - BugFix - pridan chybejici eeprom.commit() po ulozeni rezimu prace
*
* V1.1 - 5.8.2015 - pridana moznost volani callback metody pri behu konfiguracniho AP (signalizace stavu uzivatelskym zpusobem)
*
* V1.0 - publikace na www.xpablo.cz
*
*/

View File

@ -1,33 +0,0 @@
{
"name":"WiFiConfig",
"description":"Web based WiFi part configuration for the ESP8266 and ESP32 SoC",
"keywords":"wifi, configuration",
"authors":
{
"name": "Pavel Brychta",
"maintainer": true
},
"repository":
{
"type": "git",
"url": "https://git.xpablo.cz/pablo2048/WiFiConfig.git"
},
"dependencies": [
{
"name":"encString",
"version":"https://git.xpablo.cz/xPablo.cz/encString.git"
},
{
"name":"sysvars",
"version":"https://git.xpablo.cz/xPablo.cz/sysvars.git"
}
],
"version": "7.0.0",
"license": "MIT",
"frameworks": "arduino",
"platforms": ["espressif8266", "espressif32"],
"build": {
"libCompatMode": 2,
"libLDFMode": "deep"
}
}

View File

@ -1,9 +1,9 @@
name=WiFiConfig
version=7.0.0
version=5.4.0
author=Pavel Brychta
maintainer=Pavel Brychta <pablo@xpablo.cz>
maintainer=Pavel Brychta <Pablo@xpablo.cz>
sentence=Enables seamless module configuration.
paragraph=With this library you can enable your ESP8266 or ESP32 module to be configured over WiFi. Includes Captive Portal for easy configuration.
paragraph=With this library you can enable your ESP8266 module to be configured over network. Includes Captive Portal for easy configuration.
category=Other
url=https://www.xpablo.cz
architectures=esp8266,esp32
url=http://www.xpablo.cz
architectures=esp8266

View File

@ -1,925 +0,0 @@
#if defined(ESP32)
# include <rom/rtc.h> // duvod resetu (https://github.com/espressif/arduino-esp32/issues/449)
#endif
#include "WiFiConfig.h"
#include <sysvars.hpp>
#include "embHTML.h"
#include <encString.hpp>
#include <definefs.hpp>
#include <FS.h>
#ifdef USE_WIFICONFIG_FSEDITOR
# include <SPIFFSEditor.h>
# include <FSWebEditor.h>
#endif
#ifdef USE_WIFICONFIG_ARDUINO_OTA
# include <ArduinoOTA.h>
#endif
#if defined(ESP8266)
// ESP8266
# define SETHOSTNAME(a) WiFi.hostname(a)
#else
// ESP32
# define SETHOSTNAME(a) WiFi.setHostname(a)
#endif
#ifndef DEBUG_MSG
# ifdef DEBUG_ESP_PORT
# define DEBUG_MSG(_1, ...) DEBUG_ESP_PORT.printf_P(PSTR(_1), ##__VA_ARGS__)
# else
# define DEBUG_MSG(...)
# endif
#endif
#if defined(ESP8266)
extern "C" {
# include "user_interface.h"
}
#else
# include <esp_wifi.h>
#endif
String WifiConfigAPSSID(void) __attribute__((weak));
#define DNS_PORT 53
extern char WiFiDeviceName[];
static const char CHECKED[] PROGMEM = "checked='checked'";
static bool _doReconfig = false; // TODO: mozna nejak elegantneji? Ale zase setrime RAM...
String WifiConfigAPSSID(void)
{
String ssid = F(SETUP_SSID);
return ssid;
}
static uint32_t ESP_getChipId(void)
{
#if defined(ESP8266)
return ESP.getChipId();
#else
uint32_t id = 0;
for (int i = 0; i < 17; i = i + 8) {
id |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
}
return id;
#endif
}
IPAddress getOurIP(void)
{
IPAddress ipa;
WiFiMode_t wm = WiFi.getMode();
switch (wm) {
case WIFI_STA:
ipa = WiFi.localIP();
break;
case WIFI_AP:
ipa = WiFi.softAPIP();
break;
default:
ipa = IPAddress(0, 0, 0, 0); // nelze urcit ip adresu (bud je AP + STA aktivni, nebo je vypnute WiFi)
break;
}
return ipa;
}
uint8_t * getOurMAC(uint8_t *mac)
{
if (WIFIMODE_STA == svGetV<int>(F("mode"), nullptr, F(WIFICFG_FILE)))
return WiFi.macAddress(mac);
else
return WiFi.softAPmacAddress(mac);
}
WiFiConfigUsrParameter::WiFiConfigUsrParameter(const char *id, const char *label, const char *defaultValue, unsigned int length, storeparam_cb cb)
{
_cb = cb;
_id = id;
_label = label;
_length = length;
_value = new char[length + 1];
_value[0] = 0;
if (defaultValue != NULL) {
strncpy(_value, defaultValue, length);
}
}
const char* WiFiConfigUsrParameter::getValue()
{
return _value;
}
const char* WiFiConfigUsrParameter::getID()
{
return _id;
}
const char* WiFiConfigUsrParameter::getLabel()
{
return _label;
}
int WiFiConfigUsrParameter::getValueLength()
{
return _length;
}
void WiFiConfigUsrParameter::setNext(WiFiConfigUsrParameter *n)
{
_next = n;
}
WiFiConfigUsrParameter *WiFiConfigUsrParameter::getNext()
{
return _next;
}
void WiFiConfigUsrParameter::setNewValue(const char *newval)
{
if (0 != strcmp(_value, newval))
_cb(newval);
}
WiFiConfigUsrParameter *WiFiConfig::_searchUsrParameter(const char *name)
{
WiFiConfigUsrParameter *ptr = _params;
while (NULL != ptr) {
if (0 == strcmp(name, ptr->getID()))
break;
ptr = ptr->getNext();
}
return ptr;
}
void WiFiConfig::addParameter(WiFiConfigUsrParameter *p)
{
p->setNext(_params);
_params = p;
}
String WiFiConfig::infoProcessor(const String & var)
{
if (var == F("SDK")) {
#if defined(ESP8266)
return ESP.getFullVersion();
#else
// TODO
return ESP.getSdkVersion();
#endif
} else if (var == F("FS")) {
#if defined(ESP8266)
return String(ESP.getFlashChipRealSize() / 1024);
#else
// TODO
return String(ESP.getFlashChipSize());
#endif
} else if (var == F("SS")) {
return String(ESP.getSketchSize() / 1024);
} else if (var == F("FSS")) {
return String(ESP.getFreeSketchSpace() / 1024);
} else if (var == F("STAMAC")) {
uint8_t mac[6];
uint8_t* macread = WiFi.macAddress(mac);
char macaddress[20];
sprintf_P(macaddress, PSTR("%02x:%02x:%02x:%02x:%02x:%02x"), macread[0], macread[1], macread[2], macread[3], macread[4], macread[5]);
return String(macaddress);
} else if (var == F("APMAC")) {
uint8_t mac[6];
char macaddress[20];
uint8_t *macread = WiFi.softAPmacAddress(mac);
sprintf_P(macaddress, PSTR("%02x:%02x:%02x:%02x:%02x:%02x"), macread[0], macread[1], macread[2], macread[3], macread[4], macread[5]);
return String(macaddress);
} else if (var == F("ESPID")) {
char buff[8];
sprintf_P(buff, PSTR("%06X"), ESP_getChipId());
return String(buff);
} else if (var == F("FID")){
#if defined(ESP8266)
char buff[10];
sprintf_P(buff, PSTR("%08X"), ESP.getFlashChipId());
return String(buff);
#endif
}
return String(F("???"));
}
String WiFiConfig::apProcessor(const String &var)
{
if (var == F("USER")) {
String result;
if (_params) {
WiFiConfigUsrParameter *up = _params;
char buff[128];
result.reserve(1024);
result = FPSTR(PAGE_PARAM_HDR);
while (NULL != up) {
sprintf_P(buff, PAGE_PARAM, up->getLabel(), up->getID(), up->getValueLength(), up->getValue());
result.concat(buff);
up = up->getNext();
}
}
return result;
} else if (var == F("SSID")) {
String result = svGetV<String>(F("ssid"), nullptr, F(WIFICFG_FILE));
strDecode(result);
return result;
} else if (var == F("PASS")) {
String result = svGetV<String>(F("pass"), nullptr, F(WIFICFG_FILE));
strDecode(result);
return result;
} else if (var == F("APMODE")) {
String result;
if (svGetV<int>(F("mode"), nullptr, F(WIFICFG_FILE)) == WIFIMODE_AP)
result = FPSTR(CHECKED);
return result;
} else if (var == F("APCHAN")) {
String result;
uint8_t chan = svGetV<int>(F("channel"), nullptr, F(WIFICFG_FILE));
if ((chan < 1) || (chan > 13))
chan = 1; // neplatne cislo kanalu nahradime nejnizsim
result = String(chan);
return result;
} else if (var == F("STATIC")) {
String result;
if (svGetV<int>(F("ipmode"), nullptr, F(WIFICFG_FILE)) == IPCONFIG_STATIC)
result = FPSTR(CHECKED);
return result;
} else if (var == F("IP")) {
String result;
result = _getIP(F("ip")).toString();
return result;
} else if (var == F("MASK")) {
String result;
result = _getIP(F("mask")).toString();
return result;
} else if (var == F("GATE")) {
String result;
result = _getIP(F("gw")).toString();
return result;
} else if(var == F("DNS")) {
String result;
result = _getIP(F("dns")).toString();
return result;
}
return String();
}
String WiFiConfig::rootProcessor(const String &var)
{
String content;
if (var == "STATUS") {
switch (_status) {
#if defined(ESP8266)
case STATION_IDLE:
content = F("Klid");
break;
case STATION_CONNECTING:
content = F("Připojování");
break;
case STATION_WRONG_PASSWORD:
content = F("Špatné heslo");
break;
case STATION_NO_AP_FOUND:
content = F("AP nenalezen");
break;
case STATION_CONNECT_FAIL:
content = F("Připojení selhalo");
break;
case STATION_GOT_IP:
content = F("Získaná ip");
break;
case 0xfe:
content = F("Špatná konfigurace");
break;
case 0xff:
content = F("Vynucená konfigurace");
break;
default:
content = F("Neznámý");
break;
#else
case WL_IDLE_STATUS:
content = F("Klid");
break;
case WL_NO_SSID_AVAIL:
content = F("AP nenalezen");
break;
case WL_CONNECT_FAILED:
content = F("Připojení selhalo");
break;
case 0xfe:
content = F("Špatná konfigurace");
break;
case 0xff:
content = F("Vynucená konfigurace");
break;
default:
content = F("Neznámý");
break;
#endif
}
} else if (var == F("RESTORE")) {
if (USEDFS.exists(F(WIFICFG_OLD_FILE))) {
content = FPSTR(PAGE_RESTORE);
}
}
return content;
}
void WiFiConfig::_handleRestore(AsyncWebServerRequest *request)
{
USEDFS.remove(F(WIFICFG_FILE));
USEDFS.rename(F(WIFICFG_OLD_FILE), F(WIFICFG_FILE));
request->onDisconnect([]() {
_doReconfig = true; // aktivujeme novou konfiguraci a restartujeme ESP
});
request->send_P(200, TEXTHTML, PAGE_SAVED);
}
void WiFiConfig::_handleNotFound(AsyncWebServerRequest *request)
{
DEBUG_MSG("Requested URI: %s\r\n", request->url().c_str());
if (request->url().endsWith(String(F("favicon.ico")))) {
request->send_P(404, TEXTPLAIN, PSTR("Err"));
} else {
String redirect;
redirect.reserve(256);
redirect = F("http://");
redirect.concat(WiFi.softAPIP().toString());
redirect.concat(F("/index.htm"));
DEBUG_MSG("Redirection to: %s\r\n", redirect.c_str());
request->redirect(redirect);
}
}
void WiFiConfig::_handleReset(AsyncWebServerRequest *request)
{
request->onDisconnect([]() {
ESP.restart();
});
request->send_P(200, TEXTHTML, PAGE_RESTART);
}
void WiFiConfig::_handleScan(AsyncWebServerRequest *request)
{
String json;
int n = WiFi.scanComplete();
json.reserve(1024);
json = F("{\"status\":");
json.concat(String(n));
json.concat(F(",\"ssids\":["));
if (n == WIFI_SCAN_FAILED) {
WiFi.scanNetworks(true);
} else if (n) {
for (int i = 0; i < n; ++i) {
if (i)
json.concat(F(","));
json.concat(("{\"rssi\":"));
json.concat(String(WiFi.RSSI(i)));
json.concat(F(",\"ssid\":\""));
json.concat(WiFi.SSID(i));
json.concat(F("\",\"channel\":"));
json.concat(String(WiFi.channel(i)));
json.concat(F(",\"secure\":"));
json.concat(String(WiFi.encryptionType(i)));
json.concat(F("}"));
}
WiFi.scanDelete();
if (WiFi.scanComplete() == WIFI_SCAN_FAILED) {
WiFi.scanNetworks(true);
}
}
json.concat(F("]}"));
request->send(200, FPSTR(TEXTJSON), json);
}
void WiFiConfig::_handleInfo(AsyncWebServerRequest *request)
{
request->send_P(200, TEXTHTML, PAGE_INFO, std::bind(&WiFiConfig::infoProcessor, this, std::placeholders::_1));
}
void WiFiConfig::_handleRoot(AsyncWebServerRequest *request)
{
request->send_P(200, TEXTHTML, PAGE_CAPTIVEPORTALCATCH, std::bind(&WiFiConfig::rootProcessor, this, std::placeholders::_1));
_time = millis() + (_timeout * 1000); // spocitame si novy cas, kdy budeme modul restartovat
}
IPAddress WiFiConfig::_getIP(const String &from)
{
uint32_t ipa;
int result;
ipa = svGetV<uint32_t>(from, &result, F(WIFICFG_FILE));
if (SV_OK != result)
ipa = 0;
return IPAddress(ipa);
}
void WiFiConfig::_handleDisplayAP(AsyncWebServerRequest *request)
{
request->send_P(200, TEXTHTML, PAGE_INDEX1, std::bind(&WiFiConfig::apProcessor, this, std::placeholders::_1));
_time = millis() + (360 * 1000); // spocitame si novy cas, kdy budeme modul restartovat (6 minut)
}
void WiFiConfig::_handleSetAP(AsyncWebServerRequest *request)
{
String str;
str.reserve(128);
str = request->arg(F("_s"));
if (str.length() > 0) {
uint8_t mode;
if (USEDFS.exists(F(WIFICFG_OLD_FILE))) {
USEDFS.remove(F(WIFICFG_OLD_FILE));
}
USEDFS.rename(F(WIFICFG_FILE), F(WIFICFG_OLD_FILE));
strEncode(str);
svSetV(F("ssid"), str, F(WIFICFG_FILE));
str = request->arg(F("_p"));
strEncode(str);
svSetV(F("pass"), str, F(WIFICFG_FILE));
str = request->arg(F("_a"));
if (str.length() > 0) {
mode = WIFIMODE_AP; // rezim AP
str = request->arg(F("_ch")); // kanal AP
svSetV<int>(F("channel"), str.toInt(), F(WIFICFG_FILE));
} else
mode = WIFIMODE_STA; // rezim STA
svSetV(F("mode"), mode, F(WIFICFG_FILE));
str = request->arg(F("_st"));
if (0 == str.length())
svSetV<int>(F("ipmode"), IPCONFIG_DHCP, F(WIFICFG_FILE)); // mame DHCP dynamickou konfiguraci
else {
// staticka ip konfigurace
IPAddress ipa;
svSetV<int>(F("ipmode"), IPCONFIG_STATIC, F(WIFICFG_FILE)); // mame statickou konfiguraci
str = request->arg(F("_i"));
ipa.fromString(str);
svSetV<uint32_t>(F("ip"), (uint32_t)ipa, F(WIFICFG_FILE));
str = request->arg(F("_m"));
ipa.fromString(str);
svSetV<uint32_t>(F("mask"), (uint32_t)ipa, F(WIFICFG_FILE));
str = request->arg(F("_g"));
ipa.fromString(str);
svSetV<uint32_t>(F("gw"), (uint32_t)ipa, F(WIFICFG_FILE));
str = request->arg(F("_d"));
ipa.fromString(str);
svSetV<uint32_t>(F("dns"), (uint32_t)ipa, F(WIFICFG_FILE));
}
// Uzivatelske parametry
for (unsigned i = 0; i < request->args(); i++) {
if (!request->argName(i).startsWith(F("_"))) { // vnitrni parametry WiFiConfig modulu zacinaji _, takze ty muzeme ignorovat
WiFiConfigUsrParameter *up = _searchUsrParameter(request->argName(i).c_str());
if (NULL != up)
up->setNewValue(request->arg(i).c_str());
}
}
}
request->onDisconnect([]() {
_doReconfig = true; // aktivujeme novou konfiguraci a restartujeme ESP
});
request->send_P(200, TEXTHTML, PAGE_SAVED);
}
// Start WiFi v rezimu AP pro nastaveni modulu
wificonfigresult_t WiFiConfig::_setupAP(wificonfig_cb cb)
{
String ssid = WifiConfigAPSSID();
WiFi.persistent(false); // chranime flash pred zbytecnymi prepisy
dnsServer.reset(new DNSServer());
server = new AsyncWebServer(80);
server->reset();
/* Soft AP network parameters */
IPAddress apIP(172, 217, 28, 1);
IPAddress netMsk(255, 255, 255, 0);
WiFi.disconnect(); // pro jistotu se odpojime
// WiFi.mode(WIFI_AP);
#if defined(ARDUINO_ARCH_ESP8266)
WiFi.softAPConfig(apIP, apIP, netMsk);
if (ssid.endsWith(F("?"))) {
char lmac[16];
sprintf_P(lmac, PSTR("%06X"), ESP_getChipId());
ssid.replace(F("?"), String(lmac));
}
WiFi.softAP(ssid.c_str(), NULL, SETUP_CHANNEL);
WiFi.mode(WIFI_AP);
delay(500); // dulezite - jinak se nevraci spravna IP adresa !!! (udajne od verze 2.3.0 uz neni nutne)
#else
// osetreni padu ESP32 - https://github.com/espressif/arduino-esp32/issues/2025
if (ssid.endsWith(F("?"))) {
char lmac[16];
sprintf_P(lmac, PSTR("%06X"), ESP_getChipId());
ssid.replace(F("?"), String(lmac));
}
WiFi.softAP(ssid.c_str(), NULL, SETUP_CHANNEL);
delay(100); // kvuli ESP32 - cekame na start AP
WiFi.softAPConfig(apIP, apIP, netMsk);
#endif
dnsServer->setErrorReplyCode(DNSReplyCode::NoError);
dnsServer->start(DNS_PORT, "*", WiFi.softAPIP()); // spustime tzv. Captive portal - vsechny DNS dotazy jsou smerovany na nasi ip adresu
if (cb)
cb(WCS_CONFIGSTART); // signalizujeme start konfiguracniho serveru
// Nastavime handlery weboveho serveru pro konfiguraci
server->onNotFound(std::bind(&WiFiConfig::_handleNotFound, this, std::placeholders::_1));
server->on(PSTR("/config"), std::bind(&WiFiConfig::_handleDisplayAP, this, std::placeholders::_1));
server->on(PSTR("/scan"), std::bind(&WiFiConfig::_handleScan, this, std::placeholders::_1));
server->on(PSTR("/s"), std::bind(&WiFiConfig::_handleSetAP, this, std::placeholders::_1));
server->on(PSTR("/r"), std::bind(&WiFiConfig::_handleReset, this, std::placeholders::_1));
server->on(PSTR("/i"), std::bind(&WiFiConfig::_handleInfo, this, std::placeholders::_1));
server->on(PSTR("/o"), std::bind(&WiFiConfig::_handleRestore, this, std::placeholders::_1));
server->on(PSTR("/index.htm"), std::bind(&WiFiConfig::_handleRoot, this, std::placeholders::_1));
#ifdef USE_WIFICONFIG_OTAUPDATE
server->on(PSTR("/u"), []() {
server->send_P(200, TEXTHTML, PAGE_UPDATE);
});
server->on(PSTR("/update"), HTTP_POST, []() {
server->sendHeader(F("Connection"), F("close"));
server->send(200, FPSTR(TEXTPLAIN), (Update.hasError()) ? F("FAIL") : F("OK"));
ESP.restart();
}, []() {
HTTPUpload& upload = server->upload();
if (upload.status == UPLOAD_FILE_START) {
WiFiUDP::stopAll();
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
if (!Update.begin(maxSketchSpace)) { //start with max available size
//Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
//Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
DEBUG_MSG("WifiConfig: Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
//Update.printError(Serial);
}
}
yield();
});
#endif
#ifdef USE_WIFICONFIG_ARDUINO_OTA
ArduinoOTA.begin();
#endif
#ifdef USE_WIFICONFIG_FSEDITOR
#if 0
#if defined(ESP8266)
server->addHandler(new SPIFFSEditor("admin", "nimda", USEDFS));
#else
server->addHandler(new SPIFFSEditor(USEDFS, "admin", "nimda"));
#endif
#else
#if defined(ESP8266)
server->addHandler(new FSWebEditor("admin", "nimda"));
#else
server->addHandler(new FSWebEditor(USEDFS, "admin", "nimda"));
#endif
#endif
#endif
server->begin(); // startujeme webovy server
// Asynchronne ziskame seznam okolnich AP prakticky okamzite po startu konfiguracniho AP
int n = WiFi.scanComplete();
if (n == WIFI_SCAN_FAILED) {
WiFi.scanNetworks(true);
}
while (1) {
if (_doReconfig) {
// mame aktivovat novou konfiguraci
_prepareWifi();
ESP.restart();
}
if (cb)
cb(WCS_CONFIGWAIT); // volame uzivatelsky callback (napr. signalizace)
dnsServer->processNextRequest();
#ifdef USE_WIFICONFIG_ARDUINO_OTA
ArduinoOTA.handle();
#endif
yield(); // procesy uvnitr systemu ESP potrebuji take svuj cas
if (_timeout) {
if (millis() > _time) {
DEBUG_MSG("AP timeout\r\n");
if (cb)
cb(WCS_CONFIGTIMEOUT); // signalizujeme timeout
break; // ukoncime cekani a vracime se
}
}
}
// tady by asi melo byt zastaveni weboveho a dns serveru...
dnsServer->stop();
server->end();
#ifdef USE_WIFICONFIG_ARDUINO_OTA
# if defined(ESP32)
ArduinoOTA.end();
# endif
#endif
return WCR_TIMEOUT; // nepripojeno, vyprsel timeout konfiguracniho AP
}
// Testovani, zda se modul pripojil k AP
bool WiFiConfig::_testWifi(wificonfig_cb cb)
{
uint32_t startt = millis();
#if !defined(ESP8266)
_prepareWifi(); // nakonfigurujeme ESP32 dle nastavenych parametru
#endif
DEBUG_MSG("Trying to connect.\r\n");
while ((millis() - startt) < WIFI_STA_CONNECT_TIMEOUT) {
if (WL_CONNECTED == WiFi.status()) {
DEBUG_MSG("Connected...\r\n");
if (cb)
cb(WCS_CONNECTED);
return true; // jsme pripojeni
}
yield();
if (cb)
cb(WCS_CONNECTING); // signalizujeme pokracujici pokus o spojeni
}
DEBUG_MSG("Not connected!\r\n");
#if defined(ESP8266)
_status = wifi_station_get_connect_status();
#else
_status = WiFi.status();
#endif
return false; // pripojeni se nezdarilo
}
wificonfigresult_t WiFiConfig::begin(int forceConfigure, wificonfig_cb cb)
{
wificonfigresult_t result = WCR_OK; // predpokladame, ze se pripojeni podari
DEBUG_MSG("\r\n\r\n"); // oddeleni vypisu
if (0 == forceConfigure) {
DEBUG_MSG("Force config.\r\n");
_status = 0xff;
result = _setupAP(cb);
} else {
#if defined(ESP8266)
if (svGetV<int>(F("mode"), nullptr, F(WIFICFG_FILE)) != WiFi.getMode()) {
// neshoduje se rezim - musime spustit konfiguracni AP (poskozena konfigurace)
DEBUG_MSG("Wrong config (%d, %d)\r\n", svGetV<int>(F("mode"), nullptr, F(WIFICFG_FILE)), WiFi.getMode());
_status = 0xfe;
result = _setupAP(cb);
} else
#endif
{
switch (svGetV<int>(F("mode"), nullptr, F(WIFICFG_FILE))) {
case WIFIMODE_STA: {
DEBUG_MSG("STA mode.\r\n");
SETHOSTNAME(WiFiDeviceName); // nastavime jmeno zarizeni
if (IPCONFIG_STATIC == svGetV<int>(F("ipmode"), nullptr, F(WIFICFG_FILE))) {
DEBUG_MSG("Static configuration SET.\r\n");
WiFi.config(IPAddress(svGetV<uint32_t>(F("ip"), nullptr, F(WIFICFG_FILE))), IPAddress(svGetV<uint32_t>(F("gw"), nullptr, F(WIFICFG_FILE))),
IPAddress(svGetV<uint32_t>(F("mask"), nullptr, F(WIFICFG_FILE))), IPAddress(svGetV<uint32_t>(F("dns"), nullptr, F(WIFICFG_FILE))));
delay(100);
}
if (WC_DONT_RUN_CONFIGAP == _timeout)
result = WCR_CONFIGAP_NOT_STARTED; // nemame spoustet konfiguracni AP - vracime se hned
else {
if (cb)
cb(WCS_CONNECTSTART); // signalizujeme zacatek pokusu o pripojeni
if (!_testWifi(cb)) {
result = _setupAP(cb); // modul se nepripojil - startujeme AP rezim
}
}
}
break;
case WIFIMODE_AP:
DEBUG_MSG("AP mode.\r\n");
if (IPCONFIG_STATIC == svGetV<int>(F("ipmode"), nullptr, F(WIFICFG_FILE))) {
WiFi.softAPConfig(IPAddress(svGetV<uint32_t>(F("ip"), nullptr, F(WIFICFG_FILE))), IPAddress(svGetV<uint32_t>(F("gw"), nullptr, F(WIFICFG_FILE))),
IPAddress(svGetV<uint32_t>(F("mask"), nullptr, F(WIFICFG_FILE))));
}
if (cb)
cb(WCS_CONNECTED); // signalizujeme pripojeni (zde se nic jineho stejne nestane...)
break;
#if !defined(ESP8266)
default:
DEBUG_MSG("Wrong config (%d)\r\n", svGetV<int>(F("mode"), nullptr, F(WIFICFG_FILE)));
_status = 0xfe;
result = _setupAP(cb);
break;
#endif
}
}
}
return result; // mame vyreseno
}
wificonfigresult_t WiFiConfig::begin(int forceConfigure, int timeout, wificonfig_cb cb = NULL)
{
if ((timeout > 0) && (40 > timeout))
timeout = 40; // timeout musi byt minimalne 40 sekund
if ((0 == forceConfigure) && (WC_DONT_RUN_CONFIGAP == timeout))
timeout = 40;
_timeout = timeout;
if (_timeout > 0)
_time = millis() + (_timeout * 1000); // spocitame si novy cas, kdy budeme modul restartovat
return begin(forceConfigure, cb); // spustime WiFi
}
#if defined(ESP32)
static const char INITTXT[] = "{}";
#endif
void WiFiConfig::initConfig(const String &ssid, const String &pass, const int mode, const int ipcfg, const IPAddress &ip, const IPAddress &mask, const IPAddress &gw, const IPAddress &dns)
{
String es;
DEBUG_MSG("initConfig %d\r\n", mode);
if (!USEDFS.exists(F(WIFICFG_FILE))) {
DEBUG_MSG("Create file...\r\n");
File f;
f = USEDFS.open(F(WIFICFG_FILE), "w");
#if defined(ESP8266)
f.write("{}");
#else
f.write((const uint8_t *)INITTXT, strlen(INITTXT));
#endif
f.close();
}
es = ssid;
strEncode(es);
svSetV<String>(F("ssid"), es, F(WIFICFG_FILE));
es = pass;
strEncode(es);
svSetV<String>(F("pass"), es, F(WIFICFG_FILE));
svSetV(F("mode"), mode, F(WIFICFG_FILE));
svSetV(F("ipmode"), ipcfg, F(WIFICFG_FILE));
svSetV<int>(F("channel"), 3, F(WIFICFG_FILE));
svSetV<uint32_t>(F("ip"), (uint32_t)ip, F(WIFICFG_FILE));
svSetV<uint32_t>(F("mask"), (uint32_t)mask, F(WIFICFG_FILE));
svSetV<uint32_t>(F("gw"), (uint32_t)gw, F(WIFICFG_FILE));
svSetV<uint32_t>(F("dns"), (uint32_t)dns, F(WIFICFG_FILE));
_prepareWifi(); // nastavime novou WiFi konfiguraci
}
void WiFiConfig::_prepareWifi(void)
{
DEBUG_MSG("Prepare wifi...\r\n");
WiFi.persistent(true); // chceme, aby si modul zapamatoval konfiguraci
WiFi.disconnect(); // vsechno odpojime
delay(100);
String s = svGetV<String>(F("ssid"), nullptr, F(WIFICFG_FILE));
strDecode(s);
String pass = svGetV<String>(F("pass"), nullptr, F(WIFICFG_FILE));
strDecode(pass);
int mode = svGetV<int>(F("mode"), nullptr, F(WIFICFG_FILE));
DEBUG_MSG("SSID %s, Pass %s, Mode %d\r\n", s.c_str(), pass.c_str(), mode);
switch (mode) {
case WIFIMODE_STA: {
DEBUG_MSG("STA mode.\r\n");
#if defined(ESP8266)
if (strlen(WiFiDeviceName)) {
SETHOSTNAME(WiFiDeviceName); // nastavime jmeno zarizeni
}
#endif
if (IPCONFIG_STATIC == svGetV<int>(F("ipmode"), nullptr, F(WIFICFG_FILE))) {
DEBUG_MSG("Static configuration.\r\n");
WiFi.config(IPAddress(svGetV<uint32_t>(F("ip"), nullptr, F(WIFICFG_FILE))), IPAddress(svGetV<uint32_t>(F("gw"), nullptr, F(WIFICFG_FILE))),
IPAddress(svGetV<uint32_t>(F("mask"), nullptr, F(WIFICFG_FILE))), IPAddress(svGetV<uint32_t>(F("dns"), nullptr, F(WIFICFG_FILE))));
delay(100);
}
WiFi.mode(WIFI_STA); // startujeme WiFi v rezimu klienta
WiFi.begin(s.c_str(), pass.c_str());
DEBUG_MSG("STA params: %s, %s\r\n", s.c_str(), pass.c_str());
#if !defined(ESP8266)
if (strlen(WiFiDeviceName)) {
SETHOSTNAME(WiFiDeviceName); // nastavime jmeno zarizeni
}
#endif
#if defined(ESP8266)
WiFi.setAutoConnect(true);
WiFi.setAutoReconnect(true);
// wifi_station_set_auto_connect(true);
#else
//esp_wifi_set_auto_connect(true);
#endif
delay(1000);
}
break;
case WIFIMODE_AP:{
DEBUG_MSG("AP mode.\r\n");
if (s.endsWith(F("?"))) {
char lmac[16];
sprintf_P(lmac, PSTR("%06X"), ESP_getChipId());
s.replace(F("?"), String(lmac));
}
WiFi.mode(WIFI_AP); // startujeme AP
int chan = svGetV<int>(F("channel"), nullptr, F(WIFICFG_FILE));
if (pass.length()) {
// je zadane heslo do AP
WiFi.softAP(s.c_str(), pass.c_str(), chan);
} else {
// otevreny AP
WiFi.softAP(s.c_str(), NULL, chan);
}
if (IPCONFIG_STATIC == svGetV<int>(F("ipmode"), nullptr, F(WIFICFG_FILE))) {
delay(100); // kvuli ESP32 - cekame na start AP
WiFi.softAPConfig(IPAddress(svGetV<uint32_t>(F("ip"), nullptr, F(WIFICFG_FILE))), IPAddress(svGetV<uint32_t>(F("gw"), nullptr, F(WIFICFG_FILE))),
IPAddress(svGetV<uint32_t>(F("mask"), nullptr, F(WIFICFG_FILE))));
}
break;
}
default: // jakykoliv neznamy rezim (mozna zavada na EEPROM???)
DEBUG_MSG("Mode Error (%d)!!\r\n", (int)mode);
break;
}
delay(1000); // cekame XX sekund na ulozeni atd...
}
// EOF

View File

@ -1,178 +0,0 @@
/**
* @file WiFiConfig.h
* @author Pavel Brychta, http://www.xpablo.cz
*
* Copyright (c) 2015-21 Pavel Brychta. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/* Nastaveni ESP modulu, ktere pracuje takto:
* 1. Pokud je forceConfigure ==0, tak se aktivuje WiFi v rezimu AP a cele ESP je mozne nastavit webovym rozhranim (pocitam s prenosem hodnoty nouzoveho tlacitka pri startu).
* 2. Neni-li tlacitko stisknute, tak se vezme rezim prace a AP se nastavi dle nej (WIFI_STA a WIFI_AP)
* 3. Pokud byl rezim prace WIFI_STA a ESP se nepripoji k zadne siti do casu WIFI_STA_CONNECT_TIMEOUT, tak se pokracuje jako kdyby bylo stisknute rekonfiguracni tlacitko
* Podrobnejsi informace o upravach chovani v jednotlivych verzich jsou v zahlavi .cpp souboru.
*/
#ifndef __WiFiConfig_h__
#define __WiFiConfig_h__
#if defined(ESP8266)
# include <ESP8266WiFi.h>
#else
# include <WiFi.h>
#endif
#include <memory>
#include <ESPAsyncWebServer.h>
#include <DNSServer.h>
#if TEMPLATE_PLACEHOLDER != '$'
# error 'Need to redefine TEPLATE_PLACEHOLDER to $ sign'
#endif
#define WC_DONT_RUN_CONFIGAP -1 // priznak, ze si neprejeme spoustet konfiguracni AP (uziva se misto parametru timeout). Urceno pro bateriove napajene pristroje
#if not defined(WIFICFG_FILE)
# define WIFICFG_FILE "/wifi.json"
#endif
#if not defined(WIFICFG_OLD_FILE)
# define WIFICFG_OLD_FILE "/wifi.old"
#endif
// Parametr, predany uzivatelske callback funkci, urceny pro aplikacni vizualizaci stavu konfigurace a pripojeni
typedef enum {
WCS_CONNECTSTART = 0, // zacatek pokusu o pripojeni k ulozene konfiguraci
WCS_CONNECTING = 1, // probiha pokus o pripojeni
WCS_CONNECTED = 2, // pripojeni bylo uspesne/byl spusteny AP
WCS_CONFIGSTART = 3, // zacatek startu konfiguracniho AP
WCS_CONFIGWAIT = 4, // cekame na nastaveni konfigurace pres web
WCS_CONFIGTIMEOUT = 5, // doslo k vyprseni timeoutu konfigurace, budeme se vracet s False jako vysledek z .begin(...)
} wificonfigstate_t;
// Navratovy parametr z volani begin() - udava, jak se podarilo WiFiConfig modulu pripojit k AP
typedef enum {
WCR_OK = 0, // wifi pripojena/AP nastartovane (dle parametru v EEPROM)
WCR_TIMEOUT = 1, // wifi neni pripojena a vyprsel zadany timeout
WCR_CONFIGAP_NOT_STARTED = 2, // wifi neni pripojena a spusteni konfiguracniho AP bylo zakazane parametrem timeout (WC_DONT_RUN_CONFIGAP)
} wificonfigresult_t;
// Interni reprezentace konfigurace WiFi
enum {
WIFIMODE_AP = WIFI_AP, // rezim prace jako pristupovy bod (AP)
WIFIMODE_STA = WIFI_STA, // rezim prace jako klient
WIFIMODE_AP_STA = WIFI_AP_STA // rezim prace jako klient i pristupovy bod
};
// Interni reprezentace konfigurace ip
enum {
IPCONFIG_DHCP = 0x55, // DHCP konfigurace ip adres (default)
IPCONFIG_STATIC = 0xaa // staticka konfigurace ip adres
};
typedef void (*wificonfig_cb)(wificonfigstate_t state); // definice callbacku
typedef void (*storeparam_cb)(const char *newvalue); // callback pro ulozeni uzivatelskeho parametru
#ifndef WIFI_STA_CONNECT_TIMEOUT
# define WIFI_STA_CONNECT_TIMEOUT 20000UL // delka cekani na pripojeni k AP [ms]
#endif
#ifndef SETUP_SSID
# define SETUP_SSID "ESPPBSetup_?"
#endif
#ifndef SETUP_CHANNEL
# define SETUP_CHANNEL 3
#endif
/**
* \brief Ziskani nasi ip adresy
*
* \return Nase ip adresa, ziskana dle rezimu prace modulu
*/
IPAddress getOurIP(void);
/**
* \brief Ziskani nasi MAC adresy
*
* \param [in] mac kam ma byt MAC adresa ulozena
* \return Ukazatel na ulozenou MAC adresu (vraci parametr mac)
*
* \details Details
*/
uint8_t * getOurMAC(uint8_t *mac);
class WiFiConfigUsrParameter
{
public:
WiFiConfigUsrParameter(const char *id, const char *label, const char *defaultValue, unsigned int length, storeparam_cb cb);
const char *getID();
const char *getValue();
const char *getLabel();
int getValueLength();
void setNext(WiFiConfigUsrParameter *n);
WiFiConfigUsrParameter *getNext();
void setNewValue(const char *newval);
private:
const char *_id;
const char *_label;
char *_value;
int _length;
storeparam_cb _cb;
WiFiConfigUsrParameter *_next = nullptr;
};
class WiFiConfig
{
public:
WiFiConfig()
: _params(nullptr)
, _timeout(0)
{}
wificonfigresult_t begin(int forceConfigure, wificonfig_cb cb);
wificonfigresult_t begin(int forceConfigure, int timeout, wificonfig_cb cb);
void addParameter(WiFiConfigUsrParameter *p);
void initConfig(const String &ssid, const String &pass, const int mode = WIFIMODE_STA, const int ipcfg = IPCONFIG_DHCP, const IPAddress &ip = (uint32_t)0, const IPAddress &mask = (uint32_t)0, const IPAddress &gw = (uint32_t)0, const IPAddress &dns = (uint32_t)0);
private:
AsyncWebServer *server;
std::unique_ptr<DNSServer> dnsServer;
void _prepareWifi(void);
wificonfigresult_t _setupAP(wificonfig_cb cb);
void _handleDisplayAP(AsyncWebServerRequest *request);
void _handleSetAP(AsyncWebServerRequest *request);
void _handleInfo(AsyncWebServerRequest *request);
void _handleReset(AsyncWebServerRequest *request);
void _handleNotFound(AsyncWebServerRequest *request); // CaptivePortal redirector
void _handleRoot(AsyncWebServerRequest *request); // jen jednoducha stranka kvuli CaptivePortalu umoznuje prejit na spravnou stranku (ale nedela to...)
void _handleScan(AsyncWebServerRequest *request);
void _handleRestore(AsyncWebServerRequest *request);
bool _testWifi(wificonfig_cb cb);
WiFiConfigUsrParameter *_searchUsrParameter(const char *name);
IPAddress _getIP(const String &from);
String rootProcessor(const String &var);
String apProcessor(const String &var);
String infoProcessor(const String & var);
WiFiConfigUsrParameter *_params; // ukazatel na posledni zadany uzivatelsky parametr
int _timeout; // timeout pri cekani na konfiguraci
uint32_t _time; // hodnota, po ktere bude ESP restartovano (pokud je _timeout != 0)
uint8_t _status; // stav pripojeni - je pouzity pro signalizaci duvodu, proc se nepripoji k AP
};
#endif

View File

@ -1,266 +0,0 @@
// HTML data
#ifndef WIFICONFIG_WEBTITLE
# define WIFICONFIG_WEBTITLE "xPablo.cz Setup"
#endif
#ifndef WIFICONFIG_TITLE
# define WIFICONFIG_TITLE "ESP WiFiConfig"
#endif
static const char TEXTHTML[] PROGMEM = "text/html";
static const char TEXTPLAIN[] PROGMEM = "text/plain";
static const char TEXTJSON[] PROGMEM = "text/json";
static const char PAGE_INDEX1[] PROGMEM = R"=====(<!DOCTYPE html>
<html lang="en"><head><meta charset= "utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>)=====" WIFICONFIG_WEBTITLE R"=====(</title>
<style>
.c{text-align: center;}
div,input{padding:5px;font-size:1em;}
input{width:95%;}
body{text-align: center;font-family:verdana;}
button{border:0;border-radius:0.3rem;background-color:#1fa3ec;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;}
.q{float: right;width: 64px;text-align: right;}
.l{background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAALVBMVEX///8EBwfBwsLw8PAzNjaCg4NTVVUjJiZDRUUUFxdiZGSho6OSk5Pg4eFydHTCjaf3AAAAZElEQVQ4je2NSw7AIAhEBamKn97/uMXEGBvozkWb9C2Zx4xzWykBhFAeYp9gkLyZE0zIMno9n4g19hmdY39scwqVkOXaxph0ZCXQcqxSpgQpONa59wkRDOL93eAXvimwlbPbwwVAegLS1HGfZAAAAABJRU5ErkJggg==") no-repeat left center;background-size: 1em;}
#rssiBar{width: 100px;height: 15px;background: #fff;}
#rssiBar > div{width: 52px;height: 15px;background: #c20000;}
</style>
<script>
function c(l){document.getElementById('_s').value=l.innerText||l.textContent;document.getElementById('_p').focus();}
function hAP(){if (document.getElementById('_a').checked){document.getElementById('apconfig').style.display = 'block';}else{document.getElementById('apconfig').style.display = 'none';}}
function hSC(){if (document.getElementById('_st').checked){document.getElementById('staticip').style.display = 'block';}else{document.getElementById('staticip').style.display = 'none';}}
</script>
</head><body><h1>)=====" WIFICONFIG_TITLE R"=====(</h1><div style='text-align:left;display:inline-block;min-width:260px;'>
<div id="ssids">
</div>
<form method='post' action='s'>
<label>SSID<br><input id='_s' name='_s' maxlength=32 required placeholder='SSID' value="$SSID$"></label><br>
<label>Heslo<br><input id='_p' name='_p' onfocus="this.select();" maxlength=64 value="$PASS$" type='password' placeholder='heslo'></label><br>
<div>
<label><input id='_a' name='_a' type='checkbox' style="width: 10%; float: left; margin-top: 5px;" onclick='hAP();' $APMODE$>Režim AP</label>
<div id="apconfig">
<label>Kanál<br><input type="number" name="_ch" min="1" max="13" title='cislo kanalu v intervalu 1-13' value='$APCHAN$'></label><br>
</div>
</div>
<div>
<label><input id='_st' name='_st' type='checkbox' style="width: 10%; float: left; margin-top: 5px;" onclick='hSC();' $STATIC$>Statická IP konfigurace</label>
<div id="staticip">
<label>IP adresa<br><input type="text" name="_i" value='$IP$'></label><br>
<label>Síťová maska<br><input type="text" name="_m" value='$MASK$'></label><br>
<label>Síťová brána<br><input type="text" name="_g" value='$GATE$'></label><br>
<label>Server DNS<br><input type="text" name="_d" value='$DNS$'></label><br>
</div>
</div>
$USER$
<br>
<button type='submit'>Uložit a restartovat</button></form>
<script>
window.onload = function() {
hAP();
hSC();
var req = new XMLHttpRequest();
req.open("GET", "/scan", true);
req.onreadystatechange = function() {
if (req.readyState != 4 || req.status != 200)
return;
ssids = document.getElementById('ssids');
data = JSON.parse(req.responseText);
status = data.status;
html = "";
if (status > 0) {
for (i= 0 ; i < status; ++i) {
lock = "";
if (data.ssids[i].secure != 0)
lock = "l";
value = data.ssids[i].rssi;
if (value <= -100)
value = 0;
else if (value >= -50)
value = 100;
else
value = 2 * (value + 100);
line = "<div><a href='#p' onclick='c(this)'>" + data.ssids[i].ssid + "</a>&nbsp;<span class='q " + lock + "'><meter value='" + value + "' min='0' low='30' optimum='70' high='60' max='100' style='width: 70%;'></meter></span></div>";
html += line;
}
ssids.innerHTML = html;
}
};
req.send();
};
</script>
</div>)====="
#if defined APP_NAME && defined APP_VERSION
R"=====(<div style='text-align:right;font-size:11px;'><hr/>)====="
APP_NAME
" v"
APP_VERSION
R"=====(</div>
)====="
#else
R"=====(<div style='text-align:right;font-size:11px;'><hr/><a href='http://xpablo.cz' target='_blank' style='color:#aaa;'>WiFiConfig by xPablo</a></div>)====="
#endif
R"=====(</body></html>
)=====";
// Uzivatelsky pridane polozky
static const char PAGE_PARAM_HDR[] PROGMEM = R"=====(
<hr>
<h2>Uživatelské položky</h2>
)=====";
static const char PAGE_PARAM[] PROGMEM = R"=====(
<label>%s<br><input name='%s' maxlength='%d' value='%s'></label><br>
)=====";
/*
<div style='text-align:right;font-size:11px;'><hr/><a href='http://xpablo.cz' target='_blank' style='color:#aaa;'>WiFiConfig by xPablo</a></div>
*/
// Nenalezeno zadne SSID
static const char PAGE_NO_SSID[] PROGMEM = R"=====(
<div>Nenalezená žádná síť. Občerstvi stránku pro nové hledání.</div>
)=====";
// Konfigurace ulozena - restartuji...
static const char PAGE_SAVED[] PROGMEM = R"=====(
<!DOCTYPE html><html lang="cs"><head><meta http-equiv="refresh" content="5;url=/"/>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1"/>
<title>xPablo Setup - Konfigurace uložena</title>
<style>div,input {margin-bottom: 5px;}body{width:200px;display:block;margin-left:auto;margin-right:auto;}</style>
</head><body>
Uloženo do Flash...<br/>
Restart za několik sekund.
</body></html>
)=====";
static const char PAGE_CAPTIVEPORTALCATCH[] PROGMEM = R"=====(<!DOCTYPE html>
<html lang="cs"><head><meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/><title>xPablo.cz Setup</title>
<style>.c{text-align: center;} div,input{padding:5px;font-size:1em;} input{width:95%;} body{text-align: center;font-family:verdana;} button{border:0;border-radius:0.3rem;background-color:#1fa3ec;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;} .q{float: right;width: 64px;text-align: right;}
.vl-info {border-left: thick solid #1fa3ec;background: #cee6ff; text-align:left; display:inline-block; min-width:260px; margin-top:15px}
.red { background-color: #ff0000;}
.magenta { background-color: #ff00ff;}
.yellow { background-color: #FFD700;}
</style>
</head><body><div style='text-align:left;display:inline-block;min-width:260px;'>
<form action="/config" method="get">
<button>Konfigurace WiFi</button>
</form><br/>
<form action="/i" method="get">
<button>Informace o modulu</button>
</form><br/>
$RESTORE$
<form action="/r" method="post">
<button class="red">Reset</button></form><br>)====="
#if defined USE_WIFICONFIG_OTAUPDATE
R"=====(
</form><br/><form action="/u" method="get">
<button class="magenta">Aktualizace firmware</button></form><br>)====="
#endif
R"=====(
<div class=\"vl-info\">Pokus o připojení: $STATUS$</div>
)====="
#if defined APP_NAME && defined APP_VERSION
R"=====(<div style='text-align:right;font-size:11px;'><hr/>)====="
APP_NAME
" v"
APP_VERSION
R"=====(</div>
)====="
#else
R"=====(<div style='text-align:right;font-size:11px;'><hr/><a href='http://xpablo.cz' target='_blank' style='color:#aaa;'>WiFiConfig by xPablo</a></div>)====="
#endif
R"=====(</body></html>
)=====";
static const char PAGE_RESTART[] PROGMEM = R"=====(<!DOCTYPE html>
<html lang="cs"><head><meta http-equiv="refresh" content="5;url=/"/>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1"/>
<title>xPablo Setup - Restart</title>
<style>div,input {margin-bottom: 5px;}body{width:200px;display:block;margin-left:auto;margin-right:auto;}</style>
</head><body>
Restartuji...
</body></html>
)=====";
static const char PAGE_UPDATE[] PROGMEM = R"=====(
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'/>
</head>
<body>
<form method="POST" action="#" enctype="multipart/form-data" id="upload_form">
<input type="file" name="update" accept='.bin' id="file">
<input type="submit" value="Update"> </form>
<div id="prg_wrap" style="border: 0px solid; width: 100%;">
<div id="prg" style="text-shadow: 2px 2px 3px black; padding: 5px 0; display: none; border: 1px solid #008aff; background: #002180; text-align: center; color: white;"></div>
</div>
<script>
var domReady = function(callback) {
document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback);
};
domReady(function() {
var myform = document.getElementById('upload_form');
var filez = document.getElementById('file');
myform.onsubmit = function(event) {
event.preventDefault();
var formData = new FormData();
var file = filez.files[0];
if(!file) {
return false;
}
formData.append("files", file, file.name);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if(evt.lengthComputable) {
var per = Math.round((evt.loaded / evt.total) * 100);
var prg = document.getElementById('prg');
prg.innerHTML = per + "%"
prg.style.width = per + "%"
prg.style.display = "block"
}
}, false);
xhr.open('POST', location.href, true);
// Set up a handler for when the request finishes.
xhr.onload = function() {
if(xhr.status === 200) {
//alert('Success');
} else {
//alert('An error occurred!');
}
};
xhr.send(formData);
}
});
</script>
</body>
</html>
)=====";
static const char PAGE_INFO[] PROGMEM = R"=====(
<!DOCTYPE html><html lang="en"><head><meta charset= "utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>)=====" WIFICONFIG_WEBTITLE R"=====(</title>
<style>
.c{text-align: center;}
div,input{padding:5px;font-size:1em;}
input{width:95%;}
body{text-align: center;font-family:verdana;}
button{border:0;border-radius:0.3rem;background-color:#1fa3ec;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;}
.q{float: right;width: 64px;text-align: right;}
</style>
</head><body><h1>)=====" WIFICONFIG_TITLE R"=====(</h1><div style='text-align:left;display:inline-block;min-width:260px;'>
<form><table><tr><th>System Info<th>
<tr><td>Core Version:<td>$SDK$
<tr><td>Flash Size:<td>$FS$ kB
<tr><td>Sketch Size/Free:<td>$SS$ kB / $FSS$ kB
<tr><td>STA MAC:<td>$STAMAC$
<tr><td>AP MAC:<td>$APMAC$
<tr><td>ESP Chip ID:<td>$ESPID$
<tr><td>Flash Chip ID:<td>$FID$
</table></form>
)=====";
static const char PAGE_RESTORE[] PROGMEM = R"=====(
<form action="/o" method="post">
<button class="yellow">Předminulá konfigurace</button>
</form><br/>
)=====";