ESPAsyncWiFiManager.h 10 KB

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