ESPAsyncWiFiManager.cpp 24 KB

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