ESPAsyncWiFiManager.cpp 32 KB

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