ESPAsyncWiFiManager.cpp 28 KB

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