ESPAsyncWiFiManager.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /**************************************************************
  2. WiFiManager 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. #ifndef ESPAsyncWiFiManager_h
  14. #define ESPAsyncWiFiManager_h
  15. #if defined(ESP8266)
  16. #include <ESP8266WiFi.h> // https://github.com/esp8266/Arduino
  17. #else
  18. #include <WiFi.h>
  19. #include "esp_wps.h"
  20. #define ESP_WPS_MODE WPS_TYPE_PBC
  21. #endif
  22. #include <ESPAsyncWebServer.h>
  23. //#define USE_EADNS // uncomment to use ESPAsyncDNSServer
  24. #ifdef USE_EADNS
  25. #include <ESPAsyncDNSServer.h> // https://github.com/devyte/ESPAsyncDNSServer
  26. // https://github.com/me-no-dev/ESPAsyncUDP
  27. #else
  28. #include <DNSServer.h>
  29. #endif
  30. #include <memory>
  31. // fix crash on ESP32 (see https://github.com/alanswx/ESPAsyncWiFiManager/issues/44)
  32. #if defined(ESP8266)
  33. typedef int wifi_ssid_count_t;
  34. #else
  35. typedef int16_t wifi_ssid_count_t;
  36. #endif
  37. #if defined(ESP8266)
  38. extern "C"
  39. {
  40. #include "user_interface.h"
  41. }
  42. #else
  43. #include <rom/rtc.h>
  44. #endif
  45. const char WFM_HTTP_HEAD[] PROGMEM = "<!DOCTYPE html><html lang=\"en\"><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/><title>{v}</title>";
  46. const char HTTP_STYLE[] PROGMEM = "<style>.c{text-align: center;} div,input{padding:5px;font-size:1em;} input{width:95%;} body{text-align: center;font-family:verdana;} button{border:0;border-radius:0.3rem;background-color:#1fa3ec;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;} .q{float: right;width: 64px;text-align: right;} .l{background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAALVBMVEX///8EBwfBwsLw8PAzNjaCg4NTVVUjJiZDRUUUFxdiZGSho6OSk5Pg4eFydHTCjaf3AAAAZElEQVQ4je2NSw7AIAhEBamKn97/uMXEGBvozkWb9C2Zx4xzWykBhFAeYp9gkLyZE0zIMno9n4g19hmdY39scwqVkOXaxph0ZCXQcqxSpgQpONa59wkRDOL93eAXvimwlbPbwwVAegLS1HGfZAAAAABJRU5ErkJggg==\") no-repeat left center;background-size: 1em;}</style>";
  47. const char HTTP_SCRIPT[] PROGMEM = "<script>function c(l){document.getElementById('s').value=l.innerText||l.textContent;document.getElementById('p').focus();}</script>";
  48. const char HTTP_HEAD_END[] PROGMEM = "</head><body><div style='text-align:left;display:inline-block;min-width:260px;'>";
  49. const char HTTP_PORTAL_OPTIONS[] PROGMEM = "<form action=\"/wifi\" method=\"get\"><button>Configure WiFi</button></form><br/><form action=\"/0wifi\" method=\"get\"><button>Configure WiFi (No Scan)</button></form><br/><form action=\"/i\" method=\"get\"><button>Info</button></form><br/><form action=\"/r\" method=\"post\"><button>Reset</button></form>";
  50. const char HTTP_ITEM[] PROGMEM = "<div><a href='#p' onclick='c(this)'>{v}</a>&nbsp;<span class='q {i}'>{r}%</span></div>";
  51. const char HTTP_FORM_START[] PROGMEM = "<form method='get' action='wifisave'><input id='s' name='s' length=32 placeholder='SSID'><br/><input id='p' name='p' length=64 type='password' placeholder='password'><br/>";
  52. const char HTTP_FORM_PARAM[] PROGMEM = "<br/><input id='{i}' name='{n}' length={l} placeholder='{p}' value='{v}' {c}>";
  53. const char HTTP_FORM_END[] PROGMEM = "<br/><button type='submit'>save</button></form>";
  54. const char HTTP_SCAN_LINK[] PROGMEM = "<br/><div class=\"c\"><a href=\"/wifi\">Scan</a></div>";
  55. const char HTTP_SAVED[] PROGMEM = "<div>Credentials Saved<br />Trying to connect ESP to network.<br />If it fails reconnect to AP to try again</div>";
  56. const char HTTP_END[] PROGMEM = "</div></body></html>";
  57. #define WIFI_MANAGER_MAX_PARAMS 10
  58. class AsyncWiFiManagerParameter
  59. {
  60. public:
  61. AsyncWiFiManagerParameter(const char *custom);
  62. AsyncWiFiManagerParameter(const char *id,
  63. const char *placeholder,
  64. const char *defaultValue,
  65. unsigned int length);
  66. AsyncWiFiManagerParameter(const char *id,
  67. const char *placeholder,
  68. const char *defaultValue,
  69. unsigned int length,
  70. const char *custom);
  71. const char *getID();
  72. const char *getValue();
  73. const char *getPlaceholder();
  74. unsigned int getValueLength();
  75. const char *getCustomHTML();
  76. private:
  77. const char *_id;
  78. const char *_placeholder;
  79. char *_value;
  80. unsigned int _length;
  81. const char *_customHTML;
  82. void init(const char *id,
  83. const char *placeholder,
  84. const char *defaultValue,
  85. unsigned int length,
  86. const char *custom);
  87. friend class AsyncWiFiManager;
  88. };
  89. class WiFiResult
  90. {
  91. public:
  92. bool duplicate;
  93. String SSID;
  94. uint8_t encryptionType;
  95. int32_t RSSI;
  96. uint8_t *BSSID;
  97. int32_t channel;
  98. bool isHidden;
  99. WiFiResult()
  100. {
  101. }
  102. };
  103. class AsyncWiFiManager
  104. {
  105. public:
  106. #ifdef USE_EADNS
  107. AsyncWiFiManager(AsyncWebServer *server, AsyncDNSServer *dns);
  108. #else
  109. AsyncWiFiManager(AsyncWebServer *server, DNSServer *dns);
  110. #endif
  111. void scan(boolean async = false);
  112. String scanModal();
  113. void loop();
  114. void safeLoop();
  115. void criticalLoop();
  116. String infoAsString();
  117. boolean autoConnect(unsigned long maxConnectRetries = 1,
  118. unsigned long retryDelayMs = 1000);
  119. boolean autoConnect(char const *apName,
  120. char const *apPassword = NULL,
  121. unsigned long maxConnectRetries = 1,
  122. unsigned long retryDelayMs = 1000);
  123. // if you want to always start the config portal, without trying to connect first
  124. boolean startConfigPortal(char const *apName, char const *apPassword = NULL);
  125. void startConfigPortalModeless(char const *apName, char const *apPassword);
  126. // get the AP name of the config portal, so it can be used in the callback
  127. String getConfigPortalSSID();
  128. void resetSettings();
  129. // sets timeout before webserver loop ends and exits even if there has been no setup.
  130. // usefully for devices that failed to connect at some point and got stuck in a webserver loop.
  131. // in seconds, setConfigPortalTimeout is a new name for setTimeout
  132. void setConfigPortalTimeout(unsigned long seconds);
  133. void setTimeout(unsigned long seconds);
  134. // sets timeout for which to attempt connecting, usefull if you get a lot of failed connects
  135. void setConnectTimeout(unsigned long seconds);
  136. // wether or not the wifi manager tries to connect to configured access point even when
  137. // configuration portal (ESP as access point) is running [default true/on]
  138. void setTryConnectDuringConfigPortal(boolean v);
  139. void setDebugOutput(boolean debug);
  140. // defaults to not showing anything under 8% signal quality if called
  141. void setMinimumSignalQuality(unsigned int quality = 8);
  142. // sets a custom ip /gateway /subnet configuration
  143. void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn);
  144. // sets config for a static IP
  145. void setSTAStaticIPConfig(IPAddress ip,
  146. IPAddress gw,
  147. IPAddress sn,
  148. IPAddress dns1 = (uint32_t)0x00000000,
  149. IPAddress dns2 = (uint32_t)0x00000000);
  150. // called when AP mode and config portal is started
  151. void setAPCallback(std::function<void(AsyncWiFiManager *)>);
  152. // called when settings have been changed and connection was successful
  153. void setSaveConfigCallback(std::function<void()> func);
  154. void setConnectCallback(std::function<void()> func);
  155. void setDisconnectCallback(std::function<void()> func);
  156. //adds a custom parameter
  157. void addParameter(AsyncWiFiManagerParameter *p);
  158. // if this is set, it will exit after config, even if connection is unsucessful
  159. void setBreakAfterConfig(boolean shouldBreak);
  160. // if this is set, try WPS setup when starting (this will delay config portal for up to 2 mins)
  161. // TODO
  162. // if this is set, customise style
  163. void setCustomHeadElement(const char *element);
  164. // if this is true, remove duplicated Access Points - defaut true
  165. void setRemoveDuplicateAPs(boolean removeDuplicates);
  166. // sets a custom element to add to options page
  167. void setCustomOptionsElement(const char *element);
  168. String getConfiguredSTASSID(){
  169. return _ssid;
  170. }
  171. String getConfiguredSTAPassword(){
  172. return _pass;
  173. }
  174. void handleWifi(AsyncWebServerRequest *, boolean scan);
  175. void handleWifiSave(AsyncWebServerRequest *);
  176. void setupConfig();
  177. private:
  178. AsyncWebServer *server;
  179. #ifdef USE_EADNS
  180. AsyncDNSServer *dnsServer;
  181. #else
  182. DNSServer *dnsServer;
  183. #endif
  184. boolean _modeless;
  185. unsigned long scannow;
  186. boolean shouldscan = true;
  187. boolean needInfo = true;
  188. //const int WM_DONE = 0;
  189. //const int WM_WAIT = 10;
  190. //const String HTTP_HEAD = "<!DOCTYPE html><html lang=\"en\"><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/><title>{v}</title>";
  191. void setupConfigPortal();
  192. #ifdef NO_EXTRA_4K_HEAP
  193. void startWPS();
  194. #endif
  195. String pager;
  196. wl_status_t wifiStatus;
  197. const char *_apName = "no-net";
  198. const char *_apPassword = NULL;
  199. String _ssid = "";
  200. String _pass = "";
  201. unsigned long _configPortalTimeout = 0;
  202. unsigned long _connectTimeout = 0;
  203. unsigned long _configPortalStart = 0;
  204. IPAddress _ap_static_ip;
  205. IPAddress _ap_static_gw;
  206. IPAddress _ap_static_sn;
  207. IPAddress _sta_static_ip;
  208. IPAddress _sta_static_gw;
  209. IPAddress _sta_static_sn;
  210. IPAddress _sta_static_dns1 = (uint32_t)0x00000000;
  211. IPAddress _sta_static_dns2 = (uint32_t)0x00000000;
  212. unsigned int _paramsCount = 0;
  213. unsigned int _minimumQuality = 0;
  214. boolean _removeDuplicateAPs = true;
  215. boolean _shouldBreakAfterConfig = false;
  216. #ifdef NO_EXTRA_4K_HEAP
  217. boolean _tryWPS = false;
  218. #endif
  219. const char *_customHeadElement = "";
  220. const char *_customOptionsElement = "";
  221. //String getEEPROMString(int start, int len);
  222. //void setEEPROMString(int start, int len, String string);
  223. uint8_t status = WL_IDLE_STATUS;
  224. uint8_t connectWifi(String ssid, String pass);
  225. uint8_t waitForConnectResult();
  226. void setInfo();
  227. void copySSIDInfo(wifi_ssid_count_t n);
  228. String networkListAsString();
  229. void handleRoot(AsyncWebServerRequest *);
  230. void handleInfo(AsyncWebServerRequest *);
  231. void handleReset(AsyncWebServerRequest *);
  232. void handleNotFound(AsyncWebServerRequest *);
  233. boolean captivePortal(AsyncWebServerRequest *);
  234. // DNS server
  235. const byte DNS_PORT = 53;
  236. // helpers
  237. unsigned int getRSSIasQuality(int RSSI);
  238. boolean isIp(String str);
  239. String toStringIp(IPAddress ip);
  240. boolean connect;
  241. boolean _debug = false;
  242. WiFiResult *wifiSSIDs;
  243. wifi_ssid_count_t wifiSSIDCount;
  244. boolean wifiSSIDscan;
  245. boolean _tryConnectDuringConfigPortal = true;
  246. std::function<void(AsyncWiFiManager *)> _apcallback;
  247. std::function<void()> _savecallback;
  248. std::function<void()> _connectcallback;
  249. std::function<void()> _disconnectcallback;
  250. AsyncWiFiManagerParameter *_params[WIFI_MANAGER_MAX_PARAMS];
  251. template <typename Generic>
  252. void DEBUG_WM(Generic text);
  253. template <class T>
  254. auto optionalIPFromString(T *obj, const char *s) -> decltype(obj->fromString(s))
  255. {
  256. return obj->fromString(s);
  257. }
  258. auto optionalIPFromString(...) -> bool
  259. {
  260. DEBUG_WM(F("NO fromString METHOD ON IPAddress, you need ESP8266 core 2.1.0 or newer for Custom IP configuration to work."));
  261. return false;
  262. }
  263. };
  264. #endif