ESPAsyncWiFiManager.cpp 28 KB

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