ESPAsyncWiFiManager.cpp 29 KB

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