ESPAsyncWiFiManager.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. #include "user_interface.h"
  40. }
  41. #else
  42. #include <rom/rtc.h>
  43. #endif
  44. 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>";
  45. 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>";
  46. const char HTTP_SCRIPT[] PROGMEM = "<script>function c(l){document.getElementById('s').value=l.innerText||l.textContent;document.getElementById('p').focus();}</script>";
  47. const char HTTP_HEAD_END[] PROGMEM = "</head><body><div style='text-align:left;display:inline-block;min-width:260px;'>";
  48. 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>";
  49. const char HTTP_ITEM[] PROGMEM = "<div><a href='#p' onclick='c(this)'>{v}</a>&nbsp;<span class='q {i}'>{r}%</span></div>";
  50. 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/>";
  51. const char HTTP_FORM_PARAM[] PROGMEM = "<br/><input id='{i}' name='{n}' length={l} placeholder='{p}' value='{v}' {c}>";
  52. const char HTTP_FORM_END[] PROGMEM = "<br/><button type='submit'>save</button></form>";
  53. const char HTTP_SCAN_LINK[] PROGMEM = "<br/><div class=\"c\"><a href=\"/wifi\">Scan</a></div>";
  54. 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>";
  55. const char HTTP_END[] PROGMEM = "</div></body></html>";
  56. #define WIFI_MANAGER_MAX_PARAMS 10
  57. class AsyncWiFiManagerParameter {
  58. public:
  59. AsyncWiFiManagerParameter(const char *custom);
  60. AsyncWiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length);
  61. AsyncWiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom);
  62. const char *getID();
  63. const char *getValue();
  64. const char *getPlaceholder();
  65. int getValueLength();
  66. const char *getCustomHTML();
  67. private:
  68. const char *_id;
  69. const char *_placeholder;
  70. char *_value;
  71. int _length;
  72. const char *_customHTML;
  73. void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom);
  74. friend class AsyncWiFiManager;
  75. };
  76. class WiFiResult
  77. {
  78. public:
  79. bool duplicate;
  80. String SSID;
  81. uint8_t encryptionType;
  82. int32_t RSSI;
  83. uint8_t* BSSID;
  84. int32_t channel;
  85. bool isHidden;
  86. WiFiResult()
  87. {
  88. }
  89. };
  90. class AsyncWiFiManager
  91. {
  92. public:
  93. #ifdef USE_EADNS
  94. AsyncWiFiManager(AsyncWebServer * server, AsyncDNSServer *dns);
  95. #else
  96. AsyncWiFiManager(AsyncWebServer * server, DNSServer *dns);
  97. #endif
  98. void scan(boolean async = false);
  99. String scanModal();
  100. void loop();
  101. void safeLoop();
  102. void criticalLoop();
  103. String infoAsString();
  104. boolean autoConnect(unsigned long maxConnectRetries = 1, unsigned long retryDelayMs = 1000);
  105. boolean autoConnect(char const *apName, char const *apPassword = NULL, unsigned long maxConnectRetries = 1, unsigned long retryDelayMs = 1000);
  106. //if you want to always start the config portal, without trying to connect first
  107. boolean startConfigPortal(char const *apName, char const *apPassword = NULL);
  108. void startConfigPortalModeless(char const *apName, char const *apPassword);
  109. // get the AP name of the config portal, so it can be used in the callback
  110. String getConfigPortalSSID();
  111. void resetSettings();
  112. //sets timeout before webserver loop ends and exits even if there has been no setup.
  113. //usefully for devices that failed to connect at some point and got stuck in a webserver loop
  114. //in seconds setConfigPortalTimeout is a new name for setTimeout
  115. void setConfigPortalTimeout(unsigned long seconds);
  116. void setTimeout(unsigned long seconds);
  117. //sets timeout for which to attempt connecting, usefull if you get a lot of failed connects
  118. void setConnectTimeout(unsigned long seconds);
  119. //wether or not the wifi manager tries to connect to configured access point even when
  120. //configuration portal (ESP as access point) is running [default true/on]
  121. void setTryConnectDuringConfigPortal(boolean v);
  122. void setDebugOutput(boolean debug);
  123. //defaults to not showing anything under 8% signal quality if called
  124. void setMinimumSignalQuality(int quality = 8);
  125. //sets a custom ip /gateway /subnet configuration
  126. void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn);
  127. //sets config for a static IP
  128. void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns1=(uint32_t)0x00000000, IPAddress dns2=(uint32_t)0x00000000);
  129. //called when AP mode and config portal is started
  130. void setAPCallback( void (*func)(AsyncWiFiManager*) );
  131. //called when settings have been changed and connection was successful
  132. void setSaveConfigCallback( void (*func)(void) );
  133. //adds a custom parameter
  134. void addParameter(AsyncWiFiManagerParameter *p);
  135. //if this is set, it will exit after config, even if connection is unsucessful.
  136. void setBreakAfterConfig(boolean shouldBreak);
  137. //if this is set, try WPS setup when starting (this will delay config portal for up to 2 mins)
  138. //TODO
  139. //if this is set, customise style
  140. void setCustomHeadElement(const char* element);
  141. //if this is true, remove duplicated Access Points - defaut true
  142. void setRemoveDuplicateAPs(boolean removeDuplicates);
  143. //sets a custom element to add to options page
  144. void setCustomOptionsElement(const char* element);
  145. private:
  146. AsyncWebServer *server;
  147. #ifdef USE_EADNS
  148. AsyncDNSServer *dnsServer;
  149. #else
  150. DNSServer *dnsServer;
  151. #endif
  152. boolean _modeless;
  153. unsigned long scannow;
  154. int shouldscan;
  155. boolean needInfo = true;
  156. //const int WM_DONE = 0;
  157. //const int WM_WAIT = 10;
  158. //const String HTTP_HEAD = "<!DOCTYPE html><html lang=\"en\"><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/><title>{v}</title>";
  159. void setupConfigPortal();
  160. #ifdef NO_EXTRA_4K_HEAP
  161. void startWPS();
  162. #endif
  163. String pager;
  164. wl_status_t wifiStatus;
  165. const char* _apName = "no-net";
  166. const char* _apPassword = NULL;
  167. String _ssid = "";
  168. String _pass = "";
  169. unsigned long _configPortalTimeout = 0;
  170. unsigned long _connectTimeout = 0;
  171. unsigned long _configPortalStart = 0;
  172. IPAddress _ap_static_ip;
  173. IPAddress _ap_static_gw;
  174. IPAddress _ap_static_sn;
  175. IPAddress _sta_static_ip;
  176. IPAddress _sta_static_gw;
  177. IPAddress _sta_static_sn;
  178. IPAddress _sta_static_dns1= (uint32_t)0x00000000;
  179. IPAddress _sta_static_dns2= (uint32_t)0x00000000;
  180. int _paramsCount = 0;
  181. int _minimumQuality = -1;
  182. boolean _removeDuplicateAPs = true;
  183. boolean _shouldBreakAfterConfig = false;
  184. #ifdef NO_EXTRA_4K_HEAP
  185. boolean _tryWPS = false;
  186. #endif
  187. const char* _customHeadElement = "";
  188. const char* _customOptionsElement = "";
  189. //String getEEPROMString(int start, int len);
  190. //void setEEPROMString(int start, int len, String string);
  191. int status = WL_IDLE_STATUS;
  192. int connectWifi(String ssid, String pass);
  193. uint8_t waitForConnectResult();
  194. void setInfo();
  195. void copySSIDInfo(wifi_ssid_count_t n);
  196. String networkListAsString();
  197. void handleRoot(AsyncWebServerRequest *);
  198. void handleWifi(AsyncWebServerRequest*,boolean scan);
  199. void handleWifiSave(AsyncWebServerRequest*);
  200. void handleInfo(AsyncWebServerRequest*);
  201. void handleReset(AsyncWebServerRequest*);
  202. void handleNotFound(AsyncWebServerRequest*);
  203. void handle204(AsyncWebServerRequest*);
  204. boolean captivePortal(AsyncWebServerRequest*);
  205. // DNS server
  206. const byte DNS_PORT = 53;
  207. //helpers
  208. int getRSSIasQuality(int RSSI);
  209. boolean isIp(String str);
  210. String toStringIp(IPAddress ip);
  211. boolean connect;
  212. boolean _debug = true;
  213. WiFiResult *wifiSSIDs;
  214. wifi_ssid_count_t wifiSSIDCount;
  215. boolean wifiSSIDscan;
  216. boolean _tryConnectDuringConfigPortal = true;
  217. void (*_apcallback)(AsyncWiFiManager*) = NULL;
  218. void (*_savecallback)(void) = NULL;
  219. AsyncWiFiManagerParameter* _params[WIFI_MANAGER_MAX_PARAMS];
  220. template <typename Generic>
  221. void DEBUG_WM(Generic text);
  222. template <class T>
  223. auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) {
  224. return obj->fromString(s);
  225. }
  226. auto optionalIPFromString(...) -> bool {
  227. DEBUG_WM("NO fromString METHOD ON IPAddress, you need ESP8266 core 2.1.0 or newer for Custom IP configuration to work.");
  228. return false;
  229. }
  230. };
  231. #endif