ESPAsyncWiFiManager.cpp 30 KB

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