/************************************************************** WiFiManager is a library for the ESP8266/Arduino platform (https://github.com/esp8266/Arduino) to enable easy configuration and reconfiguration of WiFi credentials and store them in EEPROM. inspired by: http://www.esp8266.com/viewtopic.php?f=29&t=2520 https://github.com/chriscook8/esp-arduino-apboot https://github.com/esp8266/Arduino/tree/esp8266/hardware/esp8266com/esp8266/libraries/DNSServer/examples/CaptivePortalAdvanced Built by AlexT https://github.com/tzapu Licensed under MIT license **************************************************************/ #include "WiFiManager.h" WiFiManagerParameter::WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length) { _id = id; _placeholder = placeholder; _length = length; _value = new char[length]; for (int i = 0; i < length; i++) { _value[i] = 0; } if (defaultValue != NULL) { strncpy(_value, defaultValue, length); } } const char* WiFiManagerParameter::getValue() { return _value; } const char* WiFiManagerParameter::getID() { return _id; } const char* WiFiManagerParameter::getPlaceholder() { return _placeholder; } int WiFiManagerParameter::getValueLength() { return _length; } WiFiManager::WiFiManager() { } void WiFiManager::addParameter(WiFiManagerParameter *p) { _params[_paramsCount] = p; _paramsCount++; DEBUG_WM("Adding parameter"); DEBUG_WM(p->getID()); } void WiFiManager::setupConfigPortal(char const *apName, char const *apPassword) { dnsServer.reset(new DNSServer()); server.reset(new ESP8266WebServer(80)); DEBUG_WM(F("")); _apName = apName; _apPassword = apPassword; start = millis(); DEBUG_WM(F("Configuring access point... ")); DEBUG_WM(_apName); if (_apPassword != NULL) { if (strlen(_apPassword) < 8 || strlen(_apPassword) > 63) { // fail passphrase to short or long! DEBUG_WM(F("Invalid AccessPoint password. Ignoring")); _apPassword = NULL; } DEBUG_WM(_apPassword); } //optional soft ip config if (_ip) { DEBUG_WM(F("Custom IP/GW/Subnet")); WiFi.softAPConfig(_ip, _gw, _sn); } if (_apPassword != NULL) { WiFi.softAP(_apName, _apPassword);//password option } else { WiFi.softAP(_apName); } delay(500); // Without delay I've seen the IP address blank DEBUG_WM(F("AP IP address: ")); DEBUG_WM(WiFi.softAPIP()); /* Setup the DNS server redirecting all the domains to the apIP */ dnsServer->setErrorReplyCode(DNSReplyCode::NoError); dnsServer->start(DNS_PORT, "*", WiFi.softAPIP()); /* Setup web pages: root, wifi config pages, SO captive portal detectors and not found. */ server->on("/", std::bind(&WiFiManager::handleRoot, this)); server->on("/wifi", std::bind(&WiFiManager::handleWifi, this, true)); server->on("/0wifi", std::bind(&WiFiManager::handleWifi, this, false)); server->on("/wifisave", std::bind(&WiFiManager::handleWifiSave, this)); server->on("/generate_204", std::bind(&WiFiManager::handle204, this)); //Android/Chrome OS captive portal check. server->on("/fwlink", std::bind(&WiFiManager::handleRoot, this)); //Microsoft captive portal. Maybe not needed. Might be handled by notFound handler. server->onNotFound (std::bind(&WiFiManager::handleNotFound, this)); server->begin(); // Web server start DEBUG_WM(F("HTTP server started")); } boolean WiFiManager::autoConnect() { String ssid = "ESP" + String(ESP.getChipId()); return autoConnect(ssid.c_str(), NULL); } boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) { DEBUG_WM(F("")); DEBUG_WM(F("AutoConnect")); // read eeprom for ssid and pass String ssid = getSSID(); String pass = getPassword(); // attempt to connect; should it fail, fall back to AP WiFi.mode(WIFI_STA); if (connectWifi(ssid, pass) == WL_CONNECTED) { DEBUG_WM(F("IP Address:")); DEBUG_WM(WiFi.localIP()); //connected return true; } return startConfigPortal(apName, apPassword); } boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) { //setup AP WiFi.mode(WIFI_AP); //notify we entered AP mode if ( _apcallback != NULL) { _apcallback(); } connect = false; setupConfigPortal(apName, apPassword); while (timeout == 0 || millis() < start + timeout) { //DNS dnsServer->processNextRequest(); //HTTP server->handleClient(); if (connect) { delay(2000); DEBUG_WM(F("Connecting to new AP")); connect = false; // using user-provided _ssid, _pass in place of system-stored ssid amd pass if (connectWifi(_ssid, _pass) != WL_CONNECTED) { DEBUG_WM(F("Failed to connect.")); } else { //connected WiFi.mode(WIFI_STA); //notify that configuration has changed and any optional parameters should be saved if ( _savecallback != NULL) { //todo: check if any custom parameters actually exist, and check if they really changed maybe _savecallback(); } break; } } yield(); } server.reset(); dnsServer.reset(); return WiFi.status() == WL_CONNECTED; } int WiFiManager::connectWifi(String ssid, String pass) { DEBUG_WM(F("Connecting as wifi client...")); //WiFi.disconnect(); WiFi.begin(ssid.c_str(), pass.c_str()); int connRes = WiFi.waitForConnectResult(); DEBUG_WM ("Connection result: "); DEBUG_WM ( connRes ); return connRes; } String WiFiManager::getSSID() { if (_ssid == "") { DEBUG_WM(F("Reading SSID")); _ssid = WiFi.SSID(); DEBUG_WM(F("SSID: ")); DEBUG_WM(_ssid); } return _ssid; } String WiFiManager::getPassword() { if (_pass == "") { DEBUG_WM(F("Reading Password")); _pass = WiFi.psk(); DEBUG_WM("Password: " + _pass); //DEBUG_WM(_pass); } return _pass; } String WiFiManager::urldecode(const char *src) { String decoded = ""; char a, b; while (*src) { if ((*src == '%') && ((a = src[1]) && (b = src[2])) && (isxdigit(a) && isxdigit(b))) { if (a >= 'a') a -= 'a' - 'A'; if (a >= 'A') a -= ('A' - 10); else a -= '0'; if (b >= 'a') b -= 'a' - 'A'; if (b >= 'A') b -= ('A' - 10); else b -= '0'; decoded += char(16 * a + b); src += 3; } else if (*src == '+') { decoded += ' '; *src++; } else { decoded += *src; *src++; } } decoded += '\0'; return decoded; } void WiFiManager::resetSettings() { DEBUG_WM(F("settings invalidated")); DEBUG_WM(F("THIS MAY CAUSE AP NOT TO STRT UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA.")); WiFi.disconnect(true); //delay(200); } void WiFiManager::setTimeout(unsigned long seconds) { timeout = seconds * 1000; } void WiFiManager::setDebugOutput(boolean debug) { _debug = debug; } void WiFiManager::setAPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { _ip = ip; _gw = gw; _sn = sn; } /** Handle root or redirect to captive portal */ void WiFiManager::handleRoot() { DEBUG_WM(F("Handle root")); if (captivePortal()) { // If caprive portal redirect instead of displaying the page. return; } server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); server->sendHeader("Pragma", "no-cache"); server->sendHeader("Expires", "-1"); server->send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. String head = HTTP_HEAD; head.replace("{v}", "Options"); server->sendContent(head); server->sendContent_P(HTTP_SCRIPT); server->sendContent_P(HTTP_STYLE); server->sendContent_P(HTTP_HEAD_END); //server->sendContent(F("