ESPAsyncWiFiManager.h 9.8 KB

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