ESPAsyncWiFiManager.h 9.4 KB

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