ESPAsyncWiFiManager.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. /**************************************************************
  2. AsyncWiFiManager is a library for the ESP8266/Arduino platform
  3. (https://github.com/esp8266/Arduino) to enable easy
  4. configuration and reconfiguration of WiFi credentials using a Captive Portal
  5. inspired by:
  6. http://www.esp8266.com/viewtopic.php?f=29&t=2520
  7. https://github.com/chriscook8/esp-arduino-apboot
  8. https://github.com/esp8266/Arduino/tree/esp8266/hardware/esp8266com/esp8266/libraries/DNSServer/examples/CaptivePortalAdvanced
  9. Built by AlexT https://github.com/tzapu
  10. Licensed under MIT license
  11. **************************************************************/
  12. #include "ESPAsyncWiFiManager.h"
  13. AsyncWiFiManagerParameter::AsyncWiFiManagerParameter(const char *custom) {
  14. _id = NULL;
  15. _placeholder = NULL;
  16. _length = 0;
  17. _value = NULL;
  18. _customHTML = custom;
  19. }
  20. AsyncWiFiManagerParameter::AsyncWiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length) {
  21. init(id, placeholder, defaultValue, length, "");
  22. }
  23. AsyncWiFiManagerParameter::AsyncWiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom) {
  24. init(id, placeholder, defaultValue, length, custom);
  25. }
  26. void AsyncWiFiManagerParameter::init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom) {
  27. _id = id;
  28. _placeholder = placeholder;
  29. _length = length;
  30. _value = new char[length + 1];
  31. for (int i = 0; i < length; i++) {
  32. _value[i] = 0;
  33. }
  34. if (defaultValue != NULL) {
  35. strncpy(_value, defaultValue, length);
  36. }
  37. _customHTML = custom;
  38. }
  39. const char* AsyncWiFiManagerParameter::getValue() {
  40. return _value;
  41. }
  42. const char* AsyncWiFiManagerParameter::getID() {
  43. return _id;
  44. }
  45. const char* AsyncWiFiManagerParameter::getPlaceholder() {
  46. return _placeholder;
  47. }
  48. int AsyncWiFiManagerParameter::getValueLength() {
  49. return _length;
  50. }
  51. const char* AsyncWiFiManagerParameter::getCustomHTML() {
  52. return _customHTML;
  53. }
  54. AsyncWiFiManager::AsyncWiFiManager(AsyncWebServer *server, DNSServer *dns) :server(server), dnsServer(dns) {
  55. wifiSSIDs = NULL;
  56. wifiSSIDscan=true;
  57. }
  58. void AsyncWiFiManager::addParameter(AsyncWiFiManagerParameter *p) {
  59. _params[_paramsCount] = p;
  60. _paramsCount++;
  61. DEBUG_WM("Adding parameter");
  62. DEBUG_WM(p->getID());
  63. }
  64. void AsyncWiFiManager::setupConfigPortal() {
  65. // dnsServer.reset(new DNSServer());
  66. // server.reset(new ESP8266WebServer(80));
  67. DEBUG_WM(F(""));
  68. _configPortalStart = millis();
  69. DEBUG_WM(F("Configuring access point... "));
  70. DEBUG_WM(_apName);
  71. if (_apPassword != NULL) {
  72. if (strlen(_apPassword) < 8 || strlen(_apPassword) > 63) {
  73. // fail passphrase to short or long!
  74. DEBUG_WM(F("Invalid AccessPoint password. Ignoring"));
  75. _apPassword = NULL;
  76. }
  77. DEBUG_WM(_apPassword);
  78. }
  79. //optional soft ip config
  80. if (_ap_static_ip) {
  81. DEBUG_WM(F("Custom AP IP/GW/Subnet"));
  82. WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn);
  83. }
  84. if (_apPassword != NULL) {
  85. WiFi.softAP(_apName, _apPassword);//password option
  86. } else {
  87. WiFi.softAP(_apName);
  88. }
  89. delay(500); // Without delay I've seen the IP address blank
  90. DEBUG_WM(F("AP IP address: "));
  91. DEBUG_WM(WiFi.softAPIP());
  92. /* Setup the DNS server redirecting all the domains to the apIP */
  93. dnsServer->setErrorReplyCode(DNSReplyCode::NoError);
  94. dnsServer->start(DNS_PORT, "*", WiFi.softAPIP());
  95. /* Setup web pages: root, wifi config pages, SO captive portal detectors and not found. */
  96. server->on("/", std::bind(&AsyncWiFiManager::handleRoot, this,std::placeholders::_1)).setFilter(ON_AP_FILTER);
  97. server->on("/wifi", std::bind(&AsyncWiFiManager::handleWifi, this, std::placeholders::_1,true)).setFilter(ON_AP_FILTER);
  98. server->on("/0wifi", std::bind(&AsyncWiFiManager::handleWifi, this,std::placeholders::_1, false)).setFilter(ON_AP_FILTER);
  99. server->on("/wifisave", std::bind(&AsyncWiFiManager::handleWifiSave,this,std::placeholders::_1)).setFilter(ON_AP_FILTER);
  100. server->on("/i", std::bind(&AsyncWiFiManager::handleInfo,this, std::placeholders::_1)).setFilter(ON_AP_FILTER);
  101. server->on("/r", std::bind(&AsyncWiFiManager::handleReset, this,std::placeholders::_1)).setFilter(ON_AP_FILTER);
  102. //server->on("/generate_204", std::bind(&AsyncWiFiManager::handle204, this)); //Android/Chrome OS captive portal check.
  103. server->on("/fwlink", std::bind(&AsyncWiFiManager::handleRoot, this,std::placeholders::_1)).setFilter(ON_AP_FILTER); //Microsoft captive portal. Maybe not needed. Might be handled by notFound handler.
  104. server->onNotFound (std::bind(&AsyncWiFiManager::handleNotFound,this,std::placeholders::_1));
  105. server->begin(); // Web server start
  106. DEBUG_WM(F("HTTP server started"));
  107. }
  108. boolean AsyncWiFiManager::autoConnect() {
  109. String ssid = "ESP" + String(ESP.getChipId());
  110. return autoConnect(ssid.c_str(), NULL);
  111. }
  112. boolean AsyncWiFiManager::autoConnect(char const *apName, char const *apPassword) {
  113. DEBUG_WM(F(""));
  114. DEBUG_WM(F("AutoConnect"));
  115. // read eeprom for ssid and pass
  116. //String ssid = getSSID();
  117. //String pass = getPassword();
  118. // attempt to connect; should it fail, fall back to AP
  119. WiFi.mode(WIFI_STA);
  120. if (connectWifi("", "") == WL_CONNECTED) {
  121. DEBUG_WM(F("IP Address:"));
  122. DEBUG_WM(WiFi.localIP());
  123. //connected
  124. return true;
  125. }
  126. return startConfigPortal(apName, apPassword);
  127. }
  128. void AsyncWiFiManager::scan()
  129. {
  130. if (wifiSSIDscan)
  131. {
  132. delay(100);
  133. }
  134. if (wifiSSIDscan)
  135. {
  136. int n = WiFi.scanNetworks();
  137. DEBUG_WM(F("Scan done"));
  138. if (n == 0) {
  139. DEBUG_WM(F("No networks found"));
  140. // page += F("No networks found. Refresh to scan again.");
  141. } else {
  142. if (wifiSSIDscan)
  143. {
  144. /* WE SHOULD MOVE THIS IN PLACE ATOMICALLY */
  145. if (wifiSSIDs) delete [] wifiSSIDs;
  146. wifiSSIDs = new WiFiResult[n];
  147. wifiSSIDCount = n;
  148. for (int i=0;i<n;i++)
  149. {
  150. wifiSSIDs[i].duplicate=false;
  151. bool res=WiFi.getNetworkInfo(i, wifiSSIDs[i].SSID, wifiSSIDs[i].encryptionType, wifiSSIDs[i].RSSI, wifiSSIDs[i].BSSID, wifiSSIDs[i].channel, wifiSSIDs[i].isHidden);
  152. }
  153. // RSSI SORT
  154. // old sort
  155. for (int i = 0; i < n; i++) {
  156. for (int j = i + 1; j < n; j++) {
  157. if (wifiSSIDs[j].RSSI > wifiSSIDs[i].RSSI) {
  158. std::swap(wifiSSIDs[i], wifiSSIDs[j]);
  159. }
  160. }
  161. }
  162. // remove duplicates ( must be RSSI sorted )
  163. if (_removeDuplicateAPs) {
  164. String cssid;
  165. for (int i = 0; i < n; i++) {
  166. if (wifiSSIDs[i].duplicate == true) continue;
  167. cssid = wifiSSIDs[i].SSID;
  168. for (int j = i + 1; j < n; j++) {
  169. if (cssid == wifiSSIDs[j].SSID) {
  170. DEBUG_WM("DUP AP: " +wifiSSIDs[j].SSID);
  171. wifiSSIDs[j].duplicate=true; // set dup aps to NULL
  172. }
  173. }
  174. }
  175. }
  176. }
  177. }
  178. }
  179. }
  180. boolean AsyncWiFiManager::startConfigPortal(char const *apName, char const *apPassword) {
  181. //setup AP
  182. WiFi.mode(WIFI_AP_STA);
  183. DEBUG_WM("SET AP STA");
  184. _apName = apName;
  185. _apPassword = apPassword;
  186. //notify we entered AP mode
  187. if ( _apcallback != NULL) {
  188. _apcallback(this);
  189. }
  190. connect = false;
  191. setupConfigPortal();
  192. int scannow= -1 ;
  193. while (_configPortalTimeout == 0 || millis() < _configPortalStart + _configPortalTimeout) {
  194. //DNS
  195. dnsServer->processNextRequest();
  196. //
  197. // we should do a scan every so often here
  198. //
  199. if ( millis() > scannow + 10000)
  200. {
  201. DEBUG_WM(F("About to scan()"));
  202. scan();
  203. scannow= millis() ;
  204. }
  205. if (connect) {
  206. connect = false;
  207. delay(2000);
  208. DEBUG_WM(F("Connecting to new AP"));
  209. // using user-provided _ssid, _pass in place of system-stored ssid and pass
  210. if (connectWifi(_ssid, _pass) != WL_CONNECTED) {
  211. DEBUG_WM(F("Failed to connect."));
  212. } else {
  213. //connected
  214. WiFi.mode(WIFI_STA);
  215. //notify that configuration has changed and any optional parameters should be saved
  216. if ( _savecallback != NULL) {
  217. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  218. _savecallback();
  219. }
  220. break;
  221. }
  222. if (_shouldBreakAfterConfig) {
  223. //flag set to exit after config after trying to connect
  224. //notify that configuration has changed and any optional parameters should be saved
  225. if ( _savecallback != NULL) {
  226. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  227. _savecallback();
  228. }
  229. break;
  230. }
  231. }
  232. yield();
  233. }
  234. // server.reset();
  235. // dnsServer.reset();
  236. return WiFi.status() == WL_CONNECTED;
  237. }
  238. int AsyncWiFiManager::connectWifi(String ssid, String pass) {
  239. DEBUG_WM(F("Connecting as wifi client..."));
  240. // check if we've got static_ip settings, if we do, use those.
  241. if (_sta_static_ip) {
  242. DEBUG_WM(F("Custom STA IP/GW/Subnet"));
  243. WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn);
  244. DEBUG_WM(WiFi.localIP());
  245. }
  246. //fix for auto connect racing issue
  247. if (WiFi.status() == WL_CONNECTED) {
  248. DEBUG_WM("Already connected. Bailing out.");
  249. return WL_CONNECTED;
  250. }
  251. //check if we have ssid and pass and force those, if not, try with last saved values
  252. if (ssid != "") {
  253. WiFi.begin(ssid.c_str(), pass.c_str());
  254. } else {
  255. if (WiFi.SSID()) {
  256. DEBUG_WM("Using last saved values, should be faster");
  257. //trying to fix connection in progress hanging
  258. ETS_UART_INTR_DISABLE();
  259. wifi_station_disconnect();
  260. ETS_UART_INTR_ENABLE();
  261. WiFi.begin();
  262. } else {
  263. DEBUG_WM("No saved credentials");
  264. }
  265. }
  266. int connRes = waitForConnectResult();
  267. DEBUG_WM ("Connection result: ");
  268. DEBUG_WM ( connRes );
  269. //not connected, WPS enabled, no pass - first attempt
  270. if (_tryWPS && connRes != WL_CONNECTED && pass == "") {
  271. startWPS();
  272. //should be connected at the end of WPS
  273. connRes = waitForConnectResult();
  274. }
  275. return connRes;
  276. }
  277. uint8_t AsyncWiFiManager::waitForConnectResult() {
  278. if (_connectTimeout == 0) {
  279. return WiFi.waitForConnectResult();
  280. } else {
  281. DEBUG_WM (F("Waiting for connection result with time out"));
  282. unsigned long start = millis();
  283. boolean keepConnecting = true;
  284. uint8_t status;
  285. while (keepConnecting) {
  286. status = WiFi.status();
  287. if (millis() > start + _connectTimeout) {
  288. keepConnecting = false;
  289. DEBUG_WM (F("Connection timed out"));
  290. }
  291. if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) {
  292. keepConnecting = false;
  293. }
  294. delay(100);
  295. }
  296. return status;
  297. }
  298. }
  299. void AsyncWiFiManager::startWPS() {
  300. DEBUG_WM("START WPS");
  301. WiFi.beginWPSConfig();
  302. DEBUG_WM("END WPS");
  303. }
  304. /*
  305. String AsyncWiFiManager::getSSID() {
  306. if (_ssid == "") {
  307. DEBUG_WM(F("Reading SSID"));
  308. _ssid = WiFi.SSID();
  309. DEBUG_WM(F("SSID: "));
  310. DEBUG_WM(_ssid);
  311. }
  312. return _ssid;
  313. }
  314. String AsyncWiFiManager::getPassword() {
  315. if (_pass == "") {
  316. DEBUG_WM(F("Reading Password"));
  317. _pass = WiFi.psk();
  318. DEBUG_WM("Password: " + _pass);
  319. //DEBUG_WM(_pass);
  320. }
  321. return _pass;
  322. }
  323. */
  324. String AsyncWiFiManager::getConfigPortalSSID() {
  325. return _apName;
  326. }
  327. void AsyncWiFiManager::resetSettings() {
  328. DEBUG_WM(F("settings invalidated"));
  329. DEBUG_WM(F("THIS MAY CAUSE AP NOT TO START UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA."));
  330. WiFi.disconnect(true);
  331. //delay(200);
  332. }
  333. void AsyncWiFiManager::setTimeout(unsigned long seconds) {
  334. setConfigPortalTimeout(seconds);
  335. }
  336. void AsyncWiFiManager::setConfigPortalTimeout(unsigned long seconds) {
  337. _configPortalTimeout = seconds * 1000;
  338. }
  339. void AsyncWiFiManager::setConnectTimeout(unsigned long seconds) {
  340. _connectTimeout = seconds * 1000;
  341. }
  342. void AsyncWiFiManager::setDebugOutput(boolean debug) {
  343. _debug = debug;
  344. }
  345. void AsyncWiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) {
  346. _ap_static_ip = ip;
  347. _ap_static_gw = gw;
  348. _ap_static_sn = sn;
  349. }
  350. void AsyncWiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) {
  351. _sta_static_ip = ip;
  352. _sta_static_gw = gw;
  353. _sta_static_sn = sn;
  354. }
  355. void AsyncWiFiManager::setMinimumSignalQuality(int quality) {
  356. _minimumQuality = quality;
  357. }
  358. void AsyncWiFiManager::setBreakAfterConfig(boolean shouldBreak) {
  359. _shouldBreakAfterConfig = shouldBreak;
  360. }
  361. /** Handle root or redirect to captive portal */
  362. void AsyncWiFiManager::handleRoot(AsyncWebServerRequest *request) {
  363. DEBUG_WM(F("Handle root"));
  364. if (captivePortal(request)) { // If caprive portal redirect instead of displaying the page.
  365. return;
  366. }
  367. String page = FPSTR(WFM_HTTP_HEAD);
  368. page.replace("{v}", "Options");
  369. page += FPSTR(HTTP_SCRIPT);
  370. page += FPSTR(HTTP_STYLE);
  371. page += _customHeadElement;
  372. page += FPSTR(HTTP_HEAD_END);
  373. page += "<h1>";
  374. page += _apName;
  375. page += "</h1>";
  376. page += F("<h3>AsyncWiFiManager</h3>");
  377. page += FPSTR(HTTP_PORTAL_OPTIONS);
  378. page += FPSTR(HTTP_END);
  379. request->send(200, "text/html", page);
  380. }
  381. /** Wifi config page handler */
  382. void AsyncWiFiManager::handleWifi(AsyncWebServerRequest *request,boolean scan) {
  383. String page = FPSTR(WFM_HTTP_HEAD);
  384. page.replace("{v}", "Config ESP");
  385. page += FPSTR(HTTP_SCRIPT);
  386. page += FPSTR(HTTP_STYLE);
  387. page += _customHeadElement;
  388. page += FPSTR(HTTP_HEAD_END);
  389. if (scan) {
  390. wifiSSIDscan=false;
  391. int n = wifiSSIDCount;
  392. DEBUG_WM(F("Scan done"));
  393. if (n == 0) {
  394. DEBUG_WM(F("No networks found"));
  395. page += F("No networks found. Refresh to scan again.");
  396. } else {
  397. //display networks in page
  398. for (int i = 0; i < n; i++) {
  399. if (wifiSSIDs[i].duplicate == true) continue; // skip dups
  400. DEBUG_WM(wifiSSIDs[i].SSID);
  401. DEBUG_WM(wifiSSIDs[i].RSSI);
  402. int quality = getRSSIasQuality(wifiSSIDs[i].RSSI);
  403. if (_minimumQuality == -1 || _minimumQuality < quality) {
  404. String item = FPSTR(HTTP_ITEM);
  405. String rssiQ;
  406. rssiQ += quality;
  407. item.replace("{v}", wifiSSIDs[i].SSID);
  408. item.replace("{r}", rssiQ);
  409. if (wifiSSIDs[i].encryptionType != ENC_TYPE_NONE) {
  410. item.replace("{i}", "l");
  411. } else {
  412. item.replace("{i}", "");
  413. }
  414. //DEBUG_WM(item);
  415. page += item;
  416. delay(0);
  417. } else {
  418. DEBUG_WM(F("Skipping due to quality"));
  419. }
  420. }
  421. page += "<br/>";
  422. }
  423. }
  424. wifiSSIDscan=true;
  425. page += FPSTR(HTTP_FORM_START);
  426. char parLength[2];
  427. // add the extra parameters to the form
  428. for (int i = 0; i < _paramsCount; i++) {
  429. if (_params[i] == NULL) {
  430. break;
  431. }
  432. String pitem = FPSTR(HTTP_FORM_PARAM);
  433. if (_params[i]->getID() != NULL) {
  434. pitem.replace("{i}", _params[i]->getID());
  435. pitem.replace("{n}", _params[i]->getID());
  436. pitem.replace("{p}", _params[i]->getPlaceholder());
  437. snprintf(parLength, 2, "%d", _params[i]->getValueLength());
  438. pitem.replace("{l}", parLength);
  439. pitem.replace("{v}", _params[i]->getValue());
  440. pitem.replace("{c}", _params[i]->getCustomHTML());
  441. } else {
  442. pitem = _params[i]->getCustomHTML();
  443. }
  444. page += pitem;
  445. }
  446. if (_params[0] != NULL) {
  447. page += "<br/>";
  448. }
  449. if (_sta_static_ip) {
  450. String item = FPSTR(HTTP_FORM_PARAM);
  451. item.replace("{i}", "ip");
  452. item.replace("{n}", "ip");
  453. item.replace("{p}", "Static IP");
  454. item.replace("{l}", "15");
  455. item.replace("{v}", _sta_static_ip.toString());
  456. page += item;
  457. item = FPSTR(HTTP_FORM_PARAM);
  458. item.replace("{i}", "gw");
  459. item.replace("{n}", "gw");
  460. item.replace("{p}", "Static Gateway");
  461. item.replace("{l}", "15");
  462. item.replace("{v}", _sta_static_gw.toString());
  463. page += item;
  464. item = FPSTR(HTTP_FORM_PARAM);
  465. item.replace("{i}", "sn");
  466. item.replace("{n}", "sn");
  467. item.replace("{p}", "Subnet");
  468. item.replace("{l}", "15");
  469. item.replace("{v}", _sta_static_sn.toString());
  470. page += item;
  471. page += "<br/>";
  472. }
  473. page += FPSTR(HTTP_FORM_END);
  474. page += FPSTR(HTTP_SCAN_LINK);
  475. page += FPSTR(HTTP_END);
  476. request->send(200, "text/html", page);
  477. DEBUG_WM(F("Sent config page"));
  478. }
  479. /** Handle the WLAN save form and redirect to WLAN config page again */
  480. void AsyncWiFiManager::handleWifiSave(AsyncWebServerRequest *request) {
  481. DEBUG_WM(F("WiFi save"));
  482. //SAVE/connect here
  483. _ssid = request->arg("s").c_str();
  484. _pass = request->arg("p").c_str();
  485. //parameters
  486. for (int i = 0; i < _paramsCount; i++) {
  487. if (_params[i] == NULL) {
  488. break;
  489. }
  490. //read parameter
  491. String value = request->arg(_params[i]->getID()).c_str();
  492. //store it in array
  493. value.toCharArray(_params[i]->_value, _params[i]->_length);
  494. DEBUG_WM(F("Parameter"));
  495. DEBUG_WM(_params[i]->getID());
  496. DEBUG_WM(value);
  497. }
  498. if (request->hasArg("ip")) {
  499. DEBUG_WM(F("static ip"));
  500. DEBUG_WM(request->arg("ip"));
  501. //_sta_static_ip.fromString(request->arg("ip"));
  502. String ip = request->arg("ip");
  503. optionalIPFromString(&_sta_static_ip, ip.c_str());
  504. }
  505. if (request->hasArg("gw")) {
  506. DEBUG_WM(F("static gateway"));
  507. DEBUG_WM(request->arg("gw"));
  508. String gw = request->arg("gw");
  509. optionalIPFromString(&_sta_static_gw, gw.c_str());
  510. }
  511. if (request->hasArg("sn")) {
  512. DEBUG_WM(F("static netmask"));
  513. DEBUG_WM(request->arg("sn"));
  514. String sn = request->arg("sn");
  515. optionalIPFromString(&_sta_static_sn, sn.c_str());
  516. }
  517. String page = FPSTR(WFM_HTTP_HEAD);
  518. page.replace("{v}", "Credentials Saved");
  519. page += FPSTR(HTTP_SCRIPT);
  520. page += FPSTR(HTTP_STYLE);
  521. page += _customHeadElement;
  522. page += FPSTR(HTTP_HEAD_END);
  523. page += FPSTR(HTTP_SAVED);
  524. page += FPSTR(HTTP_END);
  525. request->send(200, "text/html", page);
  526. DEBUG_WM(F("Sent wifi save page"));
  527. connect = true; //signal ready to connect/reset
  528. }
  529. /** Handle the info page */
  530. void AsyncWiFiManager::handleInfo(AsyncWebServerRequest *request) {
  531. DEBUG_WM(F("Info"));
  532. String page = FPSTR(WFM_HTTP_HEAD);
  533. page.replace("{v}", "Info");
  534. page += FPSTR(HTTP_SCRIPT);
  535. page += FPSTR(HTTP_STYLE);
  536. page += _customHeadElement;
  537. page += FPSTR(HTTP_HEAD_END);
  538. page += F("<dl>");
  539. page += F("<dt>Chip ID</dt><dd>");
  540. page += ESP.getChipId();
  541. page += F("</dd>");
  542. page += F("<dt>Flash Chip ID</dt><dd>");
  543. page += ESP.getFlashChipId();
  544. page += F("</dd>");
  545. page += F("<dt>IDE Flash Size</dt><dd>");
  546. page += ESP.getFlashChipSize();
  547. page += F(" bytes</dd>");
  548. page += F("<dt>Real Flash Size</dt><dd>");
  549. page += ESP.getFlashChipRealSize();
  550. page += F(" bytes</dd>");
  551. page += F("<dt>Soft AP IP</dt><dd>");
  552. page += WiFi.softAPIP().toString();
  553. page += F("</dd>");
  554. page += F("<dt>Soft AP MAC</dt><dd>");
  555. page += WiFi.softAPmacAddress();
  556. page += F("</dd>");
  557. page += F("<dt>Station MAC</dt><dd>");
  558. page += WiFi.macAddress();
  559. page += F("</dd>");
  560. page += F("</dl>");
  561. page += FPSTR(HTTP_END);
  562. request->send(200, "text/html", page);
  563. DEBUG_WM(F("Sent info page"));
  564. }
  565. /** Handle the reset page */
  566. void AsyncWiFiManager::handleReset(AsyncWebServerRequest *request) {
  567. DEBUG_WM(F("Reset"));
  568. String page = FPSTR(WFM_HTTP_HEAD);
  569. page.replace("{v}", "Info");
  570. page += FPSTR(HTTP_SCRIPT);
  571. page += FPSTR(HTTP_STYLE);
  572. page += _customHeadElement;
  573. page += FPSTR(HTTP_HEAD_END);
  574. page += F("Module will reset in a few seconds.");
  575. page += FPSTR(HTTP_END);
  576. request->send(200, "text/html", page);
  577. DEBUG_WM(F("Sent reset page"));
  578. delay(5000);
  579. ESP.reset();
  580. delay(2000);
  581. }
  582. //removed as mentioned here https://github.com/tzapu/AsyncWiFiManager/issues/114
  583. /*void AsyncWiFiManager::handle204(AsyncWebServerRequest *request) {
  584. DEBUG_WM(F("204 No Response"));
  585. request->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  586. request->sendHeader("Pragma", "no-cache");
  587. request->sendHeader("Expires", "-1");
  588. request->send ( 204, "text/plain", "");
  589. }*/
  590. void AsyncWiFiManager::handleNotFound(AsyncWebServerRequest *request) {
  591. if (captivePortal(request)) { // If captive portal redirect instead of displaying the error page.
  592. return;
  593. }
  594. String message = "File Not Found\n\n";
  595. message += "URI: ";
  596. message += request->url();
  597. message += "\nMethod: ";
  598. message += ( request->method() == HTTP_GET ) ? "GET" : "POST";
  599. message += "\nArguments: ";
  600. message += request->args();
  601. message += "\n";
  602. for ( uint8_t i = 0; i < request->args(); i++ ) {
  603. message += " " + request->argName ( i ) + ": " + request->arg ( i ) + "\n";
  604. }
  605. AsyncWebServerResponse *response = request->beginResponse(404,"text/plain",message);
  606. response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  607. response->addHeader("Pragma", "no-cache");
  608. response->addHeader("Expires", "-1");
  609. request->send (response );
  610. }
  611. /** Redirect to captive portal if we got a request for another domain. Return true in that case so the page handler do not try to handle the request again. */
  612. boolean AsyncWiFiManager::captivePortal(AsyncWebServerRequest *request) {
  613. if (!isIp(request->host()) ) {
  614. DEBUG_WM(F("Request redirected to captive portal"));
  615. AsyncWebServerResponse *response = request->beginResponse(302,"text/plain","");
  616. response->addHeader("Location", String("http://") + toStringIp(request->client()->localIP()));
  617. request->send ( response);
  618. return true;
  619. }
  620. return false;
  621. }
  622. //start up config portal callback
  623. void AsyncWiFiManager::setAPCallback( void (*func)(AsyncWiFiManager* myAsyncWiFiManager) ) {
  624. _apcallback = func;
  625. }
  626. //start up save config callback
  627. void AsyncWiFiManager::setSaveConfigCallback( void (*func)(void) ) {
  628. _savecallback = func;
  629. }
  630. //sets a custom element to add to head, like a new style tag
  631. void AsyncWiFiManager::setCustomHeadElement(const char* element) {
  632. _customHeadElement = element;
  633. }
  634. //if this is true, remove duplicated Access Points - defaut true
  635. void AsyncWiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) {
  636. _removeDuplicateAPs = removeDuplicates;
  637. }
  638. template <typename Generic>
  639. void AsyncWiFiManager::DEBUG_WM(Generic text) {
  640. if (_debug) {
  641. Serial.print("*WM: ");
  642. Serial.println(text);
  643. }
  644. }
  645. int AsyncWiFiManager::getRSSIasQuality(int RSSI) {
  646. int quality = 0;
  647. if (RSSI <= -100) {
  648. quality = 0;
  649. } else if (RSSI >= -50) {
  650. quality = 100;
  651. } else {
  652. quality = 2 * (RSSI + 100);
  653. }
  654. return quality;
  655. }
  656. /** Is this an IP? */
  657. boolean AsyncWiFiManager::isIp(String str) {
  658. for (int i = 0; i < str.length(); i++) {
  659. int c = str.charAt(i);
  660. if (c != '.' && (c < '0' || c > '9')) {
  661. return false;
  662. }
  663. }
  664. return true;
  665. }
  666. /** IP to String? */
  667. String AsyncWiFiManager::toStringIp(IPAddress ip) {
  668. String res = "";
  669. for (int i = 0; i < 3; i++) {
  670. res += String((ip >> (8 * i)) & 0xFF) + ".";
  671. }
  672. res += String(((ip >> 8 * 3)) & 0xFF);
  673. return res;
  674. }