ESPAsyncWiFiManager.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. if (_tryWPS && connRes != WL_CONNECTED && pass == "") {
  466. startWPS();
  467. //should be connected at the end of WPS
  468. connRes = waitForConnectResult();
  469. }
  470. needInfo = true;
  471. setInfo();
  472. return connRes;
  473. }
  474. uint8_t AsyncWiFiManager::waitForConnectResult() {
  475. if (_connectTimeout == 0) {
  476. return WiFi.waitForConnectResult();
  477. } else {
  478. DEBUG_WM (F("Waiting for connection result with time out"));
  479. unsigned long start = millis();
  480. boolean keepConnecting = true;
  481. uint8_t status;
  482. while (keepConnecting) {
  483. status = WiFi.status();
  484. if (millis() > start + _connectTimeout) {
  485. keepConnecting = false;
  486. DEBUG_WM (F("Connection timed out"));
  487. }
  488. if (status == WL_CONNECTED || status == WL_CONNECT_FAILED) {
  489. keepConnecting = false;
  490. }
  491. delay(100);
  492. }
  493. return status;
  494. }
  495. }
  496. void AsyncWiFiManager::startWPS() {
  497. DEBUG_WM("START WPS");
  498. #if defined(ESP8266)
  499. WiFi.beginWPSConfig();
  500. #else
  501. esp_wps_config_t config = WPS_CONFIG_INIT_DEFAULT(ESP_WPS_MODE);
  502. esp_wifi_wps_enable(&config);
  503. esp_wifi_wps_start(0);
  504. #endif
  505. DEBUG_WM("END WPS");
  506. }
  507. /*
  508. String AsyncWiFiManager::getSSID() {
  509. if (_ssid == "") {
  510. DEBUG_WM(F("Reading SSID"));
  511. _ssid = WiFi.SSID();
  512. DEBUG_WM(F("SSID: "));
  513. DEBUG_WM(_ssid);
  514. }
  515. return _ssid;
  516. }
  517. String AsyncWiFiManager::getPassword() {
  518. if (_pass == "") {
  519. DEBUG_WM(F("Reading Password"));
  520. _pass = WiFi.psk();
  521. DEBUG_WM("Password: " + _pass);
  522. //DEBUG_WM(_pass);
  523. }
  524. return _pass;
  525. }
  526. */
  527. String AsyncWiFiManager::getConfigPortalSSID() {
  528. return _apName;
  529. }
  530. void AsyncWiFiManager::resetSettings() {
  531. DEBUG_WM(F("settings invalidated"));
  532. DEBUG_WM(F("THIS MAY CAUSE AP NOT TO START UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA."));
  533. WiFi.disconnect(true);
  534. //delay(200);
  535. }
  536. void AsyncWiFiManager::setTimeout(unsigned long seconds) {
  537. setConfigPortalTimeout(seconds);
  538. }
  539. void AsyncWiFiManager::setConfigPortalTimeout(unsigned long seconds) {
  540. _configPortalTimeout = seconds * 1000;
  541. }
  542. void AsyncWiFiManager::setConnectTimeout(unsigned long seconds) {
  543. _connectTimeout = seconds * 1000;
  544. }
  545. void AsyncWiFiManager::setDebugOutput(boolean debug) {
  546. _debug = debug;
  547. }
  548. void AsyncWiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) {
  549. _ap_static_ip = ip;
  550. _ap_static_gw = gw;
  551. _ap_static_sn = sn;
  552. }
  553. void AsyncWiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) {
  554. _sta_static_ip = ip;
  555. _sta_static_gw = gw;
  556. _sta_static_sn = sn;
  557. }
  558. void AsyncWiFiManager::setMinimumSignalQuality(int quality) {
  559. _minimumQuality = quality;
  560. }
  561. void AsyncWiFiManager::setBreakAfterConfig(boolean shouldBreak) {
  562. _shouldBreakAfterConfig = shouldBreak;
  563. }
  564. /** Handle root or redirect to captive portal */
  565. void AsyncWiFiManager::handleRoot(AsyncWebServerRequest *request) {
  566. // AJS - maybe we should set a scan when we get to the root???
  567. // and only scan on demand? timer + on demand? plus a link to make it happen?
  568. shouldscan=true;
  569. scannow= -1 ;
  570. DEBUG_WM(F("Handle root"));
  571. if (captivePortal(request)) { // If captive portal redirect instead of displaying the page.
  572. return;
  573. }
  574. String page = FPSTR(WFM_HTTP_HEAD);
  575. page.replace("{v}", "Options");
  576. page += FPSTR(HTTP_SCRIPT);
  577. page += FPSTR(HTTP_STYLE);
  578. page += _customHeadElement;
  579. page += FPSTR(HTTP_HEAD_END);
  580. page += "<h1>";
  581. page += _apName;
  582. page += "</h1>";
  583. page += F("<h3>AsyncWiFiManager</h3>");
  584. page += FPSTR(HTTP_PORTAL_OPTIONS);
  585. page += FPSTR(HTTP_END);
  586. request->send(200, "text/html", page);
  587. }
  588. /** Wifi config page handler */
  589. void AsyncWiFiManager::handleWifi(AsyncWebServerRequest *request,boolean scan) {
  590. shouldscan=true;
  591. scannow= -1 ;
  592. String page = FPSTR(WFM_HTTP_HEAD);
  593. page.replace("{v}", "Config ESP");
  594. page += FPSTR(HTTP_SCRIPT);
  595. page += FPSTR(HTTP_STYLE);
  596. page += _customHeadElement;
  597. page += FPSTR(HTTP_HEAD_END);
  598. if (scan) {
  599. wifiSSIDscan=false;
  600. DEBUG_WM(F("Scan done"));
  601. if (wifiSSIDCount==0) {
  602. DEBUG_WM(F("No networks found"));
  603. page += F("No networks found. Refresh to scan again.");
  604. } else {
  605. //display networks in page
  606. String pager = networkListAsString();
  607. page += pager;
  608. page += "<br/>";
  609. }
  610. }
  611. wifiSSIDscan=true;
  612. page += FPSTR(HTTP_FORM_START);
  613. char parLength[2];
  614. // add the extra parameters to the form
  615. for (int i = 0; i < _paramsCount; i++) {
  616. if (_params[i] == NULL) {
  617. break;
  618. }
  619. String pitem = FPSTR(HTTP_FORM_PARAM);
  620. if (_params[i]->getID() != NULL) {
  621. pitem.replace("{i}", _params[i]->getID());
  622. pitem.replace("{n}", _params[i]->getID());
  623. pitem.replace("{p}", _params[i]->getPlaceholder());
  624. snprintf(parLength, 2, "%d", _params[i]->getValueLength());
  625. pitem.replace("{l}", parLength);
  626. pitem.replace("{v}", _params[i]->getValue());
  627. pitem.replace("{c}", _params[i]->getCustomHTML());
  628. } else {
  629. pitem = _params[i]->getCustomHTML();
  630. }
  631. page += pitem;
  632. }
  633. if (_params[0] != NULL) {
  634. page += "<br/>";
  635. }
  636. if (_sta_static_ip) {
  637. String item = FPSTR(HTTP_FORM_PARAM);
  638. item.replace("{i}", "ip");
  639. item.replace("{n}", "ip");
  640. item.replace("{p}", "Static IP");
  641. item.replace("{l}", "15");
  642. item.replace("{v}", _sta_static_ip.toString());
  643. page += item;
  644. item = FPSTR(HTTP_FORM_PARAM);
  645. item.replace("{i}", "gw");
  646. item.replace("{n}", "gw");
  647. item.replace("{p}", "Static Gateway");
  648. item.replace("{l}", "15");
  649. item.replace("{v}", _sta_static_gw.toString());
  650. page += item;
  651. item = FPSTR(HTTP_FORM_PARAM);
  652. item.replace("{i}", "sn");
  653. item.replace("{n}", "sn");
  654. item.replace("{p}", "Subnet");
  655. item.replace("{l}", "15");
  656. item.replace("{v}", _sta_static_sn.toString());
  657. page += item;
  658. page += "<br/>";
  659. }
  660. page += FPSTR(HTTP_FORM_END);
  661. page += FPSTR(HTTP_SCAN_LINK);
  662. page += FPSTR(HTTP_END);
  663. request->send(200, "text/html", page);
  664. DEBUG_WM(F("Sent config page"));
  665. }
  666. /** Handle the WLAN save form and redirect to WLAN config page again */
  667. void AsyncWiFiManager::handleWifiSave(AsyncWebServerRequest *request) {
  668. DEBUG_WM(F("WiFi save"));
  669. //SAVE/connect here
  670. needInfo = true;
  671. _ssid = request->arg("s").c_str();
  672. _pass = request->arg("p").c_str();
  673. //parameters
  674. for (int i = 0; i < _paramsCount; i++) {
  675. if (_params[i] == NULL) {
  676. break;
  677. }
  678. //read parameter
  679. String value = request->arg(_params[i]->getID()).c_str();
  680. //store it in array
  681. value.toCharArray(_params[i]->_value, _params[i]->_length);
  682. DEBUG_WM(F("Parameter"));
  683. DEBUG_WM(_params[i]->getID());
  684. DEBUG_WM(value);
  685. }
  686. if (request->hasArg("ip")) {
  687. DEBUG_WM(F("static ip"));
  688. DEBUG_WM(request->arg("ip"));
  689. //_sta_static_ip.fromString(request->arg("ip"));
  690. String ip = request->arg("ip");
  691. optionalIPFromString(&_sta_static_ip, ip.c_str());
  692. }
  693. if (request->hasArg("gw")) {
  694. DEBUG_WM(F("static gateway"));
  695. DEBUG_WM(request->arg("gw"));
  696. String gw = request->arg("gw");
  697. optionalIPFromString(&_sta_static_gw, gw.c_str());
  698. }
  699. if (request->hasArg("sn")) {
  700. DEBUG_WM(F("static netmask"));
  701. DEBUG_WM(request->arg("sn"));
  702. String sn = request->arg("sn");
  703. optionalIPFromString(&_sta_static_sn, sn.c_str());
  704. }
  705. String page = FPSTR(WFM_HTTP_HEAD);
  706. page.replace("{v}", "Credentials Saved");
  707. page += FPSTR(HTTP_SCRIPT);
  708. page += FPSTR(HTTP_STYLE);
  709. page += _customHeadElement;
  710. page += F("<meta http-equiv=\"refresh\" content=\"5; url=/i\">");
  711. page += FPSTR(HTTP_HEAD_END);
  712. page += FPSTR(HTTP_SAVED);
  713. page += FPSTR(HTTP_END);
  714. request->send(200, "text/html", page);
  715. DEBUG_WM(F("Sent wifi save page"));
  716. connect = true; //signal ready to connect/reset
  717. }
  718. /** Handle the info page */
  719. String AsyncWiFiManager::infoAsString()
  720. {
  721. String page;
  722. page += F("<dt>Chip ID</dt><dd>");
  723. #if defined(ESP8266)
  724. page += ESP.getChipId();
  725. #else
  726. page += getESP32ChipID();
  727. #endif
  728. page += F("</dd>");
  729. page += F("<dt>Flash Chip ID</dt><dd>");
  730. #if defined(ESP8266)
  731. page += ESP.getFlashChipId();
  732. #else
  733. page += F("N/A for ESP32");
  734. #endif
  735. page += F("</dd>");
  736. page += F("<dt>IDE Flash Size</dt><dd>");
  737. page += ESP.getFlashChipSize();
  738. page += F(" bytes</dd>");
  739. page += F("<dt>Real Flash Size</dt><dd>");
  740. #if defined(ESP8266)
  741. page += ESP.getFlashChipRealSize();
  742. #else
  743. page += F("N/A for ESP32");
  744. #endif
  745. page += F(" bytes</dd>");
  746. page += F("<dt>Soft AP IP</dt><dd>");
  747. page += WiFi.softAPIP().toString();
  748. page += F("</dd>");
  749. page += F("<dt>Soft AP MAC</dt><dd>");
  750. page += WiFi.softAPmacAddress();
  751. page += F("</dd>");
  752. page += F("<dt>Station SSID</dt><dd>");
  753. page += WiFi.SSID();
  754. page += F("</dd>");
  755. page += F("<dt>Station IP</dt><dd>");
  756. page += WiFi.localIP().toString();
  757. page += F("</dd>");
  758. page += F("<dt>Station MAC</dt><dd>");
  759. page += WiFi.macAddress();
  760. page += F("</dd>");
  761. page += F("</dl>");
  762. return page;
  763. }
  764. void AsyncWiFiManager::handleInfo(AsyncWebServerRequest *request) {
  765. DEBUG_WM(F("Info"));
  766. String page = FPSTR(WFM_HTTP_HEAD);
  767. page.replace("{v}", "Info");
  768. page += FPSTR(HTTP_SCRIPT);
  769. page += FPSTR(HTTP_STYLE);
  770. page += _customHeadElement;
  771. if (connect==true)
  772. page += F("<meta http-equiv=\"refresh\" content=\"5; url=/i\">");
  773. page += FPSTR(HTTP_HEAD_END);
  774. page += F("<dl>");
  775. if (connect==true)
  776. {
  777. page += F("<dt>Trying to connect</dt><dd>");
  778. page += wifiStatus;
  779. page += F("</dd>");
  780. }
  781. page +=pager;
  782. page += FPSTR(HTTP_END);
  783. request->send(200, "text/html", page);
  784. DEBUG_WM(F("Sent info page"));
  785. }
  786. /** Handle the reset page */
  787. void AsyncWiFiManager::handleReset(AsyncWebServerRequest *request) {
  788. DEBUG_WM(F("Reset"));
  789. String page = FPSTR(WFM_HTTP_HEAD);
  790. page.replace("{v}", "Info");
  791. page += FPSTR(HTTP_SCRIPT);
  792. page += FPSTR(HTTP_STYLE);
  793. page += _customHeadElement;
  794. page += FPSTR(HTTP_HEAD_END);
  795. page += F("Module will reset in a few seconds.");
  796. page += FPSTR(HTTP_END);
  797. request->send(200, "text/html", page);
  798. DEBUG_WM(F("Sent reset page"));
  799. delay(5000);
  800. #if defined(ESP8266)
  801. ESP.reset();
  802. #else
  803. ESP.restart();
  804. #endif
  805. delay(2000);
  806. }
  807. //removed as mentioned here https://github.com/tzapu/AsyncWiFiManager/issues/114
  808. /*void AsyncWiFiManager::handle204(AsyncWebServerRequest *request) {
  809. DEBUG_WM(F("204 No Response"));
  810. request->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  811. request->sendHeader("Pragma", "no-cache");
  812. request->sendHeader("Expires", "-1");
  813. request->send ( 204, "text/plain", "");
  814. }*/
  815. void AsyncWiFiManager::handleNotFound(AsyncWebServerRequest *request) {
  816. if (captivePortal(request)) { // If captive portal redirect instead of displaying the error page.
  817. return;
  818. }
  819. String message = "File Not Found\n\n";
  820. message += "URI: ";
  821. message += request->url();
  822. message += "\nMethod: ";
  823. message += ( request->method() == HTTP_GET ) ? "GET" : "POST";
  824. message += "\nArguments: ";
  825. message += request->args();
  826. message += "\n";
  827. for ( uint8_t i = 0; i < request->args(); i++ ) {
  828. message += " " + request->argName ( i ) + ": " + request->arg ( i ) + "\n";
  829. }
  830. AsyncWebServerResponse *response = request->beginResponse(404,"text/plain",message);
  831. response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  832. response->addHeader("Pragma", "no-cache");
  833. response->addHeader("Expires", "-1");
  834. request->send (response );
  835. }
  836. /** 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. */
  837. boolean AsyncWiFiManager::captivePortal(AsyncWebServerRequest *request) {
  838. if (!isIp(request->host()) ) {
  839. DEBUG_WM(F("Request redirected to captive portal"));
  840. AsyncWebServerResponse *response = request->beginResponse(302,"text/plain","");
  841. response->addHeader("Location", String("http://") + toStringIp(request->client()->localIP()));
  842. request->send ( response);
  843. return true;
  844. }
  845. return false;
  846. }
  847. //start up config portal callback
  848. void AsyncWiFiManager::setAPCallback( void (*func)(AsyncWiFiManager* myAsyncWiFiManager) ) {
  849. _apcallback = func;
  850. }
  851. //start up save config callback
  852. void AsyncWiFiManager::setSaveConfigCallback( void (*func)(void) ) {
  853. _savecallback = func;
  854. }
  855. //sets a custom element to add to head, like a new style tag
  856. void AsyncWiFiManager::setCustomHeadElement(const char* element) {
  857. _customHeadElement = element;
  858. }
  859. //if this is true, remove duplicated Access Points - defaut true
  860. void AsyncWiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) {
  861. _removeDuplicateAPs = removeDuplicates;
  862. }
  863. template <typename Generic>
  864. void AsyncWiFiManager::DEBUG_WM(Generic text) {
  865. if (_debug) {
  866. Serial.print("*WM: ");
  867. Serial.println(text);
  868. }
  869. }
  870. int AsyncWiFiManager::getRSSIasQuality(int RSSI) {
  871. int quality = 0;
  872. if (RSSI <= -100) {
  873. quality = 0;
  874. } else if (RSSI >= -50) {
  875. quality = 100;
  876. } else {
  877. quality = 2 * (RSSI + 100);
  878. }
  879. return quality;
  880. }
  881. /** Is this an IP? */
  882. boolean AsyncWiFiManager::isIp(String str) {
  883. for (int i = 0; i < str.length(); i++) {
  884. int c = str.charAt(i);
  885. if (c != '.' && (c < '0' || c > '9')) {
  886. return false;
  887. }
  888. }
  889. return true;
  890. }
  891. /** IP to String? */
  892. String AsyncWiFiManager::toStringIp(IPAddress ip) {
  893. String res = "";
  894. for (int i = 0; i < 3; i++) {
  895. res += String((ip >> (8 * i)) & 0xFF) + ".";
  896. }
  897. res += String(((ip >> 8 * 3)) & 0xFF);
  898. return res;
  899. }