ESPAsyncWiFiManager.cpp 32 KB

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