ESPAsyncWiFiManager.cpp 27 KB

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