PersWiFiManager.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /* PersWiFiManager
  2. version 3.0.1
  3. https://r-downing.github.io/PersWiFiManager/
  4. */
  5. #include "PersWiFiManager.h"
  6. #if defined(ESP32)
  7. #include <esp_wifi.h>
  8. #endif
  9. #ifdef WIFI_HTM_PROGMEM
  10. const char wifi_htm[] PROGMEM = R"=====(
  11. <!DOCTYPE html>
  12. <html>
  13. <head>
  14. <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
  15. <title>ESP WiFi</title>
  16. <script>
  17. function g(i){
  18. return document.getElementById(i);
  19. };
  20. function p(t,l){
  21. if(confirm(t)) window.location=l;
  22. };
  23. function E(s){
  24. return document.createElement(s)
  25. };
  26. var S="setAttribute",A="appendChild",H="innerHTML",X,wl;
  27. function scan(){
  28. if(X) return;
  29. X=new XMLHttpRequest(),wl=document.getElementById('wl');
  30. wl[H]="Scanning...";
  31. X.onreadystatechange=function(){
  32. if (this.readyState==4&&this.status==200){
  33. X=0;wl[H]="";
  34. this.responseText.split("\n").forEach(function (e){
  35. let t=e.split(","), s=t.slice(2).join(',');
  36. var d=E('div'),i=E('a'),c=E('a');
  37. i[S]('class','s');
  38. c[S]('class','q');
  39. i.onclick=function(){
  40. g('s').value=s;
  41. g('p').focus();
  42. };
  43. i[A](document.createTextNode(s));
  44. c[H]=t[0]+"%"+(parseInt(t[1])?"\uD83D\uDD12":"\u26A0");
  45. wl[A](i);
  46. wl[A](c);
  47. wl[A](document.createElement('br'));
  48. });
  49. }
  50. };
  51. X.open("GET","wifi/list",true);
  52. X.send();
  53. };
  54. </script>
  55. <style>
  56. input{
  57. padding:5px;font-size:1em;width:95%;
  58. }
  59. body{
  60. text-align:center;font-family:verdana;background-color:black;color:white;
  61. }
  62. a{
  63. color:#1fa3ec;
  64. }
  65. button{
  66. border:0;border-radius:0.3em;background-color:#1fa3ec;color:#fff;
  67. line-height:2.4em;font-size:1.2em;width:100%;display:block;
  68. }
  69. .q{
  70. float:right;
  71. }
  72. .s{
  73. display:inline-block;width:14em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
  74. }
  75. #wl{
  76. line-height:1.5em;
  77. }
  78. </style>
  79. </head>
  80. <body>
  81. <div style='text-align:left;display:inline-block;width:320px;padding:5px'>
  82. <button onclick="scan()">&#x21bb; Scan</button>
  83. <p id='wl'></p>
  84. <form method='post' action='/wifi/connect'>
  85. <input id='s' name='n' length=32 placeholder='SSID'>
  86. <br>
  87. <input id='p' name='p' length=64 type='password' placeholder='password'>
  88. <br><br>
  89. <button type='submit'>Connect</button>
  90. </form>
  91. <br><br>
  92. <button onclick="p('Reboot device?','/wifi/rst')">Reboot</button>
  93. <br>
  94. <a href="javascript:history.back()">Back</a> |<a href="/">Home</a>
  95. </div>
  96. </body>
  97. </html>
  98. )=====";
  99. #endif
  100. #if defined(ESP8266)
  101. PersWiFiManager::PersWiFiManager(ESP8266WebServer& s, DNSServer& d) {
  102. #elif defined(ESP32)
  103. PersWiFiManager::PersWiFiManager(WebServer& s, DNSServer& d) {
  104. #endif
  105. _server = &s;
  106. _dnsServer = &d;
  107. _apPass = "";
  108. _freshConnectionAttempt = false;
  109. } //PersWiFiManager
  110. bool PersWiFiManager::attemptConnection(const String& ssid, const String& pass) {
  111. //attempt to connect to wifi
  112. WiFi.mode(WIFI_STA);
  113. if (ssid.length()) {
  114. resetSettings(); // To avoid issues (experience from WiFiManager)
  115. if (pass.length()) WiFi.begin(ssid.c_str(), pass.c_str());
  116. else WiFi.begin(ssid.c_str());
  117. } else {
  118. if((getSsid() == "") && (WiFi.status() != WL_CONNECTED)) { // No saved credentials, so skip trying to connect
  119. _connectStartTime = millis();
  120. _freshConnectionAttempt = true;
  121. return false;
  122. } else {
  123. WiFi.begin();
  124. }
  125. }
  126. //if in nonblock mode, skip this loop
  127. _connectStartTime = millis();// + 1;
  128. while (!_connectNonBlock && _connectStartTime) {
  129. handleWiFi();
  130. delay(10);
  131. }
  132. return (WiFi.status() == WL_CONNECTED);
  133. } //attemptConnection
  134. void PersWiFiManager::handleWiFi() {
  135. if (!_connectStartTime) return;
  136. if (WiFi.status() == WL_CONNECTED) {
  137. _connectStartTime = 0;
  138. if (_connectHandler) _connectHandler();
  139. return;
  140. }
  141. //if failed or no saved SSID or no WiFi credentials were found or not connected and time is up
  142. if ((WiFi.status() == WL_CONNECT_FAILED) || _freshConnectionAttempt || ((WiFi.status() != WL_CONNECTED) && ((millis() - _connectStartTime) > (1000 * WIFI_CONNECT_TIMEOUT)))) {
  143. startApMode();
  144. _connectStartTime = 0; //reset connect start time
  145. _freshConnectionAttempt = false;
  146. }
  147. } //handleWiFi
  148. void PersWiFiManager::startApMode(){
  149. //start AP mode
  150. IPAddress apIP(192, 168, 4, 1);
  151. WiFi.mode(WIFI_AP);
  152. WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  153. _apPass.length() ? WiFi.softAP(getApSsid().c_str(), _apPass.c_str()) : WiFi.softAP(getApSsid().c_str());
  154. if (_apHandler) _apHandler();
  155. }//startApMode
  156. void PersWiFiManager::setConnectNonBlock(bool b) {
  157. _connectNonBlock = b;
  158. } //setConnectNonBlock
  159. void PersWiFiManager::setupWiFiHandlers() {
  160. IPAddress apIP(192, 168, 4, 1);
  161. _dnsServer->setErrorReplyCode(DNSReplyCode::NoError);
  162. _dnsServer->start((byte)53, "*", apIP); //used for captive portal in AP mode
  163. _server->on("/wifi/list", [&] () {
  164. //scan for wifi networks
  165. int n = WiFi.scanNetworks();
  166. //build array of indices
  167. int ix[n];
  168. for (int i = 0; i < n; i++) ix[i] = i;
  169. //sort by signal strength
  170. 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]);
  171. //remove duplicates
  172. 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;
  173. //build plain text string of wifi info
  174. //format [signal%]:[encrypted 0 or 1]:SSID
  175. String s = "";
  176. s.reserve(2050);
  177. for (int i = 0; i < n && s.length() < 2000; i++) { //check s.length to limit memory usage
  178. if (ix[i] != -1) {
  179. #if defined(ESP8266)
  180. s += String(i ? "\n" : "") + ((constrain(WiFi.RSSI(ix[i]), -100, -50) + 100) * 2) + ","
  181. + ((WiFi.encryptionType(ix[i]) == ENC_TYPE_NONE) ? 0 : 1) + "," + WiFi.SSID(ix[i]);
  182. #elif defined(ESP32)
  183. s += String(i ? "\n" : "") + ((constrain(WiFi.RSSI(ix[i]), -100, -50) + 100) * 2) + ","
  184. + ((WiFi.encryptionType(ix[i]) == WIFI_AUTH_OPEN) ? 0 : 1) + "," + WiFi.SSID(ix[i]);
  185. #endif
  186. }
  187. }
  188. //send string to client
  189. _server->send(200, "text/plain", s);
  190. }); //_server->on /wifi/list
  191. _server->on("/wifi/connect", [&]() {
  192. _server->send(200, "text/html", "connecting...");
  193. attemptConnection(_server->arg("n"), _server->arg("p"));
  194. }); //_server->on /wifi/connect
  195. _server->on("/wifi/ap", [&](){
  196. _server->send(200, "text/html", "access point: "+getApSsid());
  197. startApMode();
  198. }); //_server->on /wifi/ap
  199. _server->on("/wifi/rst", [&]() {
  200. _server->send(200, "text/html", "Rebooting...");
  201. delay(100);
  202. //ESP.restart();
  203. // Adding Safer Restart method
  204. #if defined(ESP8266)
  205. ESP.wdtDisable();
  206. ESP.reset();
  207. #elif defined(ESP32)
  208. ESP.restart();
  209. #endif
  210. delay(2000);
  211. });
  212. #ifdef WIFI_HTM_PROGMEM
  213. _server->on("/wifi.htm", [&]() {
  214. _server->sendHeader("Cache-Control", " no-cache, no-store, must-revalidate");
  215. _server->sendHeader("Expires", " 0");
  216. _server->send(200, "text/html", wifi_htm);
  217. });
  218. #endif
  219. }//setupWiFiHandlers
  220. bool PersWiFiManager::begin(const String& ssid, const String& pass) {
  221. #if defined(ESP32)
  222. WiFi.mode(WIFI_STA); // ESP32 needs this before setupWiFiHandlers(). Might be good for ESP8266 too?
  223. #endif
  224. setupWiFiHandlers();
  225. return attemptConnection(ssid, pass); //switched order of these two for return
  226. } //begin
  227. void PersWiFiManager::resetSettings() {
  228. #if defined(ESP8266)
  229. WiFi.disconnect();
  230. #elif defined(ESP32)
  231. wifi_mode_t m = WiFi.getMode();
  232. if(!(m & WIFI_MODE_STA)) WiFi.mode(WIFI_STA);
  233. WiFi.disconnect(false, true);
  234. if(!(m & WIFI_MODE_STA)) WiFi.mode(m);
  235. #endif
  236. } // resetSettings
  237. String PersWiFiManager::getApSsid() {
  238. #if defined(ESP8266)
  239. return _apSsid.length() ? _apSsid : "ESP8266";
  240. #elif defined(ESP32)
  241. return _apSsid.length() ? _apSsid : "ESP32";
  242. #endif
  243. } //getApSsid
  244. String PersWiFiManager::getSsid() {
  245. #if defined(ESP8266)
  246. return WiFi.SSID();
  247. #elif defined(ESP32)
  248. wifi_config_t conf;
  249. esp_wifi_get_config(WIFI_IF_STA, &conf); // load wifi settings to struct comf
  250. const char *SSID = reinterpret_cast<const char*>(conf.sta.ssid);
  251. return String(SSID);
  252. #endif
  253. } //getSsid
  254. void PersWiFiManager::setApCredentials(const String& apSsid, const String& apPass) {
  255. if (apSsid.length()) _apSsid = apSsid;
  256. if (apPass.length() >= 8) _apPass = apPass;
  257. } //setApCredentials
  258. void PersWiFiManager::onConnect(WiFiChangeHandlerFunction fn) {
  259. _connectHandler = fn;
  260. }
  261. void PersWiFiManager::onAp(WiFiChangeHandlerFunction fn) {
  262. _apHandler = fn;
  263. }