ESPAsyncWiFiManager.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  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. _savecallback();
  316. }
  317. //notify we entered AP mode
  318. if ( _apcallback != NULL) {
  319. _apcallback(this);
  320. }
  321. connect = false;
  322. setupConfigPortal();
  323. scannow= -1 ;
  324. }
  325. void AsyncWiFiManager::loop(){
  326. safeLoop();
  327. criticalLoop();
  328. }
  329. void AsyncWiFiManager::setInfo() {
  330. if (needInfo) {
  331. pager = infoAsString();
  332. wifiStatus = WiFi.status();
  333. needInfo = false;
  334. }
  335. }
  336. /**
  337. * Anything that accesses WiFi, ESP or EEPROM goes here
  338. */
  339. void AsyncWiFiManager::criticalLoop(){
  340. if (_modeless)
  341. {
  342. if ( scannow==-1 || millis() > scannow + 60000)
  343. {
  344. scan();
  345. scannow= millis() ;
  346. }
  347. if (connect) {
  348. connect = false;
  349. //delay(2000);
  350. DEBUG_WM(F("Connecting to new AP"));
  351. // using user-provided _ssid, _pass in place of system-stored ssid and pass
  352. if (connectWifi(_ssid, _pass) != WL_CONNECTED) {
  353. DEBUG_WM(F("Failed to connect."));
  354. } else {
  355. //connected
  356. // alanswx - should we have a config to decide if we should shut down AP?
  357. // WiFi.mode(WIFI_STA);
  358. //notify that configuration has changed and any optional parameters should be saved
  359. if ( _savecallback != NULL) {
  360. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  361. _savecallback();
  362. }
  363. return;
  364. }
  365. if (_shouldBreakAfterConfig) {
  366. //flag set to exit after config after trying to connect
  367. //notify that configuration has changed and any optional parameters should be saved
  368. if ( _savecallback != NULL) {
  369. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  370. _savecallback();
  371. }
  372. }
  373. }
  374. }
  375. }
  376. /*
  377. * Anything that doesn't access WiFi, ESP or EEPROM can go here
  378. */
  379. void AsyncWiFiManager::safeLoop(){
  380. #ifndef USE_EADNS
  381. dnsServer->processNextRequest();
  382. #endif
  383. }
  384. boolean AsyncWiFiManager::startConfigPortal(char const *apName, char const *apPassword) {
  385. //setup AP
  386. WiFi.mode(WIFI_AP_STA);
  387. DEBUG_WM("SET AP STA");
  388. _apName = apName;
  389. _apPassword = apPassword;
  390. //notify we entered AP mode
  391. if ( _apcallback != NULL) {
  392. _apcallback(this);
  393. }
  394. connect = false;
  395. setupConfigPortal();
  396. scannow= -1 ;
  397. while (_configPortalTimeout == 0 || millis() < _configPortalStart + _configPortalTimeout) {
  398. //DNS
  399. #ifndef USE_EADNS
  400. dnsServer->processNextRequest();
  401. #endif
  402. //
  403. // we should do a scan every so often here and
  404. // try to reconnect to AP while we are at it
  405. //
  406. if ( scannow == -1 || millis() > scannow + 10000)
  407. {
  408. DEBUG_WM(F("About to scan()"));
  409. shouldscan=true; // since we are modal, we can scan every time
  410. WiFi.disconnect(); // we might still be connecting, so that has to stop for scanning
  411. scan();
  412. if(_tryConnectDuringConfigPortal) WiFi.begin(); // try to reconnect to AP
  413. scannow= millis() ;
  414. }
  415. // attempts to reconnect were successful
  416. if(WiFi.status() == WL_CONNECTED) {
  417. //connected
  418. WiFi.mode(WIFI_STA);
  419. //notify that configuration has changed and any optional parameters should be saved
  420. if ( _savecallback != NULL) {
  421. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  422. _savecallback();
  423. }
  424. break;
  425. }
  426. if (connect) {
  427. connect = false;
  428. delay(2000);
  429. DEBUG_WM(F("Connecting to new AP"));
  430. // using user-provided _ssid, _pass in place of system-stored ssid and pass
  431. if (connectWifi(_ssid, _pass) == WL_CONNECTED) {
  432. //connected
  433. WiFi.mode(WIFI_STA);
  434. //notify that configuration has changed and any optional parameters should be saved
  435. if ( _savecallback != NULL) {
  436. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  437. _savecallback();
  438. }
  439. break;
  440. } else {
  441. DEBUG_WM(F("Failed to connect."));
  442. }
  443. if (_shouldBreakAfterConfig) {
  444. //flag set to exit after config after trying to connect
  445. //notify that configuration has changed and any optional parameters should be saved
  446. if ( _savecallback != NULL) {
  447. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  448. _savecallback();
  449. }
  450. break;
  451. }
  452. }
  453. yield();
  454. }
  455. server->reset();
  456. #ifdef USE_EADNS
  457. *dnsServer=AsyncDNSServer();
  458. #else
  459. *dnsServer=DNSServer();
  460. #endif
  461. return WiFi.status() == WL_CONNECTED;
  462. }
  463. int AsyncWiFiManager::connectWifi(String ssid, String pass) {
  464. DEBUG_WM(F("Connecting as wifi client..."));
  465. // check if we've got static_ip settings, if we do, use those.
  466. if (_sta_static_ip) {
  467. DEBUG_WM(F("Custom STA IP/GW/Subnet/DNS"));
  468. WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn, _sta_static_dns1, _sta_static_dns2);
  469. DEBUG_WM(WiFi.localIP());
  470. }
  471. //fix for auto connect racing issue
  472. // if (WiFi.status() == WL_CONNECTED) {
  473. // DEBUG_WM("Already connected. Bailing out.");
  474. // return WL_CONNECTED;
  475. // }
  476. //check if we have ssid and pass and force those, if not, try with last saved values
  477. if (ssid != "") {
  478. #if defined(ESP8266)
  479. //trying to fix connection in progress hanging
  480. ETS_UART_INTR_DISABLE();
  481. wifi_station_disconnect();
  482. ETS_UART_INTR_ENABLE();
  483. #else
  484. WiFi.disconnect(false);
  485. #endif
  486. WiFi.begin(ssid.c_str(), pass.c_str());
  487. } else {
  488. if (WiFi.SSID().length() > 0) {
  489. DEBUG_WM("Using last saved values, should be faster");
  490. #if defined(ESP8266)
  491. //trying to fix connection in progress hanging
  492. ETS_UART_INTR_DISABLE();
  493. wifi_station_disconnect();
  494. ETS_UART_INTR_ENABLE();
  495. #else
  496. WiFi.disconnect(false);
  497. #endif
  498. WiFi.begin();
  499. } else {
  500. DEBUG_WM("Try to connect with saved credentials");
  501. WiFi.begin();
  502. }
  503. }
  504. int connRes = waitForConnectResult();
  505. DEBUG_WM ("Connection result: ");
  506. DEBUG_WM ( connRes );
  507. //not connected, WPS enabled, no pass - first attempt
  508. #ifdef NO_EXTRA_4K_HEAP
  509. if (_tryWPS && connRes != WL_CONNECTED && pass == "") {
  510. startWPS();
  511. //should be connected at the end of WPS
  512. connRes = waitForConnectResult();
  513. }
  514. #endif
  515. needInfo = true;
  516. setInfo();
  517. return connRes;
  518. }
  519. uint8_t AsyncWiFiManager::waitForConnectResult() {
  520. if (_connectTimeout == 0) {
  521. return WiFi.waitForConnectResult();
  522. } else {
  523. DEBUG_WM (F("Waiting for connection result with time out"));
  524. unsigned long start = millis();
  525. boolean keepConnecting = true;
  526. uint8_t status;
  527. while (keepConnecting) {
  528. status = WiFi.status();
  529. if (millis() > start + _connectTimeout) {
  530. keepConnecting = false;
  531. DEBUG_WM (F("Connection timed out"));
  532. }
  533. if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) {
  534. keepConnecting = false;
  535. }
  536. delay(100);
  537. }
  538. return status;
  539. }
  540. }
  541. #ifdef NO_EXTRA_4K_HEAP
  542. void AsyncWiFiManager::startWPS() {
  543. DEBUG_WM("START WPS");
  544. #if defined(ESP8266)
  545. WiFi.beginWPSConfig();
  546. #else
  547. //esp_wps_config_t config = WPS_CONFIG_INIT_DEFAULT(ESP_WPS_MODE);
  548. esp_wps_config_t config = {};
  549. config.wps_type = ESP_WPS_MODE;
  550. config.crypto_funcs = &g_wifi_default_wps_crypto_funcs;
  551. strcpy(config.factory_info.manufacturer,"ESPRESSIF");
  552. strcpy(config.factory_info.model_number, "ESP32");
  553. strcpy(config.factory_info.model_name, "ESPRESSIF IOT");
  554. strcpy(config.factory_info.device_name,"ESP STATION");
  555. esp_wifi_wps_enable(&config);
  556. esp_wifi_wps_start(0);
  557. #endif
  558. DEBUG_WM("END WPS");
  559. }
  560. #endif
  561. /*
  562. String AsyncWiFiManager::getSSID() {
  563. if (_ssid == "") {
  564. DEBUG_WM(F("Reading SSID"));
  565. _ssid = WiFi.SSID();
  566. DEBUG_WM(F("SSID: "));
  567. DEBUG_WM(_ssid);
  568. }
  569. return _ssid;
  570. }
  571. String AsyncWiFiManager::getPassword() {
  572. if (_pass == "") {
  573. DEBUG_WM(F("Reading Password"));
  574. _pass = WiFi.psk();
  575. DEBUG_WM("Password: " + _pass);
  576. //DEBUG_WM(_pass);
  577. }
  578. return _pass;
  579. }
  580. */
  581. String AsyncWiFiManager::getConfigPortalSSID() {
  582. return _apName;
  583. }
  584. void AsyncWiFiManager::resetSettings() {
  585. DEBUG_WM(F("settings invalidated"));
  586. DEBUG_WM(F("THIS MAY CAUSE AP NOT TO START UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA."));
  587. WiFi.disconnect(true);
  588. //delay(200);
  589. }
  590. void AsyncWiFiManager::setTimeout(unsigned long seconds) {
  591. setConfigPortalTimeout(seconds);
  592. }
  593. void AsyncWiFiManager::setConfigPortalTimeout(unsigned long seconds) {
  594. _configPortalTimeout = seconds * 1000;
  595. }
  596. void AsyncWiFiManager::setConnectTimeout(unsigned long seconds) {
  597. _connectTimeout = seconds * 1000;
  598. }
  599. void AsyncWiFiManager::setTryConnectDuringConfigPortal(boolean v) {
  600. _tryConnectDuringConfigPortal = v;
  601. }
  602. void AsyncWiFiManager::setDebugOutput(boolean debug) {
  603. _debug = debug;
  604. }
  605. void AsyncWiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) {
  606. _ap_static_ip = ip;
  607. _ap_static_gw = gw;
  608. _ap_static_sn = sn;
  609. }
  610. void AsyncWiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns1, IPAddress dns2) {
  611. _sta_static_ip = ip;
  612. _sta_static_gw = gw;
  613. _sta_static_sn = sn;
  614. _sta_static_dns1 = dns1;
  615. _sta_static_dns2 = dns2;
  616. }
  617. void AsyncWiFiManager::setMinimumSignalQuality(int quality) {
  618. _minimumQuality = quality;
  619. }
  620. void AsyncWiFiManager::setBreakAfterConfig(boolean shouldBreak) {
  621. _shouldBreakAfterConfig = shouldBreak;
  622. }
  623. /** Handle root or redirect to captive portal */
  624. void AsyncWiFiManager::handleRoot(AsyncWebServerRequest *request) {
  625. // AJS - maybe we should set a scan when we get to the root???
  626. // and only scan on demand? timer + on demand? plus a link to make it happen?
  627. shouldscan=true;
  628. scannow= -1 ;
  629. DEBUG_WM(F("Handle root"));
  630. if (captivePortal(request)) { // If captive portal redirect instead of displaying the page.
  631. return;
  632. }
  633. String page = FPSTR(WFM_HTTP_HEAD);
  634. page.replace("{v}", "Options");
  635. page += FPSTR(HTTP_SCRIPT);
  636. page += FPSTR(HTTP_STYLE);
  637. page += _customHeadElement;
  638. page += FPSTR(HTTP_HEAD_END);
  639. page += "<h1>";
  640. page += _apName;
  641. page += "</h1>";
  642. page += F("<h3>AsyncWiFiManager</h3>");
  643. page += FPSTR(HTTP_PORTAL_OPTIONS);
  644. page += FPSTR(HTTP_END);
  645. request->send(200, "text/html", page);
  646. }
  647. /** Wifi config page handler */
  648. void AsyncWiFiManager::handleWifi(AsyncWebServerRequest *request,boolean scan) {
  649. shouldscan=true;
  650. scannow= -1 ;
  651. String page = FPSTR(WFM_HTTP_HEAD);
  652. page.replace("{v}", "Config ESP");
  653. page += FPSTR(HTTP_SCRIPT);
  654. page += FPSTR(HTTP_STYLE);
  655. page += _customHeadElement;
  656. page += FPSTR(HTTP_HEAD_END);
  657. if (scan) {
  658. wifiSSIDscan=false;
  659. DEBUG_WM(F("Scan done"));
  660. if (wifiSSIDCount==0) {
  661. DEBUG_WM(F("No networks found"));
  662. page += F("No networks found. Refresh to scan again.");
  663. } else {
  664. //display networks in page
  665. String pager = networkListAsString();
  666. page += pager;
  667. page += "<br/>";
  668. }
  669. }
  670. wifiSSIDscan=true;
  671. page += FPSTR(HTTP_FORM_START);
  672. char parLength[2];
  673. // add the extra parameters to the form
  674. for (int i = 0; i < _paramsCount; i++) {
  675. if (_params[i] == NULL) {
  676. break;
  677. }
  678. String pitem = FPSTR(HTTP_FORM_PARAM);
  679. if (_params[i]->getID() != NULL) {
  680. pitem.replace("{i}", _params[i]->getID());
  681. pitem.replace("{n}", _params[i]->getID());
  682. pitem.replace("{p}", _params[i]->getPlaceholder());
  683. snprintf(parLength, 2, "%d", _params[i]->getValueLength());
  684. pitem.replace("{l}", parLength);
  685. pitem.replace("{v}", _params[i]->getValue());
  686. pitem.replace("{c}", _params[i]->getCustomHTML());
  687. } else {
  688. pitem = _params[i]->getCustomHTML();
  689. }
  690. page += pitem;
  691. }
  692. if (_params[0] != NULL) {
  693. page += "<br/>";
  694. }
  695. if (_sta_static_ip) {
  696. String item = FPSTR(HTTP_FORM_PARAM);
  697. item.replace("{i}", "ip");
  698. item.replace("{n}", "ip");
  699. item.replace("{p}", "Static IP");
  700. item.replace("{l}", "15");
  701. item.replace("{v}", _sta_static_ip.toString());
  702. page += item;
  703. item = FPSTR(HTTP_FORM_PARAM);
  704. item.replace("{i}", "gw");
  705. item.replace("{n}", "gw");
  706. item.replace("{p}", "Static Gateway");
  707. item.replace("{l}", "15");
  708. item.replace("{v}", _sta_static_gw.toString());
  709. page += item;
  710. item = FPSTR(HTTP_FORM_PARAM);
  711. item.replace("{i}", "sn");
  712. item.replace("{n}", "sn");
  713. item.replace("{p}", "Subnet");
  714. item.replace("{l}", "15");
  715. item.replace("{v}", _sta_static_sn.toString());
  716. page += item;
  717. item = FPSTR(HTTP_FORM_PARAM);
  718. item.replace("{i}", "dns1");
  719. item.replace("{n}", "dns1");
  720. item.replace("{p}", "DNS1");
  721. item.replace("{l}", "15");
  722. item.replace("{v}", _sta_static_dns1.toString());
  723. page += item;
  724. item = FPSTR(HTTP_FORM_PARAM);
  725. item.replace("{i}", "dns2");
  726. item.replace("{n}", "dns2");
  727. item.replace("{p}", "DNS2");
  728. item.replace("{l}", "15");
  729. item.replace("{v}", _sta_static_dns2.toString());
  730. page += item;
  731. page += "<br/>";
  732. }
  733. page += FPSTR(HTTP_FORM_END);
  734. page += FPSTR(HTTP_SCAN_LINK);
  735. page += FPSTR(HTTP_END);
  736. request->send(200, "text/html", page);
  737. DEBUG_WM(F("Sent config page"));
  738. }
  739. /** Handle the WLAN save form and redirect to WLAN config page again */
  740. void AsyncWiFiManager::handleWifiSave(AsyncWebServerRequest *request) {
  741. DEBUG_WM(F("WiFi save"));
  742. //SAVE/connect here
  743. needInfo = true;
  744. _ssid = request->arg("s").c_str();
  745. _pass = request->arg("p").c_str();
  746. //parameters
  747. for (int i = 0; i < _paramsCount; i++) {
  748. if (_params[i] == NULL) {
  749. break;
  750. }
  751. //read parameter
  752. String value = request->arg(_params[i]->getID()).c_str();
  753. //store it in array
  754. value.toCharArray(_params[i]->_value, _params[i]->_length);
  755. DEBUG_WM(F("Parameter"));
  756. DEBUG_WM(_params[i]->getID());
  757. DEBUG_WM(value);
  758. }
  759. if (request->hasArg("ip")) {
  760. DEBUG_WM(F("static ip"));
  761. DEBUG_WM(request->arg("ip"));
  762. //_sta_static_ip.fromString(request->arg("ip"));
  763. String ip = request->arg("ip");
  764. optionalIPFromString(&_sta_static_ip, ip.c_str());
  765. }
  766. if (request->hasArg("gw")) {
  767. DEBUG_WM(F("static gateway"));
  768. DEBUG_WM(request->arg("gw"));
  769. String gw = request->arg("gw");
  770. optionalIPFromString(&_sta_static_gw, gw.c_str());
  771. }
  772. if (request->hasArg("sn")) {
  773. DEBUG_WM(F("static netmask"));
  774. DEBUG_WM(request->arg("sn"));
  775. String sn = request->arg("sn");
  776. optionalIPFromString(&_sta_static_sn, sn.c_str());
  777. }
  778. if (request->hasArg("dns1")) {
  779. DEBUG_WM(F("static DNS 1"));
  780. DEBUG_WM(request->arg("dns1"));
  781. String dns1 = request->arg("dns1");
  782. optionalIPFromString(&_sta_static_dns1, dns1.c_str());
  783. }
  784. if (request->hasArg("dns2")) {
  785. DEBUG_WM(F("static DNS 2"));
  786. DEBUG_WM(request->arg("dns2"));
  787. String dns2 = request->arg("dns2");
  788. optionalIPFromString(&_sta_static_dns2, dns2.c_str());
  789. }
  790. String page = FPSTR(WFM_HTTP_HEAD);
  791. page.replace("{v}", "Credentials Saved");
  792. page += FPSTR(HTTP_SCRIPT);
  793. page += FPSTR(HTTP_STYLE);
  794. page += _customHeadElement;
  795. page += F("<meta http-equiv=\"refresh\" content=\"5; url=/i\">");
  796. page += FPSTR(HTTP_HEAD_END);
  797. page += FPSTR(HTTP_SAVED);
  798. page += FPSTR(HTTP_END);
  799. request->send(200, "text/html", page);
  800. DEBUG_WM(F("Sent wifi save page"));
  801. connect = true; //signal ready to connect/reset
  802. }
  803. /** Handle the info page */
  804. String AsyncWiFiManager::infoAsString()
  805. {
  806. String page;
  807. page += F("<dt>Chip ID</dt><dd>");
  808. #if defined(ESP8266)
  809. page += ESP.getChipId();
  810. #else
  811. page += getESP32ChipID();
  812. #endif
  813. page += F("</dd>");
  814. page += F("<dt>Flash Chip ID</dt><dd>");
  815. #if defined(ESP8266)
  816. page += ESP.getFlashChipId();
  817. #else
  818. page += F("N/A for ESP32");
  819. #endif
  820. page += F("</dd>");
  821. page += F("<dt>IDE Flash Size</dt><dd>");
  822. page += ESP.getFlashChipSize();
  823. page += F(" bytes</dd>");
  824. page += F("<dt>Real Flash Size</dt><dd>");
  825. #if defined(ESP8266)
  826. page += ESP.getFlashChipRealSize();
  827. #else
  828. page += F("N/A for ESP32");
  829. #endif
  830. page += F(" bytes</dd>");
  831. page += F("<dt>Soft AP IP</dt><dd>");
  832. page += WiFi.softAPIP().toString();
  833. page += F("</dd>");
  834. page += F("<dt>Soft AP MAC</dt><dd>");
  835. page += WiFi.softAPmacAddress();
  836. page += F("</dd>");
  837. page += F("<dt>Station SSID</dt><dd>");
  838. page += WiFi.SSID();
  839. page += F("</dd>");
  840. page += F("<dt>Station IP</dt><dd>");
  841. page += WiFi.localIP().toString();
  842. page += F("</dd>");
  843. page += F("<dt>Station MAC</dt><dd>");
  844. page += WiFi.macAddress();
  845. page += F("</dd>");
  846. page += F("</dl>");
  847. return page;
  848. }
  849. void AsyncWiFiManager::handleInfo(AsyncWebServerRequest *request) {
  850. DEBUG_WM(F("Info"));
  851. String page = FPSTR(WFM_HTTP_HEAD);
  852. page.replace("{v}", "Info");
  853. page += FPSTR(HTTP_SCRIPT);
  854. page += FPSTR(HTTP_STYLE);
  855. page += _customHeadElement;
  856. if (connect==true)
  857. page += F("<meta http-equiv=\"refresh\" content=\"5; url=/i\">");
  858. page += FPSTR(HTTP_HEAD_END);
  859. page += F("<dl>");
  860. if (connect==true)
  861. {
  862. page += F("<dt>Trying to connect</dt><dd>");
  863. page += wifiStatus;
  864. page += F("</dd>");
  865. }
  866. page +=pager;
  867. page += FPSTR(HTTP_END);
  868. request->send(200, "text/html", page);
  869. DEBUG_WM(F("Sent info page"));
  870. }
  871. /** Handle the reset page */
  872. void AsyncWiFiManager::handleReset(AsyncWebServerRequest *request) {
  873. DEBUG_WM(F("Reset"));
  874. String page = FPSTR(WFM_HTTP_HEAD);
  875. page.replace("{v}", "Info");
  876. page += FPSTR(HTTP_SCRIPT);
  877. page += FPSTR(HTTP_STYLE);
  878. page += _customHeadElement;
  879. page += FPSTR(HTTP_HEAD_END);
  880. page += F("Module will reset in a few seconds.");
  881. page += FPSTR(HTTP_END);
  882. request->send(200, "text/html", page);
  883. DEBUG_WM(F("Sent reset page"));
  884. delay(5000);
  885. #if defined(ESP8266)
  886. ESP.reset();
  887. #else
  888. ESP.restart();
  889. #endif
  890. delay(2000);
  891. }
  892. //removed as mentioned here https://github.com/tzapu/AsyncWiFiManager/issues/114
  893. /*void AsyncWiFiManager::handle204(AsyncWebServerRequest *request) {
  894. DEBUG_WM(F("204 No Response"));
  895. request->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  896. request->sendHeader("Pragma", "no-cache");
  897. request->sendHeader("Expires", "-1");
  898. request->send ( 204, "text/plain", "");
  899. }*/
  900. void AsyncWiFiManager::handleNotFound(AsyncWebServerRequest *request) {
  901. if (captivePortal(request)) { // If captive portal redirect instead of displaying the error page.
  902. return;
  903. }
  904. String message = "File Not Found\n\n";
  905. message += "URI: ";
  906. message += request->url();
  907. message += "\nMethod: ";
  908. message += ( request->method() == HTTP_GET ) ? "GET" : "POST";
  909. message += "\nArguments: ";
  910. message += request->args();
  911. message += "\n";
  912. for ( uint8_t i = 0; i < request->args(); i++ ) {
  913. message += " " + request->argName ( i ) + ": " + request->arg ( i ) + "\n";
  914. }
  915. AsyncWebServerResponse *response = request->beginResponse(404,"text/plain",message);
  916. response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  917. response->addHeader("Pragma", "no-cache");
  918. response->addHeader("Expires", "-1");
  919. request->send (response );
  920. }
  921. /** 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. */
  922. boolean AsyncWiFiManager::captivePortal(AsyncWebServerRequest *request) {
  923. if (!isIp(request->host()) ) {
  924. DEBUG_WM(F("Request redirected to captive portal"));
  925. AsyncWebServerResponse *response = request->beginResponse(302,"text/plain","");
  926. response->addHeader("Location", String("http://") + toStringIp(request->client()->localIP()));
  927. request->send ( response);
  928. return true;
  929. }
  930. return false;
  931. }
  932. //start up config portal callback
  933. void AsyncWiFiManager::setAPCallback( void (*func)(AsyncWiFiManager* myAsyncWiFiManager) ) {
  934. _apcallback = func;
  935. }
  936. //start up save config callback
  937. void AsyncWiFiManager::setSaveConfigCallback( void (*func)(void) ) {
  938. _savecallback = func;
  939. }
  940. //sets a custom element to add to head, like a new style tag
  941. void AsyncWiFiManager::setCustomHeadElement(const char* element) {
  942. _customHeadElement = element;
  943. }
  944. //if this is true, remove duplicated Access Points - defaut true
  945. void AsyncWiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) {
  946. _removeDuplicateAPs = removeDuplicates;
  947. }
  948. template <typename Generic>
  949. void AsyncWiFiManager::DEBUG_WM(Generic text) {
  950. if (_debug) {
  951. Serial.print("*WM: ");
  952. Serial.println(text);
  953. }
  954. }
  955. int AsyncWiFiManager::getRSSIasQuality(int RSSI) {
  956. int quality = 0;
  957. if (RSSI <= -100) {
  958. quality = 0;
  959. } else if (RSSI >= -50) {
  960. quality = 100;
  961. } else {
  962. quality = 2 * (RSSI + 100);
  963. }
  964. return quality;
  965. }
  966. /** Is this an IP? */
  967. boolean AsyncWiFiManager::isIp(String str) {
  968. for (int i = 0; i < str.length(); i++) {
  969. int c = str.charAt(i);
  970. if (c != '.' && (c < '0' || c > '9')) {
  971. return false;
  972. }
  973. }
  974. return true;
  975. }
  976. /** IP to String? */
  977. String AsyncWiFiManager::toStringIp(IPAddress ip) {
  978. String res = "";
  979. for (int i = 0; i < 3; i++) {
  980. res += String((ip >> (8 * i)) & 0xFF) + ".";
  981. }
  982. res += String(((ip >> 8 * 3)) & 0xFF);
  983. return res;
  984. }