ESPAsyncWiFiManager.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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. Ported to Async Web Server by https://github.com/alanswx
  11. Licensed under MIT license
  12. **************************************************************/
  13. #include "ESPAsyncWiFiManager.h"
  14. AsyncWiFiManagerParameter::AsyncWiFiManagerParameter(const char *custom) {
  15. _id = NULL;
  16. _placeholder = NULL;
  17. _length = 0;
  18. _value = NULL;
  19. _customHTML = custom;
  20. }
  21. AsyncWiFiManagerParameter::AsyncWiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length) {
  22. init(id, placeholder, defaultValue, length, "");
  23. }
  24. AsyncWiFiManagerParameter::AsyncWiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom) {
  25. init(id, placeholder, defaultValue, length, custom);
  26. }
  27. void AsyncWiFiManagerParameter::init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom) {
  28. _id = id;
  29. _placeholder = placeholder;
  30. _length = length;
  31. _value = new char[length + 1];
  32. for (int i = 0; i < length; i++) {
  33. _value[i] = 0;
  34. }
  35. if (defaultValue != NULL) {
  36. strncpy(_value, defaultValue, length);
  37. }
  38. _customHTML = custom;
  39. }
  40. const char* AsyncWiFiManagerParameter::getValue() {
  41. return _value;
  42. }
  43. const char* AsyncWiFiManagerParameter::getID() {
  44. return _id;
  45. }
  46. const char* AsyncWiFiManagerParameter::getPlaceholder() {
  47. return _placeholder;
  48. }
  49. int AsyncWiFiManagerParameter::getValueLength() {
  50. return _length;
  51. }
  52. const char* AsyncWiFiManagerParameter::getCustomHTML() {
  53. return _customHTML;
  54. }
  55. #ifdef USE_EADNS
  56. AsyncWiFiManager::AsyncWiFiManager(AsyncWebServer *server, AsyncDNSServer *dns) :server(server), dnsServer(dns) {
  57. #else
  58. AsyncWiFiManager::AsyncWiFiManager(AsyncWebServer *server, DNSServer *dns) :server(server), dnsServer(dns) {
  59. #endif
  60. wifiSSIDs = NULL;
  61. wifiSSIDscan=true;
  62. _modeless=false;
  63. shouldscan=true;
  64. }
  65. void AsyncWiFiManager::addParameter(AsyncWiFiManagerParameter *p) {
  66. _params[_paramsCount] = p;
  67. _paramsCount++;
  68. DEBUG_WM("Adding parameter");
  69. DEBUG_WM(p->getID());
  70. }
  71. void AsyncWiFiManager::setupConfigPortal() {
  72. // dnsServer.reset(new DNSServer());
  73. // server.reset(new ESP8266WebServer(80));
  74. server->reset();
  75. DEBUG_WM(F(""));
  76. _configPortalStart = millis();
  77. DEBUG_WM(F("Configuring access point... "));
  78. DEBUG_WM(_apName);
  79. if (_apPassword != NULL) {
  80. if (strlen(_apPassword) < 8 || strlen(_apPassword) > 63) {
  81. // fail passphrase to short or long!
  82. DEBUG_WM(F("Invalid AccessPoint password. Ignoring"));
  83. _apPassword = NULL;
  84. }
  85. DEBUG_WM(_apPassword);
  86. }
  87. //optional soft ip config
  88. if (_ap_static_ip) {
  89. DEBUG_WM(F("Custom AP IP/GW/Subnet"));
  90. WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn);
  91. }
  92. if (_apPassword != NULL) {
  93. WiFi.softAP(_apName, _apPassword);//password option
  94. } else {
  95. WiFi.softAP(_apName);
  96. }
  97. delay(500); // Without delay I've seen the IP address blank
  98. DEBUG_WM(F("AP IP address: "));
  99. DEBUG_WM(WiFi.softAPIP());
  100. /* Setup the DNS server redirecting all the domains to the apIP */
  101. dnsServer->setErrorReplyCode(DNSReplyCode::NoError);
  102. dnsServer->start(DNS_PORT, "*", WiFi.softAPIP());
  103. setInfo();
  104. /* Setup web pages: root, wifi config pages, SO captive portal detectors and not found. */
  105. server->on("/", std::bind(&AsyncWiFiManager::handleRoot, this,std::placeholders::_1)).setFilter(ON_AP_FILTER);
  106. server->on("/wifi", std::bind(&AsyncWiFiManager::handleWifi, this, std::placeholders::_1,true)).setFilter(ON_AP_FILTER);
  107. server->on("/0wifi", std::bind(&AsyncWiFiManager::handleWifi, this,std::placeholders::_1, false)).setFilter(ON_AP_FILTER);
  108. server->on("/wifisave", std::bind(&AsyncWiFiManager::handleWifiSave,this,std::placeholders::_1)).setFilter(ON_AP_FILTER);
  109. server->on("/i", std::bind(&AsyncWiFiManager::handleInfo,this, std::placeholders::_1)).setFilter(ON_AP_FILTER);
  110. server->on("/r", std::bind(&AsyncWiFiManager::handleReset, this,std::placeholders::_1)).setFilter(ON_AP_FILTER);
  111. //server->on("/generate_204", std::bind(&AsyncWiFiManager::handle204, this)); //Android/Chrome OS captive portal check.
  112. 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.
  113. server->onNotFound (std::bind(&AsyncWiFiManager::handleNotFound,this,std::placeholders::_1));
  114. server->begin(); // Web server start
  115. DEBUG_WM(F("HTTP server started"));
  116. }
  117. static const char HEX_CHAR_ARRAY[17] = "0123456789ABCDEF";
  118. /**
  119. * convert char array (hex values) to readable string by seperator
  120. * buf: buffer to convert
  121. * length: data length
  122. * strSeperator seperator between each hex value
  123. * return: formated value as String
  124. */
  125. static String byteToHexString(uint8_t* buf, uint8_t length, String strSeperator="-") {
  126. String dataString = "";
  127. for (uint8_t i = 0; i < length; i++) {
  128. byte v = buf[i] / 16;
  129. byte w = buf[i] % 16;
  130. if (i>0) {
  131. dataString += strSeperator;
  132. }
  133. dataString += String(HEX_CHAR_ARRAY[v]);
  134. dataString += String(HEX_CHAR_ARRAY[w]);
  135. }
  136. dataString.toUpperCase();
  137. return dataString;
  138. } // byteToHexString
  139. #if !defined(ESP8266)
  140. String getESP32ChipID() {
  141. uint64_t chipid;
  142. chipid=ESP.getEfuseMac();//The chip ID is essentially its MAC address(length: 6 bytes).
  143. int chipid_size = 6;
  144. uint8_t chipid_arr[chipid_size];
  145. for (uint8_t i=0; i < chipid_size; i++) {
  146. chipid_arr[i] = (chipid >> (8 * i)) & 0xff;
  147. }
  148. return byteToHexString(chipid_arr, chipid_size, "");
  149. }
  150. #endif
  151. boolean AsyncWiFiManager::autoConnect() {
  152. String ssid = "ESP";
  153. #if defined(ESP8266)
  154. ssid += String(ESP.getChipId());
  155. #else
  156. ssid += getESP32ChipID();
  157. #endif
  158. return autoConnect(ssid.c_str(), NULL);
  159. }
  160. boolean AsyncWiFiManager::autoConnect(char const *apName, char const *apPassword) {
  161. DEBUG_WM(F(""));
  162. DEBUG_WM(F("AutoConnect"));
  163. // read eeprom for ssid and pass
  164. //String ssid = getSSID();
  165. //String pass = getPassword();
  166. // attempt to connect; should it fail, fall back to AP
  167. WiFi.mode(WIFI_STA);
  168. if (connectWifi("", "") == WL_CONNECTED) {
  169. DEBUG_WM(F("IP Address:"));
  170. DEBUG_WM(WiFi.localIP());
  171. //connected
  172. return true;
  173. }
  174. return startConfigPortal(apName, apPassword);
  175. }
  176. String AsyncWiFiManager::networkListAsString()
  177. {
  178. String pager ;
  179. //display networks in page
  180. for (int i = 0; i < wifiSSIDCount; i++) {
  181. if (wifiSSIDs[i].duplicate == true) continue; // skip dups
  182. int quality = getRSSIasQuality(wifiSSIDs[i].RSSI);
  183. if (_minimumQuality == -1 || _minimumQuality < quality) {
  184. String item = FPSTR(HTTP_ITEM);
  185. String rssiQ;
  186. rssiQ += quality;
  187. item.replace("{v}", wifiSSIDs[i].SSID);
  188. item.replace("{r}", rssiQ);
  189. #if defined(ESP8266)
  190. if (wifiSSIDs[i].encryptionType != ENC_TYPE_NONE) {
  191. #else
  192. if (wifiSSIDs[i].encryptionType != WIFI_AUTH_OPEN) {
  193. #endif
  194. item.replace("{i}", "l");
  195. } else {
  196. item.replace("{i}", "");
  197. }
  198. pager += item;
  199. } else {
  200. DEBUG_WM(F("Skipping due to quality"));
  201. }
  202. }
  203. return pager;
  204. }
  205. String AsyncWiFiManager::scanModal()
  206. {
  207. shouldscan=true;
  208. scan();
  209. String pager=networkListAsString();
  210. return pager;
  211. }
  212. void AsyncWiFiManager::scan()
  213. {
  214. if (!shouldscan) return;
  215. DEBUG_WM(F("About to scan()"));
  216. if (wifiSSIDscan)
  217. {
  218. delay(100);
  219. }
  220. if (wifiSSIDscan)
  221. {
  222. int n = WiFi.scanNetworks();
  223. DEBUG_WM(F("Scan done"));
  224. if (n == 0) {
  225. DEBUG_WM(F("No networks found"));
  226. // page += F("No networks found. Refresh to scan again.");
  227. } else {
  228. if (wifiSSIDscan)
  229. {
  230. /* WE SHOULD MOVE THIS IN PLACE ATOMICALLY */
  231. if (wifiSSIDs) delete [] wifiSSIDs;
  232. wifiSSIDs = new WiFiResult[n];
  233. wifiSSIDCount = n;
  234. if (n>0)
  235. shouldscan=false;
  236. for (int i=0;i<n;i++)
  237. {
  238. wifiSSIDs[i].duplicate=false;
  239. #if defined(ESP8266)
  240. bool res=WiFi.getNetworkInfo(i, wifiSSIDs[i].SSID, wifiSSIDs[i].encryptionType, wifiSSIDs[i].RSSI, wifiSSIDs[i].BSSID, wifiSSIDs[i].channel, wifiSSIDs[i].isHidden);
  241. #else
  242. bool res=WiFi.getNetworkInfo(i, wifiSSIDs[i].SSID, wifiSSIDs[i].encryptionType, wifiSSIDs[i].RSSI, wifiSSIDs[i].BSSID, wifiSSIDs[i].channel);
  243. #endif
  244. }
  245. // RSSI SORT
  246. // old sort
  247. for (int i = 0; i < n; i++) {
  248. for (int j = i + 1; j < n; j++) {
  249. if (wifiSSIDs[j].RSSI > wifiSSIDs[i].RSSI) {
  250. std::swap(wifiSSIDs[i], wifiSSIDs[j]);
  251. }
  252. }
  253. }
  254. // remove duplicates ( must be RSSI sorted )
  255. if (_removeDuplicateAPs) {
  256. String cssid;
  257. for (int i = 0; i < n; i++) {
  258. if (wifiSSIDs[i].duplicate == true) continue;
  259. cssid = wifiSSIDs[i].SSID;
  260. for (int j = i + 1; j < n; j++) {
  261. if (cssid == wifiSSIDs[j].SSID) {
  262. DEBUG_WM("DUP AP: " +wifiSSIDs[j].SSID);
  263. wifiSSIDs[j].duplicate=true; // set dup aps to NULL
  264. }
  265. }
  266. }
  267. }
  268. }
  269. }
  270. }
  271. }
  272. void AsyncWiFiManager::startConfigPortalModeless(char const *apName, char const *apPassword) {
  273. _modeless =true;
  274. _apName = apName;
  275. _apPassword = apPassword;
  276. /*
  277. AJS - do we want this?
  278. */
  279. //setup AP
  280. WiFi.mode(WIFI_AP_STA);
  281. DEBUG_WM("SET AP STA");
  282. // try to connect
  283. if (connectWifi("", "") == WL_CONNECTED) {
  284. DEBUG_WM(F("IP Address:"));
  285. DEBUG_WM(WiFi.localIP());
  286. //connected
  287. // call the callback!
  288. _savecallback();
  289. }
  290. //notify we entered AP mode
  291. if ( _apcallback != NULL) {
  292. _apcallback(this);
  293. }
  294. connect = false;
  295. setupConfigPortal();
  296. scannow= -1 ;
  297. }
  298. void AsyncWiFiManager::loop(){
  299. safeLoop();
  300. criticalLoop();
  301. }
  302. void AsyncWiFiManager::setInfo() {
  303. if (needInfo) {
  304. pager = infoAsString();
  305. wifiStatus = WiFi.status();
  306. needInfo = false;
  307. }
  308. }
  309. /**
  310. * Anything that accesses WiFi, ESP or EEPROM goes here
  311. */
  312. void AsyncWiFiManager::criticalLoop(){
  313. if (_modeless)
  314. {
  315. if ( scannow==-1 || millis() > scannow + 60000)
  316. {
  317. scan();
  318. scannow= millis() ;
  319. }
  320. if (connect) {
  321. connect = false;
  322. //delay(2000);
  323. DEBUG_WM(F("Connecting to new AP"));
  324. // using user-provided _ssid, _pass in place of system-stored ssid and pass
  325. if (connectWifi(_ssid, _pass) != WL_CONNECTED) {
  326. DEBUG_WM(F("Failed to connect."));
  327. } else {
  328. //connected
  329. // alanswx - should we have a config to decide if we should shut down AP?
  330. // WiFi.mode(WIFI_STA);
  331. //notify that configuration has changed and any optional parameters should be saved
  332. if ( _savecallback != NULL) {
  333. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  334. _savecallback();
  335. }
  336. return;
  337. }
  338. if (_shouldBreakAfterConfig) {
  339. //flag set to exit after config after trying to connect
  340. //notify that configuration has changed and any optional parameters should be saved
  341. if ( _savecallback != NULL) {
  342. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  343. _savecallback();
  344. }
  345. }
  346. }
  347. }
  348. }
  349. /*
  350. * Anything that doesn't access WiFi, ESP or EEPROM can go here
  351. */
  352. void AsyncWiFiManager::safeLoop(){
  353. #ifndef USE_EADNS
  354. dnsServer->processNextRequest();
  355. #endif
  356. }
  357. boolean AsyncWiFiManager::startConfigPortal(char const *apName, char const *apPassword) {
  358. //setup AP
  359. WiFi.mode(WIFI_AP_STA);
  360. DEBUG_WM("SET AP STA");
  361. _apName = apName;
  362. _apPassword = apPassword;
  363. //notify we entered AP mode
  364. if ( _apcallback != NULL) {
  365. _apcallback(this);
  366. }
  367. connect = false;
  368. setupConfigPortal();
  369. scannow= -1 ;
  370. while (_configPortalTimeout == 0 || millis() < _configPortalStart + _configPortalTimeout) {
  371. //DNS
  372. //dnsServer->processNextRequest();
  373. //
  374. // we should do a scan every so often here
  375. //
  376. if ( millis() > scannow + 10000)
  377. {
  378. DEBUG_WM(F("About to scan()"));
  379. shouldscan=true; // since we are modal, we can scan every time
  380. scan();
  381. scannow= millis() ;
  382. }
  383. if (connect) {
  384. connect = false;
  385. delay(2000);
  386. DEBUG_WM(F("Connecting to new AP"));
  387. // using user-provided _ssid, _pass in place of system-stored ssid and pass
  388. if (connectWifi(_ssid, _pass) != WL_CONNECTED) {
  389. DEBUG_WM(F("Failed to connect."));
  390. } else {
  391. //connected
  392. WiFi.mode(WIFI_STA);
  393. //notify that configuration has changed and any optional parameters should be saved
  394. if ( _savecallback != NULL) {
  395. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  396. _savecallback();
  397. }
  398. break;
  399. }
  400. if (_shouldBreakAfterConfig) {
  401. //flag set to exit after config after trying to connect
  402. //notify that configuration has changed and any optional parameters should be saved
  403. if ( _savecallback != NULL) {
  404. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  405. _savecallback();
  406. }
  407. break;
  408. }
  409. }
  410. yield();
  411. }
  412. server->reset();
  413. #ifdef USE_EADNS
  414. *dnsServer=AsyncDNSServer();
  415. #else
  416. *dnsServer=DNSServer();
  417. #endif
  418. return WiFi.status() == WL_CONNECTED;
  419. }
  420. int AsyncWiFiManager::connectWifi(String ssid, String pass) {
  421. DEBUG_WM(F("Connecting as wifi client..."));
  422. // check if we've got static_ip settings, if we do, use those.
  423. if (_sta_static_ip) {
  424. DEBUG_WM(F("Custom STA IP/GW/Subnet"));
  425. WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn);
  426. DEBUG_WM(WiFi.localIP());
  427. }
  428. //fix for auto connect racing issue
  429. // if (WiFi.status() == WL_CONNECTED) {
  430. // DEBUG_WM("Already connected. Bailing out.");
  431. // return WL_CONNECTED;
  432. // }
  433. //check if we have ssid and pass and force those, if not, try with last saved values
  434. if (ssid != "") {
  435. #if defined(ESP8266)
  436. //trying to fix connection in progress hanging
  437. ETS_UART_INTR_DISABLE();
  438. wifi_station_disconnect();
  439. ETS_UART_INTR_ENABLE();
  440. #else
  441. WiFi.disconnect(false);
  442. #endif
  443. WiFi.begin(ssid.c_str(), pass.c_str());
  444. } else {
  445. if (WiFi.SSID().length() > 0) {
  446. DEBUG_WM("Using last saved values, should be faster");
  447. #if defined(ESP8266)
  448. //trying to fix connection in progress hanging
  449. ETS_UART_INTR_DISABLE();
  450. wifi_station_disconnect();
  451. ETS_UART_INTR_ENABLE();
  452. #else
  453. WiFi.disconnect(false);
  454. #endif
  455. WiFi.begin();
  456. } else {
  457. DEBUG_WM("No saved credentials");
  458. }
  459. }
  460. int connRes = waitForConnectResult();
  461. DEBUG_WM ("Connection result: ");
  462. DEBUG_WM ( connRes );
  463. //not connected, WPS enabled, no pass - first attempt
  464. if (_tryWPS && connRes != WL_CONNECTED && pass == "") {
  465. startWPS();
  466. //should be connected at the end of WPS
  467. connRes = waitForConnectResult();
  468. }
  469. needInfo = true;
  470. setInfo();
  471. return connRes;
  472. }
  473. uint8_t AsyncWiFiManager::waitForConnectResult() {
  474. if (_connectTimeout == 0) {
  475. return WiFi.waitForConnectResult();
  476. } else {
  477. DEBUG_WM (F("Waiting for connection result with time out"));
  478. unsigned long start = millis();
  479. boolean keepConnecting = true;
  480. uint8_t status;
  481. while (keepConnecting) {
  482. status = WiFi.status();
  483. if (millis() > start + _connectTimeout) {
  484. keepConnecting = false;
  485. DEBUG_WM (F("Connection timed out"));
  486. }
  487. if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) {
  488. keepConnecting = false;
  489. }
  490. delay(100);
  491. }
  492. return status;
  493. }
  494. }
  495. void AsyncWiFiManager::startWPS() {
  496. DEBUG_WM("START WPS");
  497. #if defined(ESP8266)
  498. WiFi.beginWPSConfig();
  499. #else
  500. esp_wps_config_t config = WPS_CONFIG_INIT_DEFAULT(ESP_WPS_MODE);
  501. esp_wifi_wps_enable(&config);
  502. esp_wifi_wps_start(0);
  503. #endif
  504. DEBUG_WM("END WPS");
  505. }
  506. /*
  507. String AsyncWiFiManager::getSSID() {
  508. if (_ssid == "") {
  509. DEBUG_WM(F("Reading SSID"));
  510. _ssid = WiFi.SSID();
  511. DEBUG_WM(F("SSID: "));
  512. DEBUG_WM(_ssid);
  513. }
  514. return _ssid;
  515. }
  516. String AsyncWiFiManager::getPassword() {
  517. if (_pass == "") {
  518. DEBUG_WM(F("Reading Password"));
  519. _pass = WiFi.psk();
  520. DEBUG_WM("Password: " + _pass);
  521. //DEBUG_WM(_pass);
  522. }
  523. return _pass;
  524. }
  525. */
  526. String AsyncWiFiManager::getConfigPortalSSID() {
  527. return _apName;
  528. }
  529. void AsyncWiFiManager::resetSettings() {
  530. DEBUG_WM(F("settings invalidated"));
  531. DEBUG_WM(F("THIS MAY CAUSE AP NOT TO START UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA."));
  532. WiFi.disconnect(true);
  533. //delay(200);
  534. }
  535. void AsyncWiFiManager::setTimeout(unsigned long seconds) {
  536. setConfigPortalTimeout(seconds);
  537. }
  538. void AsyncWiFiManager::setConfigPortalTimeout(unsigned long seconds) {
  539. _configPortalTimeout = seconds * 1000;
  540. }
  541. void AsyncWiFiManager::setConnectTimeout(unsigned long seconds) {
  542. _connectTimeout = seconds * 1000;
  543. }
  544. void AsyncWiFiManager::setDebugOutput(boolean debug) {
  545. _debug = debug;
  546. }
  547. void AsyncWiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) {
  548. _ap_static_ip = ip;
  549. _ap_static_gw = gw;
  550. _ap_static_sn = sn;
  551. }
  552. void AsyncWiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) {
  553. _sta_static_ip = ip;
  554. _sta_static_gw = gw;
  555. _sta_static_sn = sn;
  556. }
  557. void AsyncWiFiManager::setMinimumSignalQuality(int quality) {
  558. _minimumQuality = quality;
  559. }
  560. void AsyncWiFiManager::setBreakAfterConfig(boolean shouldBreak) {
  561. _shouldBreakAfterConfig = shouldBreak;
  562. }
  563. /** Handle root or redirect to captive portal */
  564. void AsyncWiFiManager::handleRoot(AsyncWebServerRequest *request) {
  565. // AJS - maybe we should set a scan when we get to the root???
  566. // and only scan on demand? timer + on demand? plus a link to make it happen?
  567. shouldscan=true;
  568. scannow= -1 ;
  569. DEBUG_WM(F("Handle root"));
  570. if (captivePortal(request)) { // If captive portal redirect instead of displaying the page.
  571. return;
  572. }
  573. String page = FPSTR(WFM_HTTP_HEAD);
  574. page.replace("{v}", "Options");
  575. page += FPSTR(HTTP_SCRIPT);
  576. page += FPSTR(HTTP_STYLE);
  577. page += _customHeadElement;
  578. page += FPSTR(HTTP_HEAD_END);
  579. page += "<h1>";
  580. page += _apName;
  581. page += "</h1>";
  582. page += F("<h3>AsyncWiFiManager</h3>");
  583. page += FPSTR(HTTP_PORTAL_OPTIONS);
  584. page += FPSTR(HTTP_END);
  585. request->send(200, "text/html", page);
  586. }
  587. /** Wifi config page handler */
  588. void AsyncWiFiManager::handleWifi(AsyncWebServerRequest *request,boolean scan) {
  589. shouldscan=true;
  590. scannow= -1 ;
  591. String page = FPSTR(WFM_HTTP_HEAD);
  592. page.replace("{v}", "Config ESP");
  593. page += FPSTR(HTTP_SCRIPT);
  594. page += FPSTR(HTTP_STYLE);
  595. page += _customHeadElement;
  596. page += FPSTR(HTTP_HEAD_END);
  597. if (scan) {
  598. wifiSSIDscan=false;
  599. DEBUG_WM(F("Scan done"));
  600. if (wifiSSIDCount==0) {
  601. DEBUG_WM(F("No networks found"));
  602. page += F("No networks found. Refresh to scan again.");
  603. } else {
  604. //display networks in page
  605. String pager = networkListAsString();
  606. page += pager;
  607. page += "<br/>";
  608. }
  609. }
  610. wifiSSIDscan=true;
  611. page += FPSTR(HTTP_FORM_START);
  612. char parLength[2];
  613. // add the extra parameters to the form
  614. for (int i = 0; i < _paramsCount; i++) {
  615. if (_params[i] == NULL) {
  616. break;
  617. }
  618. String pitem = FPSTR(HTTP_FORM_PARAM);
  619. if (_params[i]->getID() != NULL) {
  620. pitem.replace("{i}", _params[i]->getID());
  621. pitem.replace("{n}", _params[i]->getID());
  622. pitem.replace("{p}", _params[i]->getPlaceholder());
  623. snprintf(parLength, 2, "%d", _params[i]->getValueLength());
  624. pitem.replace("{l}", parLength);
  625. pitem.replace("{v}", _params[i]->getValue());
  626. pitem.replace("{c}", _params[i]->getCustomHTML());
  627. } else {
  628. pitem = _params[i]->getCustomHTML();
  629. }
  630. page += pitem;
  631. }
  632. if (_params[0] != NULL) {
  633. page += "<br/>";
  634. }
  635. if (_sta_static_ip) {
  636. String item = FPSTR(HTTP_FORM_PARAM);
  637. item.replace("{i}", "ip");
  638. item.replace("{n}", "ip");
  639. item.replace("{p}", "Static IP");
  640. item.replace("{l}", "15");
  641. item.replace("{v}", _sta_static_ip.toString());
  642. page += item;
  643. item = FPSTR(HTTP_FORM_PARAM);
  644. item.replace("{i}", "gw");
  645. item.replace("{n}", "gw");
  646. item.replace("{p}", "Static Gateway");
  647. item.replace("{l}", "15");
  648. item.replace("{v}", _sta_static_gw.toString());
  649. page += item;
  650. item = FPSTR(HTTP_FORM_PARAM);
  651. item.replace("{i}", "sn");
  652. item.replace("{n}", "sn");
  653. item.replace("{p}", "Subnet");
  654. item.replace("{l}", "15");
  655. item.replace("{v}", _sta_static_sn.toString());
  656. page += item;
  657. page += "<br/>";
  658. }
  659. page += FPSTR(HTTP_FORM_END);
  660. page += FPSTR(HTTP_SCAN_LINK);
  661. page += FPSTR(HTTP_END);
  662. request->send(200, "text/html", page);
  663. DEBUG_WM(F("Sent config page"));
  664. }
  665. /** Handle the WLAN save form and redirect to WLAN config page again */
  666. void AsyncWiFiManager::handleWifiSave(AsyncWebServerRequest *request) {
  667. DEBUG_WM(F("WiFi save"));
  668. //SAVE/connect here
  669. needInfo = true;
  670. _ssid = request->arg("s").c_str();
  671. _pass = request->arg("p").c_str();
  672. //parameters
  673. for (int i = 0; i < _paramsCount; i++) {
  674. if (_params[i] == NULL) {
  675. break;
  676. }
  677. //read parameter
  678. String value = request->arg(_params[i]->getID()).c_str();
  679. //store it in array
  680. value.toCharArray(_params[i]->_value, _params[i]->_length);
  681. DEBUG_WM(F("Parameter"));
  682. DEBUG_WM(_params[i]->getID());
  683. DEBUG_WM(value);
  684. }
  685. if (request->hasArg("ip")) {
  686. DEBUG_WM(F("static ip"));
  687. DEBUG_WM(request->arg("ip"));
  688. //_sta_static_ip.fromString(request->arg("ip"));
  689. String ip = request->arg("ip");
  690. optionalIPFromString(&_sta_static_ip, ip.c_str());
  691. }
  692. if (request->hasArg("gw")) {
  693. DEBUG_WM(F("static gateway"));
  694. DEBUG_WM(request->arg("gw"));
  695. String gw = request->arg("gw");
  696. optionalIPFromString(&_sta_static_gw, gw.c_str());
  697. }
  698. if (request->hasArg("sn")) {
  699. DEBUG_WM(F("static netmask"));
  700. DEBUG_WM(request->arg("sn"));
  701. String sn = request->arg("sn");
  702. optionalIPFromString(&_sta_static_sn, sn.c_str());
  703. }
  704. String page = FPSTR(WFM_HTTP_HEAD);
  705. page.replace("{v}", "Credentials Saved");
  706. page += FPSTR(HTTP_SCRIPT);
  707. page += FPSTR(HTTP_STYLE);
  708. page += _customHeadElement;
  709. page += F("<meta http-equiv=\"refresh\" content=\"5; url=/i\">");
  710. page += FPSTR(HTTP_HEAD_END);
  711. page += FPSTR(HTTP_SAVED);
  712. page += FPSTR(HTTP_END);
  713. request->send(200, "text/html", page);
  714. DEBUG_WM(F("Sent wifi save page"));
  715. connect = true; //signal ready to connect/reset
  716. }
  717. /** Handle the info page */
  718. String AsyncWiFiManager::infoAsString()
  719. {
  720. String page;
  721. page += F("<dt>Chip ID</dt><dd>");
  722. #if defined(ESP8266)
  723. page += ESP.getChipId();
  724. #else
  725. page += getESP32ChipID();
  726. #endif
  727. page += F("</dd>");
  728. page += F("<dt>Flash Chip ID</dt><dd>");
  729. #if defined(ESP8266)
  730. page += ESP.getFlashChipId();
  731. #else
  732. page += F("N/A for ESP32");
  733. #endif
  734. page += F("</dd>");
  735. page += F("<dt>IDE Flash Size</dt><dd>");
  736. page += ESP.getFlashChipSize();
  737. page += F(" bytes</dd>");
  738. page += F("<dt>Real Flash Size</dt><dd>");
  739. #if defined(ESP8266)
  740. page += ESP.getFlashChipRealSize();
  741. #else
  742. page += F("N/A for ESP32");
  743. #endif
  744. page += F(" bytes</dd>");
  745. page += F("<dt>Soft AP IP</dt><dd>");
  746. page += WiFi.softAPIP().toString();
  747. page += F("</dd>");
  748. page += F("<dt>Soft AP MAC</dt><dd>");
  749. page += WiFi.softAPmacAddress();
  750. page += F("</dd>");
  751. page += F("<dt>Station SSID</dt><dd>");
  752. page += WiFi.SSID();
  753. page += F("</dd>");
  754. page += F("<dt>Station IP</dt><dd>");
  755. page += WiFi.localIP().toString();
  756. page += F("</dd>");
  757. page += F("<dt>Station MAC</dt><dd>");
  758. page += WiFi.macAddress();
  759. page += F("</dd>");
  760. page += F("</dl>");
  761. return page;
  762. }
  763. void AsyncWiFiManager::handleInfo(AsyncWebServerRequest *request) {
  764. DEBUG_WM(F("Info"));
  765. String page = FPSTR(WFM_HTTP_HEAD);
  766. page.replace("{v}", "Info");
  767. page += FPSTR(HTTP_SCRIPT);
  768. page += FPSTR(HTTP_STYLE);
  769. page += _customHeadElement;
  770. if (connect==true)
  771. page += F("<meta http-equiv=\"refresh\" content=\"5; url=/i\">");
  772. page += FPSTR(HTTP_HEAD_END);
  773. page += F("<dl>");
  774. if (connect==true)
  775. {
  776. page += F("<dt>Trying to connect</dt><dd>");
  777. page += wifiStatus;
  778. page += F("</dd>");
  779. }
  780. page +=pager;
  781. page += FPSTR(HTTP_END);
  782. request->send(200, "text/html", page);
  783. DEBUG_WM(F("Sent info page"));
  784. }
  785. /** Handle the reset page */
  786. void AsyncWiFiManager::handleReset(AsyncWebServerRequest *request) {
  787. DEBUG_WM(F("Reset"));
  788. String page = FPSTR(WFM_HTTP_HEAD);
  789. page.replace("{v}", "Info");
  790. page += FPSTR(HTTP_SCRIPT);
  791. page += FPSTR(HTTP_STYLE);
  792. page += _customHeadElement;
  793. page += FPSTR(HTTP_HEAD_END);
  794. page += F("Module will reset in a few seconds.");
  795. page += FPSTR(HTTP_END);
  796. request->send(200, "text/html", page);
  797. DEBUG_WM(F("Sent reset page"));
  798. delay(5000);
  799. #if defined(ESP8266)
  800. ESP.reset();
  801. #else
  802. ESP.restart();
  803. #endif
  804. delay(2000);
  805. }
  806. //removed as mentioned here https://github.com/tzapu/AsyncWiFiManager/issues/114
  807. /*void AsyncWiFiManager::handle204(AsyncWebServerRequest *request) {
  808. DEBUG_WM(F("204 No Response"));
  809. request->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  810. request->sendHeader("Pragma", "no-cache");
  811. request->sendHeader("Expires", "-1");
  812. request->send ( 204, "text/plain", "");
  813. }*/
  814. void AsyncWiFiManager::handleNotFound(AsyncWebServerRequest *request) {
  815. if (captivePortal(request)) { // If captive portal redirect instead of displaying the error page.
  816. return;
  817. }
  818. String message = "File Not Found\n\n";
  819. message += "URI: ";
  820. message += request->url();
  821. message += "\nMethod: ";
  822. message += ( request->method() == HTTP_GET ) ? "GET" : "POST";
  823. message += "\nArguments: ";
  824. message += request->args();
  825. message += "\n";
  826. for ( uint8_t i = 0; i < request->args(); i++ ) {
  827. message += " " + request->argName ( i ) + ": " + request->arg ( i ) + "\n";
  828. }
  829. AsyncWebServerResponse *response = request->beginResponse(404,"text/plain",message);
  830. response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  831. response->addHeader("Pragma", "no-cache");
  832. response->addHeader("Expires", "-1");
  833. request->send (response );
  834. }
  835. /** 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. */
  836. boolean AsyncWiFiManager::captivePortal(AsyncWebServerRequest *request) {
  837. if (!isIp(request->host()) ) {
  838. DEBUG_WM(F("Request redirected to captive portal"));
  839. AsyncWebServerResponse *response = request->beginResponse(302,"text/plain","");
  840. response->addHeader("Location", String("http://") + toStringIp(request->client()->localIP()));
  841. request->send ( response);
  842. return true;
  843. }
  844. return false;
  845. }
  846. //start up config portal callback
  847. void AsyncWiFiManager::setAPCallback( void (*func)(AsyncWiFiManager* myAsyncWiFiManager) ) {
  848. _apcallback = func;
  849. }
  850. //start up save config callback
  851. void AsyncWiFiManager::setSaveConfigCallback( void (*func)(void) ) {
  852. _savecallback = func;
  853. }
  854. //sets a custom element to add to head, like a new style tag
  855. void AsyncWiFiManager::setCustomHeadElement(const char* element) {
  856. _customHeadElement = element;
  857. }
  858. //if this is true, remove duplicated Access Points - defaut true
  859. void AsyncWiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) {
  860. _removeDuplicateAPs = removeDuplicates;
  861. }
  862. template <typename Generic>
  863. void AsyncWiFiManager::DEBUG_WM(Generic text) {
  864. if (_debug) {
  865. Serial.print("*WM: ");
  866. Serial.println(text);
  867. }
  868. }
  869. int AsyncWiFiManager::getRSSIasQuality(int RSSI) {
  870. int quality = 0;
  871. if (RSSI <= -100) {
  872. quality = 0;
  873. } else if (RSSI >= -50) {
  874. quality = 100;
  875. } else {
  876. quality = 2 * (RSSI + 100);
  877. }
  878. return quality;
  879. }
  880. /** Is this an IP? */
  881. boolean AsyncWiFiManager::isIp(String str) {
  882. for (int i = 0; i < str.length(); i++) {
  883. int c = str.charAt(i);
  884. if (c != '.' && (c < '0' || c > '9')) {
  885. return false;
  886. }
  887. }
  888. return true;
  889. }
  890. /** IP to String? */
  891. String AsyncWiFiManager::toStringIp(IPAddress ip) {
  892. String res = "";
  893. for (int i = 0; i < 3; i++) {
  894. res += String((ip >> (8 * i)) & 0xFF) + ".";
  895. }
  896. res += String(((ip >> 8 * 3)) & 0xFF);
  897. return res;
  898. }