ESPAsyncWiFiManager.h 10 KB

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