PersWiFiManagerExt.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. /* PersWiFiManagerExt
  2. v1.0.0
  3. Based on PersWiFiManager v5.0.0 from https://r-downing.github.io/PersWiFiManager/
  4. Extended by Flo Kra
  5. */
  6. #include "PersWiFiManagerExt.h"
  7. #if defined(ESP32)
  8. #include <esp_wifi.h>
  9. #endif
  10. #ifdef WIFI_HTM_PROGMEM
  11. const char wifi_htm[] PROGMEM = R"=====(
  12. <!DOCTYPE html>
  13. <html>
  14. <head>
  15. <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
  16. <title>ESP WiFi</title>
  17. <script>
  18. function g(i){
  19. return document.getElementById(i);
  20. };
  21. function p(t,l){
  22. if(confirm(t)) window.location=l;
  23. };
  24. function E(s){
  25. return document.createElement(s)
  26. };
  27. var S="setAttribute",A="appendChild",H="innerHTML",X,wl;
  28. function scan(){
  29. if(X) return;
  30. X=new XMLHttpRequest(),wl=document.getElementById('wl');
  31. wl[H]="Scanning...";
  32. X.onreadystatechange=function(){
  33. if (this.readyState==4&&this.status==200){
  34. X=0;wl[H]="";
  35. this.responseText.split("\n").forEach(function (e){
  36. let t=e.split(","), s=t.slice(2).join(',');
  37. var d=E('div'),i=E('a'),c=E('a');
  38. i[S]('class','s');
  39. c[S]('class','q');
  40. i.onclick=function(){
  41. g('s').value=s;
  42. g('p').focus();
  43. };
  44. i[A](document.createTextNode(s));
  45. c[H]=t[0]+"%"+(parseInt(t[1])?"\uD83D\uDD12":"\u26A0");
  46. wl[A](i);
  47. wl[A](c);
  48. wl[A](document.createElement('br'));
  49. });
  50. }
  51. };
  52. X.open("GET","wifi/list",true);
  53. X.send();
  54. };
  55. </script>
  56. <style>
  57. input{
  58. padding:5px;font-size:1em;width:95%;
  59. }
  60. body{
  61. text-align:center;font-family:verdana;background-color:black;color:white;
  62. }
  63. a{
  64. color:#1fa3ec;
  65. }
  66. button{
  67. border:0;border-radius:0.3em;background-color:#1fa3ec;color:#fff;
  68. line-height:2.4em;font-size:1.2em;width:100%;display:block;
  69. }
  70. .q{
  71. float:right;
  72. }
  73. .s{
  74. display:inline-block;width:14em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
  75. }
  76. #wl{
  77. line-height:1.5em;
  78. }
  79. </style>
  80. </head>
  81. <body>
  82. <div style='text-align:left;display:inline-block;width:320px;padding:5px'>
  83. <button onclick="scan()">&#x21bb; Scan</button>
  84. <p id='wl'></p>
  85. <form method='post' action='/wifi/connect'>
  86. <input id='s' name='n' length=32 placeholder='SSID'>
  87. <br>
  88. <input id='p' name='p' length=64 type='password' placeholder='password'>
  89. <br><br>
  90. <button type='submit'>Connect</button>
  91. </form>
  92. <br><br>
  93. <button onclick="p('Reboot device?','/wifi/rst')">Reboot</button>
  94. <br>
  95. <a href="javascript:history.back()">Back</a> |<a href="/">Home</a>
  96. </div>
  97. </body>
  98. </html>
  99. )=====";
  100. #endif
  101. #if defined(ESP8266)
  102. PersWiFiManager::PersWiFiManager(ESP8266WebServer& s, DNSServer& d) {
  103. #elif defined(ESP32)
  104. PersWiFiManager::PersWiFiManager(WebServer& s, DNSServer& d) {
  105. #endif
  106. _server = &s;
  107. _dnsServer = &d;
  108. _apPass = "";
  109. _freshConnectionAttempt = false;
  110. _w1Ssid = "";
  111. _w1Pass = "";
  112. _w2Ssid = "";
  113. _w2Pass = "";
  114. _httpUser = "";
  115. _httpPass = "";
  116. _connectNonBlock = true;
  117. _apStartTime = 0;
  118. _useSetWifi1Credentials = false;
  119. _useSetWifi2Credentials = false;
  120. _wifi1ConnectAttempts = 0;
  121. _wifi2ConnectAttempts = 0;
  122. _connectSetWifi = 0;
  123. _apModeFinished = false;
  124. _lastSuccessfulConnect = 0;
  125. _forceRetryWifi1LastTime = 0;
  126. _apTimeout = WIFI_AP_TIMEOUT;
  127. _apStartAfter = WIFI_CONNECT_TIMEOUT_STARTAP;
  128. _connCheckInterval = WIFI_CONNCHECK_INTERVAL;
  129. _rebootOnNoConnectAfter = WIFI_REBOOT_ON_NO_CONNECT_AFTER;
  130. _forceRetryWifi1Interval = WIFI_FORCE_RETRY_WIFI1_INTERVAL;
  131. _lastRunHandleWifi = 0;
  132. _lastConnectionCheckOK = 0;
  133. _wifiDisconnectedCounter = 0;
  134. _apModeEnabled = true;
  135. _httpAuth = false;
  136. } //PersWiFiManager
  137. bool PersWiFiManager::attemptConnection(const String& ssid, const String& pass) {
  138. //attempt to connect to wifi
  139. WiFi.mode(WIFI_STA);
  140. if (ssid.length()) {
  141. resetSettings(); // To avoid issues (experience from WiFiManager)
  142. if (pass.length()) WiFi.begin(ssid.c_str(), pass.c_str());
  143. else WiFi.begin(ssid.c_str());
  144. _connectStartTime = millis();
  145. } else {
  146. if((getSsid() == "") && (WiFi.status() != WL_CONNECTED)) { // No saved credentials from last connection, so skip trying to connect
  147. if(!_useSetWifi1Credentials && !_useSetWifi2Credentials) {
  148. _connectStartTime = millis();
  149. _freshConnectionAttempt = true;
  150. #ifdef DEBUG
  151. Serial.println("WiFi: no saved credentials");
  152. #endif
  153. return false;
  154. }
  155. } else {
  156. if(!_useSetWifi1Credentials && !_useSetWifi2Credentials) {
  157. // if no credentials were set using setWifi1Credentials/setWifi2Credentials
  158. // use saved credentials from last successful connection
  159. WiFi.begin();
  160. _connectStartTime = millis();
  161. #ifdef DEBUG
  162. Serial.println("WiFi: try connect using saved credentials");
  163. #endif
  164. }
  165. }
  166. }
  167. // if Wifi credentials were set using setWifi[x]Credentials method - use them
  168. if (_useSetWifi1Credentials || _useSetWifi2Credentials) {
  169. if (!_w1Ssid.length() && !_w2Ssid.length()) {
  170. #ifdef DEBUG
  171. Serial.println("WiFi: ERROR - both SSIDs empty");
  172. #endif
  173. // both configured WiFis have an empty SSID - no WiFi configured, directly switch to AP mode
  174. _freshConnectionAttempt = true;
  175. _connectStartTime = millis();
  176. }
  177. else {
  178. if(_useSetWifi1Credentials && (_wifi1ConnectAttempts < SETWIFI_CONNECT_TRIES)) {
  179. _wifi1ConnectAttempts++;
  180. _connectSetWifi = 1;
  181. #ifdef DEBUG
  182. Serial.print("WiFi: trying WiFi-1... attempt: "); Serial.println(_wifi1ConnectAttempts);
  183. #endif
  184. resetSettings();
  185. delay(10);
  186. if (_w1Pass.length()) {
  187. //Serial.println("WiFi.begin(_w1Ssid.c_str(), _w1Pass.c_str());");
  188. WiFi.begin(_w1Ssid.c_str(), _w1Pass.c_str());
  189. }
  190. else {
  191. //Serial.println("WiFi.begin(_w1Ssid.c_str());");
  192. WiFi.begin(_w1Ssid.c_str());
  193. }
  194. _connectStartTime = millis();
  195. }
  196. else if(_useSetWifi2Credentials && (_wifi2ConnectAttempts < SETWIFI_CONNECT_TRIES)) {
  197. _wifi2ConnectAttempts++;
  198. _connectSetWifi = 2;
  199. #ifdef DEBUG
  200. Serial.print("WiFi: trying WiFi-2... attempt: "); Serial.println(_wifi2ConnectAttempts);
  201. #endif
  202. resetSettings();
  203. delay(10);
  204. if (_w2Pass.length()) {
  205. //Serial.println("WiFi.begin(_w2Ssid.c_str(), _w2Pass.c_str());");
  206. WiFi.begin(_w2Ssid.c_str(), _w2Pass.c_str());
  207. }
  208. else {
  209. //Serial.println("WiFi.begin(_w2Ssid.c_str());");
  210. WiFi.begin(_w2Ssid.c_str());
  211. }
  212. _connectStartTime = millis();
  213. }
  214. }
  215. }
  216. //if in nonblock mode, skip this loop
  217. while (!_connectNonBlock && _connectStartTime) {
  218. handleWiFi();
  219. delay(10);
  220. }
  221. return (WiFi.status() == WL_CONNECTED);
  222. } //attemptConnection
  223. void PersWiFiManager::handleWiFi() {
  224. if (_connectStartTime && WiFi.status() == WL_CONNECTED) {
  225. _connectStartTime = 0;
  226. _apModeFinished = true; // connection was successful - disable AP until reboot
  227. _lastSuccessfulConnect = millis();
  228. #ifdef DEBUG
  229. if(_connectSetWifi > 0) Serial.print("WiFi: connected to WiFi-"); Serial.println(_connectSetWifi);
  230. #endif
  231. if(_connectSetWifi == 1) _wifi1ConnectAttempts = 0;
  232. if(_connectSetWifi == 2) _wifi2ConnectAttempts = 0;
  233. if (_connectHandler) _connectHandler();
  234. }
  235. //if failed or not connected and time is up - try connecting again (only if currently using setWifi1/setWifi2, to possibly be successful with the 2nd config set)
  236. if(_useSetWifi1Credentials || _useSetWifi2Credentials ) {
  237. if ((_connectStartTime && (WiFi.status() == WL_CONNECT_FAILED)) || (_connectStartTime && (WiFi.status() != WL_CONNECTED) && ((millis() - _connectStartTime) > (1000 * WIFI_CONNECT_TIMEOUT)))) {
  238. attemptConnection();
  239. }
  240. }
  241. //start AP mode
  242. //if connect failed or no saved SSID or no WiFi credentials were found or not connected and time is up
  243. if(_apModeEnabled && !_apModeFinished && _connectStartTime) {
  244. if ((WiFi.status() == WL_CONNECT_FAILED) || _freshConnectionAttempt || ((WiFi.status() != WL_CONNECTED) && ((millis() - _connectStartTime) > (1000 * _apStartAfter)))) {
  245. startApMode();
  246. _connectStartTime = 0; //reset connect start time
  247. _apStartTime = millis();
  248. _freshConnectionAttempt = false;
  249. }
  250. }
  251. // if AP is on and AP timeout exceeded, switch off AP mode and start normal connection handling again
  252. if ( _apModeEnabled && _apTimeout > 0 && !_apModeFinished && _apStartTime && ((millis() - _apStartTime) > (60000 * _apTimeout))) {
  253. if (WiFi.softAPgetStationNum() > 0) {
  254. // there are active connections - extend AP timeout
  255. _apStartTime = millis();
  256. }
  257. else { // no one is connected and timeout exceeded - stop AP
  258. stopApMode();
  259. _apModeFinished = true; // prevent AP again until reboot
  260. _apStartTime = 0;
  261. }
  262. }
  263. // run if WIFI_CONNCHECK_INTERVAL exceeded
  264. // try reconnect if not connected
  265. if( _connCheckInterval > 0 && (millis() - _lastRunHandleWifi) > (1000 * _connCheckInterval)) {
  266. _lastRunHandleWifi = millis();
  267. int currWifiState = WiFi.status();
  268. #ifdef DEBUG_2
  269. Serial.print("WiFi: status: ");
  270. Serial.print(currWifiState);
  271. Serial.print(" _connectStartTime: ");
  272. Serial.print(_connectStartTime);
  273. Serial.print(" _lastSuccessfulConnect: ");
  274. Serial.print(_lastSuccessfulConnect);
  275. Serial.print(" _apStartTime: ");
  276. Serial.print(_apStartTime);
  277. Serial.print(" _apModeFinished: ");
  278. Serial.println(_apModeFinished);
  279. #endif
  280. #ifdef DEBUG
  281. if(currWifiState != _wifiLastState) {
  282. Serial.print("WiFi: status changed to: ");
  283. //Serial.println(currWifiState);
  284. if(currWifiState == WL_IDLE_STATUS) Serial.println(F("WL_IDLE_STATUS"));
  285. else if(currWifiState == WL_NO_SSID_AVAIL) Serial.println(F("WL_NO_SSID_AVAIL"));
  286. else if(currWifiState == WL_CONNECTED) Serial.println(F("WL_CONNECTED"));
  287. else if(currWifiState == WL_CONNECT_FAILED) Serial.println(F("WL_CONNECT_FAILED"));
  288. else if(currWifiState == WL_DISCONNECTED) Serial.println(F("WL_DISCONNECTED"));
  289. }
  290. #endif
  291. if(currWifiState == WL_CONNECTED) _lastConnectionCheckOK = millis();
  292. // if enabled and connected to Wifi2 and _forceRetryWifi1Interval is exceeded
  293. // try reconnecting in order to prefer Wifi1 when set and available
  294. if(_forceRetryWifi1Interval && _apStartTime == 0) {
  295. if(_useSetWifi1Credentials && _connectSetWifi != 1 && _apModeFinished && _w1Ssid.length() && ((millis() - _lastSuccessfulConnect) > (60000 * _forceRetryWifi1Interval))) {
  296. if((millis() - _forceRetryWifi1LastTime) > 120000) {
  297. #ifdef DEBUG
  298. Serial.println("WiFi: connected to WiFi-2 - attempt reconnect WiFi-1");
  299. #endif
  300. _forceRetryWifi1LastTime = millis();
  301. _wifi1ConnectAttempts = 0;
  302. _wifi2ConnectAttempts = 0;
  303. attemptConnection();
  304. }
  305. }
  306. }
  307. // after AP mode is turned off, reconnect connection if it drops
  308. if(_apModeFinished && _apStartTime == 0 && currWifiState != WL_CONNECTED && _wifiLastState != WL_CONNECTED) {
  309. if( _wifiDisconnectedCounter > 2) {
  310. #ifdef DEBUG
  311. Serial.println("WiFi: not connected - attempt reconnect");
  312. #endif
  313. _wifi1ConnectAttempts = 0;
  314. _wifi2ConnectAttempts = 0;
  315. _wifiDisconnectedCounter = 0;
  316. attemptConnection();
  317. }
  318. else {
  319. #ifdef DEBUG_2
  320. Serial.print("WiFi: not connected - _wifiDisconnectedCounter=");
  321. Serial.print(_wifiDisconnectedCounter);
  322. Serial.println(" - _wifiDisconnectedCounter++");
  323. #endif
  324. _wifiDisconnectedCounter++;
  325. }
  326. }
  327. if(_rebootOnNoConnectAfter > 0 && ((millis() - _lastConnectionCheckOK) > (60000 * _rebootOnNoConnectAfter))) {
  328. #ifdef DEBUG
  329. Serial.println("WiFi: could not connect for a long time - rebooting...");
  330. #endif
  331. delay(100);
  332. //ESP.restart();
  333. // Adding Safer Restart method
  334. #if defined(ESP8266)
  335. ESP.wdtDisable();
  336. ESP.reset();
  337. #elif defined(ESP32)
  338. ESP.restart();
  339. #endif
  340. delay(2000);
  341. }
  342. if(currWifiState != _wifiLastState) {
  343. _wifiLastState = currWifiState;
  344. }
  345. }
  346. } //handleWiFi
  347. void PersWiFiManager::startApMode(){
  348. //start AP mode
  349. IPAddress apIP(192, 168, 4, 1);
  350. WiFi.mode(WIFI_AP);
  351. WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  352. _apPass.length() ? WiFi.softAP(getApSsid().c_str(), _apPass.c_str()) : WiFi.softAP(getApSsid().c_str());
  353. #ifdef DEBUG
  354. Serial.print("WiFi: AP mode started, SSID: '");
  355. Serial.print(getApSsid().c_str());
  356. Serial.print("', PW: '");
  357. Serial.print(_apPass.c_str());
  358. Serial.println("'");
  359. #endif
  360. if (_apHandler) _apHandler();
  361. }//startApMode
  362. void PersWiFiManager::stopApMode() {
  363. #ifdef DEBUG
  364. Serial.println("WiFi: AP mode stopped");
  365. #endif
  366. WiFi.softAPdisconnect(true);
  367. delay(10);
  368. attemptConnection(); // sets WiFi mode to STA and begins reconnecting
  369. }
  370. void PersWiFiManager::setConnectNonBlock(bool b) {
  371. _connectNonBlock = b;
  372. } //setConnectNonBlock
  373. void PersWiFiManager::setApModeAutostart(bool m) {
  374. _apModeEnabled = m;
  375. }
  376. void PersWiFiManager::setApTimeout(int t) {
  377. _apTimeout = t;
  378. } //setApTimeout
  379. void PersWiFiManager::setApStartAfter(int t) {
  380. _apStartAfter = t;
  381. }
  382. void PersWiFiManager::setConnCheckInterval(int t) {
  383. _connCheckInterval = t;
  384. }
  385. void PersWiFiManager::setForceRetryWifi1Interval(int t) {
  386. _forceRetryWifi1Interval = t;
  387. }
  388. void PersWiFiManager::setupWiFiHandlers() {
  389. IPAddress apIP(192, 168, 4, 1);
  390. _dnsServer->setErrorReplyCode(DNSReplyCode::NoError);
  391. _dnsServer->start((byte)53, "*", apIP); //used for captive portal in AP mode
  392. _server->on("/wifi/list", [&] () {
  393. bool requestOk = false;
  394. if(_httpAuth) {
  395. if (_server->authenticate(_httpUser.c_str(), _httpPass.c_str())) requestOk = true;
  396. else _server->send (401, "text/plain", "UNAUTHORIZED");
  397. }
  398. else requestOk = true;
  399. if(requestOk) {
  400. //scan for wifi networks
  401. int n = WiFi.scanNetworks();
  402. //build array of indices
  403. int ix[n];
  404. for (int i = 0; i < n; i++) ix[i] = i;
  405. //sort by signal strength
  406. for (int i = 0; i < n; i++) for (int j = 1; j < n - i; j++) if (WiFi.RSSI(ix[j]) > WiFi.RSSI(ix[j - 1])) std::swap(ix[j], ix[j - 1]);
  407. //remove duplicates
  408. for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (WiFi.SSID(ix[i]).equals(WiFi.SSID(ix[j])) && WiFi.encryptionType(ix[i]) == WiFi.encryptionType(ix[j])) ix[j] = -1;
  409. //build plain text string of wifi info
  410. //format [signal%]:[encrypted 0 or 1]:SSID
  411. String s = "";
  412. s.reserve(2050);
  413. for (int i = 0; i < n && s.length() < 2000; i++) { //check s.length to limit memory usage
  414. if (ix[i] != -1) {
  415. #if defined(ESP8266)
  416. s += String(i ? "\n" : "") + ((constrain(WiFi.RSSI(ix[i]), -100, -50) + 100) * 2) + ","
  417. + ((WiFi.encryptionType(ix[i]) == ENC_TYPE_NONE) ? 0 : 1) + "," + WiFi.SSID(ix[i]);
  418. #elif defined(ESP32)
  419. s += String(i ? "\n" : "") + ((constrain(WiFi.RSSI(ix[i]), -100, -50) + 100) * 2) + ","
  420. + ((WiFi.encryptionType(ix[i]) == WIFI_AUTH_OPEN) ? 0 : 1) + "," + WiFi.SSID(ix[i]);
  421. #endif
  422. }
  423. }
  424. //send string to client
  425. _server->send(200, "text/plain", s);
  426. }
  427. }); //_server->on /wifi/list
  428. _server->on("/wifi/connect", [&]() {
  429. bool requestOk = false;
  430. if(_httpAuth) {
  431. if (_server->authenticate(_httpUser.c_str(), _httpPass.c_str())) requestOk = true;
  432. else _server->send (401, "text/plain", "UNAUTHORIZED");
  433. }
  434. else requestOk = true;
  435. if(requestOk) {
  436. _server->send(200, "text/html", "connecting...");
  437. attemptConnection(_server->arg("n"), _server->arg("p"));
  438. }
  439. }); //_server->on /wifi/connect
  440. _server->on("/wifi/ap", [&](){
  441. bool requestOk = false;
  442. if(_httpAuth) {
  443. if (_server->authenticate(_httpUser.c_str(), _httpPass.c_str())) requestOk = true;
  444. else _server->send (401, "text/plain", "UNAUTHORIZED");
  445. }
  446. else requestOk = true;
  447. if(requestOk) {
  448. _server->send(200, "text/html", "access point: "+getApSsid());
  449. startApMode();
  450. }
  451. }); //_server->on /wifi/ap
  452. _server->on("/wifi/rst", [&]() {
  453. bool requestOk = false;
  454. if(_httpAuth) {
  455. if (_server->authenticate(_httpUser.c_str(), _httpPass.c_str())) requestOk = true;
  456. else _server->send (401, "text/plain", "UNAUTHORIZED");
  457. }
  458. else requestOk = true;
  459. if(requestOk) {
  460. _server->send(200, "text/html", "Rebooting...");
  461. delay(100);
  462. //ESP.restart();
  463. // Adding Safer Restart method
  464. #if defined(ESP8266)
  465. ESP.wdtDisable();
  466. ESP.reset();
  467. #elif defined(ESP32)
  468. ESP.restart();
  469. #endif
  470. delay(2000);
  471. }
  472. });
  473. #ifdef WIFI_HTM_PROGMEM
  474. _server->on(WIFI_HTM_PATH, [&]() {
  475. bool requestOk = false;
  476. if(_httpAuth) {
  477. if (_server->authenticate(_httpUser.c_str(), _httpPass.c_str())) requestOk = true;
  478. else _server->requestAuthentication();
  479. }
  480. else requestOk = true;
  481. if(requestOk) {
  482. _server->sendHeader("Cache-Control", " no-cache, no-store, must-revalidate");
  483. _server->sendHeader("Expires", " 0");
  484. _server->send(200, "text/html", wifi_htm);
  485. }
  486. });
  487. #endif
  488. }//setupWiFiHandlers
  489. bool PersWiFiManager::begin(const String& ssid, const String& pass) {
  490. #if defined(ESP32)
  491. WiFi.mode(WIFI_STA); // ESP32 needs this before setupWiFiHandlers(). Might be good for ESP8266 too?
  492. #endif
  493. setupWiFiHandlers();
  494. return attemptConnection(ssid, pass); //switched order of these two for return
  495. } //begin
  496. void PersWiFiManager::resetSettings() {
  497. #if defined(ESP8266)
  498. WiFi.disconnect();
  499. #elif defined(ESP32)
  500. wifi_mode_t m = WiFi.getMode();
  501. if(!(m & WIFI_MODE_STA)) WiFi.mode(WIFI_STA);
  502. WiFi.disconnect(false, true);
  503. if(!(m & WIFI_MODE_STA)) WiFi.mode(m);
  504. #endif
  505. } // resetSettings
  506. String PersWiFiManager::getApSsid() {
  507. #if defined(ESP8266)
  508. return _apSsid.length() ? _apSsid : "ESP8266";
  509. #elif defined(ESP32)
  510. return _apSsid.length() ? _apSsid : "ESP32";
  511. #endif
  512. } //getApSsid
  513. String PersWiFiManager::getSsid() {
  514. #if defined(ESP8266)
  515. return WiFi.SSID();
  516. #elif defined(ESP32)
  517. wifi_config_t conf;
  518. esp_wifi_get_config(WIFI_IF_STA, &conf); // load wifi settings to struct comf
  519. const char *SSID = reinterpret_cast<const char*>(conf.sta.ssid);
  520. return String(SSID);
  521. #endif
  522. } //getSsid
  523. void PersWiFiManager::setApCredentials(const String& apSsid, const String& apPass) {
  524. if (apSsid.length()) _apSsid = apSsid;
  525. if (apPass.length() >= 8) _apPass = apPass;
  526. } //setApCredentials
  527. void PersWiFiManager::setWifi1Credentials(const String& wSsid, const String& wPass) {
  528. _useSetWifi1Credentials = true;
  529. //Serial.println("setWifi1Credentials -> _useSetWifi1Credentials=true");
  530. if (wSsid.length()) {
  531. _w1Ssid = wSsid;
  532. }
  533. if (wPass.length()) _w1Pass = wPass;
  534. } //setWifi1Credentials
  535. void PersWiFiManager::setWifi2Credentials(const String& wSsid, const String& wPass) {
  536. _useSetWifi2Credentials = true;
  537. //Serial.println("setWifi2Credentials -> _useSetWifi2Credentials=true");
  538. if (wSsid.length()) {
  539. _w2Ssid = wSsid;
  540. }
  541. if (wPass.length()) _w2Pass = wPass;
  542. } //setWifi2Credentials
  543. void PersWiFiManager::onConnect(WiFiChangeHandlerFunction fn) {
  544. _connectHandler = fn;
  545. }
  546. void PersWiFiManager::onAp(WiFiChangeHandlerFunction fn) {
  547. _apHandler = fn;
  548. }
  549. void PersWiFiManager::onApOff(WiFiChangeHandlerFunction fn) {
  550. _apOffHandler = fn;
  551. }
  552. void PersWiFiManager::setHttpCredentials(const String& user, const String& pass) {
  553. if(user.length() && pass.length()) {
  554. _httpUser = user;
  555. _httpPass = pass;
  556. _httpAuth = true;
  557. }
  558. }
  559. void PersWiFiManager::setRebootOnNoConnect(int t) {
  560. _rebootOnNoConnectAfter = t;
  561. }
  562. int PersWiFiManager::getActiveWiFiNum() {
  563. return _connectSetWifi;
  564. }