ESPAsyncWiFiManager.cpp 32 KB

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