ESPAsyncWiFiManager.cpp 32 KB

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