当前位置:   article > 正文

深入学习 esp8266 wifimanager源码解析(打造专属自己的web配网)(最全的wifimanager介绍))

wifimanager

原文地址:https://my.oschina.net/u/4269090/blog/3329239

1.前言

废话少说,本篇博文的目的就是深入学习 WifiManager 这个github上非常火爆的ESP8266 web配网库,让初学者不再对web配网感到迷茫,并且通过学习第三方库来自定义自己的web配网功能。等你学习整篇博文,你会发现 So easy!!

2.WiFiManager

2.1 WiFiManager源码地址

直接点击 github 下载代码

2.2 WiFiManager是什么

一句话概括:

ESP8266 WiFi连接管理器,主要是提供Web页面配置功能,包括Web配网、自定义参数配置

2.3 安装WiFiManager 库

第一步

这个库是跟ESP8266 Arduino核心库一起使用,所以用户需要配置好Arduino For ESP8266平台,具体请参考 ESP8266开发之旅 基础篇② 如何安装ESP8266的Arduino开发环境

第二步

可以通过Arduino IDE库管理器安装WiFiManager,搜索“WiFiManager”,然后点击下载(适合新手小白,直接上手使用)

也可以直接通过github下载源码,放到你的Arduino libraries文件夹(深入学习者,可以查看源码然后改造源码,达到自定义配网功能

2.4 WiFiManager工作原理

1、当你的ESP8266上电启动时,它首先进入STA模式,然后尝试去连接之前已经保存过的AP热点(如果你不了解STA和AP的区别,麻烦参考 ESP8266开发之旅 网络篇③ Soft-AP——ESP8266WiFiAP库的使用ESP8266开发之旅 网络篇④ Station——ESP8266WiFiSTA库的使用);

2、如果连接失败(可能是因为没有保存上一次的热点信息),那么该库就会让ESP进入AP模式并且提供AP热点,启动并监听DNS服务以及Web服务(默认ip地址是192.168.4.1)(如果你不了解 DNS服务 和 Web服务的概念,麻烦参考 ESP8266开发之旅 网络篇⑮ DNSServer——真正的域名服务ESP8266开发之旅 网络篇⑪ WebServer——ESP8266WebServer库的使用

3、使用任何可以连接WiFi并且可以使用浏览器的设备(包括电脑、手机、平板)去连接ESP生成的AP热点

4、由于 DNS服务 Captive Portal功能的存在,会导致任何的网络请求都重定向到 认证配置页面(也就是我们的Web配置页面)

5、选择任意一个扫描到的AP热点,输入热点密码,点击保存

6、ESP会尝试去连接新AP热点,如果连接成功,就返回到我们的正常业务,连接失败,就会再次重复上面的操作

2.5 如何引入WiFiManager库

非常简单,直接引入:

#include <WiFiManager.h> 

至于怎么样去彻底了解这个库的使用方法,请看博主下面的源码分析。

3.WifiManager源码解析

通过查阅WifiManager的源码,整体代码非常简单,提供出来的方法调用也不多。这里博主就一个个方法详细讲解,并且深入去分析代码,以便后面自定义自己的WifiManager。主要分为几类方法:

  • 配置类方法
  • 连接类方法

博主建议:先了解有什么方法,然后在后面例子讲解中去感受方法的使用

3.1 配置类方法

主要包括:

  • setConfigPortalTimeout
  • setTimeout
  • setConnectTimeout
  • setDebugOutput
  • setMinimumSignalQuality
  • setAPStaticIPConfig
  • setSTAStaticIPConfig
  • setAPCallback
  • setSaveConfigCallback
  • addParameter
  • setBreakAfterConfig
  • setCustomHeadElement
  • setRemoveDuplicateAPs
  • resetSettings
  • getConfigPortalSSID

3.1.1 setConfigPortalTimeout/setTimeout —— 配置认证超时

函数说明

  1. /**
  2. * 功能描述:配置认证超时
  3. * @param seconds 秒数为单位
  4. */
  5. void WiFiManager::setTimeout(unsigned long seconds) {
  6. setConfigPortalTimeout(seconds);
  7. }
  8. /**
  9. * 功能描述:配置认证超时
  10. * @param seconds 秒数为单位
  11. */
  12. void WiFiManager::setConfigPortalTimeout(unsigned long seconds) {
  13. _configPortalTimeout = seconds * 1000;
  14. }

注意点

  • 配置界面超时,指的是用户进入配置界面后多少秒之内如果没有处理完毕就退出整个配置过程;
  • 默认情况下,_configPortalTimeout 等于0,也就是不限制时间;

3.1.2 setConnectTimeout —— 设置sta连接超时时间

函数说明

  1. /**
  2. * 功能描述:设置sta连接超时,超过时间就返回连接状态
  3. * @param seconds 秒数为单位
  4. */
  5. void WiFiManager::setConnectTimeout(unsigned long seconds) {
  6. _connectTimeout = seconds * 1000;
  7. }

注意点

  • 正常情况下,_connectTimeout等于0,也就是直接等待连接状态。

3.1.3 setDebugOutput —— 设置是否打开debug模式

函数说明

  1. /**
  2. * 功能描述:设置是否打开debug
  3. * @param debug true or false
  4. */
  5. void WiFiManager::setDebugOutput(boolean debug) {
  6. _debug = debug;
  7. }

注意点

  • 建议调试阶段把该功能打开,可以清晰知道整个运行流程。等待调试完毕,关闭调试功能;

3.1.4 setAPStaticIPConfig —— 设置固定AP,包括ip、网关、子网掩码

函数说明

  1. /**
  2. * 功能描述:设置固定AP,包括ip、网关、子网掩码
  3. * @param ip ip地址
  4. * @param gw 网关地址
  5. * @param sn 子网掩码
  6. */
  7. void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) {
  8. _ap_static_ip = ip;
  9. _ap_static_gw = gw;
  10. _ap_static_sn = sn;
  11. }

注意点

  • 此方法用于设置ESP在AP模式下固定的AP信息,不设置默认为192.168.4.1

3.1.5 setSTAStaticIPConfig —— 设置固定STA,包括ip、网关、子网掩码

函数说明

  1. /**
  2. * 功能描述:设置固定STA,包括ip、网关、子网掩码
  3. * @param ip ip地址
  4. * @param gw 网关地址
  5. * @param sn 子网掩码
  6. */
  7. void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) {
  8. _sta_static_ip = ip;
  9. _sta_static_gw = gw;
  10. _sta_static_sn = sn;
  11. }

注意点

  • 此方法用于设置ESP在STA模式下固定的STA信息,不设置默认由DHCP分配;

3.1.6 setMinimumSignalQuality —— 设置最小的信号质量

函数说明

  1. /**
  2. * 功能描述:设置能够接受的最低信号强度
  3. * @param quality 信号强度,默认为8
  4. */
  5. void WiFiManager::setMinimumSignalQuality(int quality) {
  6. _minimumQuality = quality;
  7. }

注意点

  • 此方法用来过滤信号强度低于quality的AP热点,用于scan扫描时过滤;

3.1.7 setBreakAfterConfig —— 设置WEB配置失败后是否退出配置

函数说明

  1. /**
  2. * 功能描述:设置WEB配置失败后是否退出配置
  3. * @param shouldBreak 是否退出配置,默认是false
  4. */
  5. void WiFiManager::setBreakAfterConfig(boolean shouldBreak) {
  6. _shouldBreakAfterConfig = shouldBreak;
  7. }

3.1.8 setAPCallback —— 设置开启AP模式配置时的通知回调

函数说明

  1. /**
  2. * 功能描述:设置开启AP模式配置时的通知回调
  3. * @param func 回调函数
  4. */
  5. void WiFiManager::setAPCallback( void (*func)(WiFiManager* myWiFiManager) ) {
  6. _apcallback = func;
  7. }

注意点

  • 此方法主要是告知我们已经进入了配置模式了;

3.1.9 setSaveConfigCallback —— 设置保存Web配置后的回调

函数说明

  1. //start up save config callback
  2. /**
  3. * 功能描述:设置保存Web配置后的回调
  4. * @param func 回调函数
  5. */
  6. void WiFiManager::setSaveConfigCallback( void (*func)(void) ) {
  7. _savecallback = func;
  8. }

注意点

  • 此方法主要是告知我们已经点击保存配置信息了;

3.1.10 addParameter —— 配置页面添加自定义参数

函数说明

  1. /**
  2. * 功能描述:配置页面添加自定义参数
  3. * @param WiFiManagerParameter 自定义参数
  4. */
  5. bool WiFiManager::addParameter(WiFiManagerParameter *p) {
  6. if(_paramsCount + 1 > _max_params)
  7. {
  8. // rezise the params array
  9. _max_params += WIFI_MANAGER_MAX_PARAMS;
  10. DEBUG_WM(F("Increasing _max_params to:"));
  11. DEBUG_WM(_max_params);
  12. WiFiManagerParameter** new_params = (WiFiManagerParameter**)realloc(_params, _max_params * sizeof(WiFiManagerParameter*));
  13. if (new_params != NULL) {
  14. _params = new_params;
  15. } else {
  16. DEBUG_WM(F("ERROR: failed to realloc params, size not increased!"));
  17. return false;
  18. }
  19. }
  20. _params[_paramsCount] = p;
  21. _paramsCount++;
  22. DEBUG_WM(F("Adding parameter"));
  23. DEBUG_WM(p->getID());
  24. return true;
  25. }

注意点

  • 普通情况下我们一般只配置SSID和Password,如果你还需要添加额外的参数(比如MQTT IP和port等等),那么这个方法就比较有用;

WiFiManagerParameter:

  1. class WiFiManagerParameter {
  2. public:
  3. /**
  4. Create custom parameters that can be added to the WiFiManager setup web page
  5. @id is used for HTTP queries and must not contain spaces nor other special characters
  6. */
  7. WiFiManagerParameter(const char *custom);
  8. WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length);
  9. WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom);
  10. ~WiFiManagerParameter();
  11. // 这里比较需要注意的是 id值,这个会在html submit的时候返回给webserver,一定不能包含空格或者其他特殊字符
  12. const char *getID();
  13. const char *getValue();
  14. const char *getPlaceholder();
  15. int getValueLength();
  16. const char *getCustomHTML();
  17. private:
  18. const char *_id;
  19. const char *_placeholder;
  20. char *_value;
  21. int _length;
  22. const char *_customHTML;
  23. void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom);
  24. friend class WiFiManager;
  25. };

3.1.11 setCustomHeadElement——设置自定义页面的头部元素

函数说明

  1. /**
  2. * 功能描述:添加一个自定义的element到页面头部 比如加个头像
  3. * @param element element样式的字符串
  4. */
  5. void WiFiManager::setCustomHeadElement(const char* element) {
  6. _customHeadElement = element;
  7. }

注意点

  • 如果你觉得官方提供的界面样式看起来不爽,那么你可以试试这个方法,试图去改变点样式;

3.1.12 setRemoveDuplicateAPs——设置是否过滤重复的AP热点

函数说明

  1. //if this is true, remove duplicated Access Points - defaut true
  2. /**
  3. * 功能描述:设置是否过滤重复的AP热点,默认过滤
  4. * @param removeDuplicates true or false,default true
  5. */
  6. void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) {
  7. _removeDuplicateAPs = removeDuplicates;
  8. }

3.1.13 resetSettings——重置配置

函数说明

  1. /**
  2. * 功能描述:重置配置
  3. * @param seconds 秒数为单位
  4. */
  5. void WiFiManager::resetSettings() {
  6. DEBUG_WM(F("settings invalidated"));
  7. DEBUG_WM(F("THIS MAY CAUSE AP NOT TO START UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA."));
  8. // 断开wifi连接,设置当前配置SSID和pwd为null 设置为true,那么就会关闭Station模式
  9. WiFi.disconnect(true);
  10. //delay(200);
  11. }

3.1.14 getConfigPortalSSID——获取WEB配置的SSID

函数说明

  1. /**
  2. * 功能描述:获取AP配置的SSID
  3. */
  4. String WiFiManager::getConfigPortalSSID() {
  5. return _apName;
  6. }

3.2 连接类方法

所谓连接类方法,也就是跟wifi连接过程中相关的方法。此类方法包括:

  • autoConnect
  • startConfigPortal

3.2.1 autoConnect —— 自动连接到上一次保存的AP热点,如果连接失败,进入AP配网模式

函数说明

  1. /**
  2. * 功能说明:自动连接到上一次保存的AP热点,如果连接失败,进入AP配网模式
  3. */
  4. boolean WiFiManager::autoConnect() {
  5. // 默认的AP ssid
  6. String ssid = "ESP" + String(ESP.getChipId());
  7. return autoConnect(ssid.c_str(), NULL);
  8. }
  9. /**
  10. * 功能说明:自动连接到上一次保存的AP热点,如果连接失败,进入AP配网模式
  11. * @param apName ap模式下的名字
  12. * @param apPassword ap模式下的密码
  13. */
  14. boolean WiFiManager::autoConnect(char const *apName, char const *apPassword) {
  15. DEBUG_WM(F(""));
  16. DEBUG_WM(F("AutoConnect"));
  17. // read eeprom for ssid and pass 这里可以从eeprom获取ssid和password
  18. //String ssid = getSSID();
  19. //String pass = getPassword();
  20. // attempt to connect; should it fail, fall back to AP
  21. WiFi.mode(WIFI_STA);
  22. if (connectWifi("", "") == WL_CONNECTED) {
  23. DEBUG_WM(F("IP Address:"));
  24. DEBUG_WM(WiFi.localIP());
  25. //connected
  26. return true;
  27. }
  28. // 如果连接失败 直接进入配网管理
  29. return startConfigPortal(apName, apPassword);
  30. }

注意点

  • 这两个方法都会自动连接到上一次保存的AP热点,连接失败,就会进入web配网页面(也就是 startConfigPortal 这个方法)。用户可以自定义AP模式下的SSID和Password(也就是调用方法2)。

connectWifi方法代码:

  1. /**
  2. * 功能描述:连接Ap热点
  3. * @param ssid 热点名称
  4. * @param pass 热点密码
  5. * @return 连接状态
  6. */
  7. int WiFiManager::connectWifi(String ssid, String pass) {
  8. DEBUG_WM(F("Connecting as wifi client..."));
  9. // check if we've got static_ip settings, if we do, use those.
  10. // 判断我们是否配置了sta(ip地址、网关地址、子网掩码),有配置就设置配置内容
  11. if (_sta_static_ip) {
  12. DEBUG_WM(F("Custom STA IP/GW/Subnet"));
  13. WiFi.config(_sta_static_ip, _sta_static_gw, _sta_static_sn);
  14. DEBUG_WM(WiFi.localIP());
  15. }
  16. //fix for auto connect racing issue
  17. // 如果连接成功了 直接返回
  18. if (WiFi.status() == WL_CONNECTED && (WiFi.SSID() == ssid)) {
  19. DEBUG_WM(F("Already connected. Bailing out."));
  20. return WL_CONNECTED;
  21. }
  22. //check if we have ssid and pass and force those, if not, try with last saved values
  23. // 判断有没有传入自定义的 ssid和 pass,没有就用上次存储的
  24. if (ssid != "") {
  25. // 连接wifi
  26. WiFi.begin(ssid.c_str(), pass.c_str());
  27. } else {
  28. if (WiFi.SSID() != "") {
  29. DEBUG_WM(F("Using last saved values, should be faster"));
  30. //trying to fix connection in progress hanging
  31. ETS_UART_INTR_DISABLE();
  32. wifi_station_disconnect();
  33. ETS_UART_INTR_ENABLE();
  34. // 连接wifi
  35. WiFi.begin();
  36. } else {
  37. DEBUG_WM(F("No saved credentials"));
  38. }
  39. }
  40. // 等待连接结果
  41. int connRes = waitForConnectResult();
  42. DEBUG_WM ("Connection result: ");
  43. DEBUG_WM ( connRes );
  44. //not connected, WPS enabled, no pass - first attempt
  45. #ifdef NO_EXTRA_4K_HEAP
  46. if (_tryWPS && connRes != WL_CONNECTED && pass == "") {
  47. startWPS();
  48. //should be connected at the end of WPS
  49. connRes = waitForConnectResult();
  50. }
  51. #endif
  52. return connRes;
  53. }
  54. /**
  55. * 功能描述:等待连接结果
  56. * 如果没有设置连接超时 直接返回状态
  57. * 如果设置了连接超时 在规定时间内等待连接状态
  58. */
  59. uint8_t WiFiManager::waitForConnectResult() {
  60. if (_connectTimeout == 0) {
  61. return WiFi.waitForConnectResult();
  62. } else {
  63. DEBUG_WM (F("Waiting for connection result with time out"));
  64. unsigned long start = millis();
  65. boolean keepConnecting = true;
  66. uint8_t status;
  67. while (keepConnecting) {
  68. status = WiFi.status();
  69. // 判断连接是否超时
  70. if (millis() > start + _connectTimeout) {
  71. keepConnecting = false;
  72. DEBUG_WM (F("Connection timed out"));
  73. }
  74. if (status == WL_CONNECTED) {
  75. keepConnecting = false;
  76. }
  77. delay(100);
  78. }
  79. return status;
  80. }
  81. }

注意点

  • DEBUG_WM debug功能的实现由 setDebugOutput 控制
  • _sta_static_ip 的值 由 setSTAStaticIPConfig 设置
  • waitForConnectResult 里面 的 _connectTimeoutsetConnectTimeout 设置

3.2.2 startConfigPortal —— 启动web配置

函数说明

函数说明

  1. /**
  2. * 功能说明:配置认证,默认ssid为esp+chipid
  3. */
  4. boolean WiFiManager::startConfigPortal() {
  5. String ssid = "ESP" + String(ESP.getChipId());
  6. return startConfigPortal(ssid.c_str(), NULL);
  7. }
  8. /**
  9. * 功能说明:配置认证,切换到AP模式 然后配置webserver和dnsserver,响应web请求
  10. * @param apName ap名字
  11. * @param apPassword ap密码
  12. */
  13. boolean WiFiManager::startConfigPortal(char const *apName, char const *apPassword) {
  14. // 如果没有连接上网络 切换到AP模式
  15. if(!WiFi.isConnected()){
  16. WiFi.persistent(false);
  17. // disconnect sta, start ap
  18. WiFi.disconnect(); // this alone is not enough to stop the autoconnecter
  19. WiFi.mode(WIFI_AP);
  20. WiFi.persistent(true);
  21. }
  22. else {
  23. //setup AP 切换到AP-STA模式
  24. WiFi.mode(WIFI_AP_STA);
  25. DEBUG_WM(F("SET AP STA"));
  26. }
  27. _apName = apName;
  28. _apPassword = apPassword;
  29. //notify we entered AP mode
  30. // 通知我们进入AP模式,可以执行回调方法
  31. if ( _apcallback != NULL) {
  32. _apcallback(this);
  33. }
  34. connect = false;
  35. // 配置信息 这是非常关键的一个方法,主要是配置webserver、DNSserver
  36. setupConfigPortal();
  37. while(1){
  38. // check if timeout 判断是否配置超时
  39. if(configPortalHasTimeout()) break;
  40. //DNS 处理dns请求
  41. dnsServer->processNextRequest();
  42. //HTTP 处理web请求
  43. server->handleClient();
  44. if (connect) {
  45. connect = false;
  46. delay(2000);
  47. DEBUG_WM(F("Connecting to new AP"));
  48. // using user-provided _ssid, _pass in place of system-stored ssid and pass
  49. // 使用用户提供的wifi账号密码来设置
  50. if (connectWifi(_ssid, _pass) != WL_CONNECTED) {
  51. DEBUG_WM(F("Failed to connect."));
  52. } else {
  53. //connected
  54. WiFi.mode(WIFI_STA);
  55. //notify that configuration has changed and any optional parameters should be saved
  56. // 通知外面wifi连接成功,可以做一些额外操作
  57. if ( _savecallback != NULL) {
  58. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  59. _savecallback();
  60. }
  61. break;
  62. }
  63. // 判断配置后是否断开
  64. if (_shouldBreakAfterConfig) {
  65. //flag set to exit after config after trying to connect
  66. //notify that configuration has changed and any optional parameters should be saved
  67. if ( _savecallback != NULL) {
  68. //todo: check if any custom parameters actually exist, and check if they really changed maybe
  69. _savecallback();
  70. }
  71. break;
  72. }
  73. }
  74. yield();
  75. }
  76. server.reset();
  77. dnsServer.reset();
  78. return WiFi.status() == WL_CONNECTED;
  79. }

注意点

  • configPortalHasTimeout 用来判断是否在认证界面配置超时
  • _apcallback 通过 setAPCallback 设置
  • _savecallback 通过 setSaveConfigCallback 设置,主要用于配置完毕后保存一些信息;
  • _shouldBreakAfterConfig 通过 setBreakAfterConfig 设置,主要用来判断配置失败后是否保存信息退出;

关键方法 setupConfigPortal(一定要看博主在源码中的注释)

  1. /**
  2. * 功能描述:配置web服务以及dns重定向功能
  3. */
  4. void WiFiManager::setupConfigPortal() {
  5. // 配置dns服务(这里主要是用到重定向功能)
  6. dnsServer.reset(new DNSServer());
  7. // 配置web服务 主要用来显示web页面 实现AP配网之类的功能
  8. server.reset(new ESP8266WebServer(80));
  9. DEBUG_WM(F(""));
  10. _configPortalStart = millis();
  11. DEBUG_WM(F("Configuring access point... "));
  12. DEBUG_WM(_apName);
  13. if (_apPassword != NULL) {
  14. if (strlen(_apPassword) < 8 || strlen(_apPassword) > 63) {
  15. // fail passphrase to short or long!
  16. DEBUG_WM(F("Invalid AccessPoint password. Ignoring"));
  17. _apPassword = NULL;
  18. }
  19. DEBUG_WM(_apPassword);
  20. }
  21. //optional soft ip config
  22. // 配置自定义固定AP信息
  23. if (_ap_static_ip) {
  24. DEBUG_WM(F("Custom AP IP/GW/Subnet"));
  25. WiFi.softAPConfig(_ap_static_ip, _ap_static_gw, _ap_static_sn);
  26. }
  27. // 配置AP热点
  28. if (_apPassword != NULL) {
  29. WiFi.softAP(_apName, _apPassword);//password option
  30. } else {
  31. WiFi.softAP(_apName);
  32. }
  33. delay(500); // Without delay I've seen the IP address blank
  34. DEBUG_WM(F("AP IP address: "));
  35. DEBUG_WM(WiFi.softAPIP());
  36. /* Setup the DNS server redirecting all the domains to the apIP */
  37. // 配置DNS 重定向功能 全部请求都重定向到AP
  38. dnsServer->setErrorReplyCode(DNSReplyCode::NoError);
  39. dnsServer->start(DNS_PORT, "*", WiFi.softAPIP());
  40. /* Setup web pages: root, wifi config pages, SO captive portal detectors and not found. */
  41. // 配置Web服务器的功能 这里就是实现AP配网功能
  42. server->on(String(F("/")).c_str(), std::bind(&WiFiManager::handleRoot, this));
  43. server->on(String(F("/wifi")).c_str(), std::bind(&WiFiManager::handleWifi, this, true));
  44. server->on(String(F("/0wifi")).c_str(), std::bind(&WiFiManager::handleWifi, this, false));
  45. server->on(String(F("/wifisave")).c_str(), std::bind(&WiFiManager::handleWifiSave, this));
  46. server->on(String(F("/i")).c_str(), std::bind(&WiFiManager::handleInfo, this));
  47. server->on(String(F("/r")).c_str(), std::bind(&WiFiManager::handleReset, this));
  48. //server->on("/generate_204", std::bind(&WiFiManager::handle204, this)); //Android/Chrome OS captive portal check.
  49. server->on(String(F("/fwlink")).c_str(), std::bind(&WiFiManager::handleRoot, this)); //Microsoft captive portal. Maybe not needed. Might be handled by notFound handler.
  50. server->onNotFound (std::bind(&WiFiManager::handleNotFound, this));
  51. server->begin(); // Web server start
  52. DEBUG_WM(F("HTTP server started"));
  53. }

注意点

  • _ap_static_ip 通过 setAPStaticIPConfig 设置,设置AP模式下的固定IP信息
  • handleRoot 处理域的web请求,比如 192.168.4.1
  • handleWifi 处理web配置页面的请求
  • handleWifiSave 处理wifi配置信息保存请求
  • handleInfo 处理wifi信息的展示
  • handleReset 处理wifi配置重置的请求

接下来,重点讲解handleXXX方法的具体内容以及展示页面(后面打造专属自己的web配网也是从这里修改)。

3.2.2.1 handleRoot —— 根目录页面

函数说明

  1. /** Handle root or redirect to captive portal */
  2. /**
  3. * 功能描述:响应root请求,也就是ip请求
  4. */
  5. void WiFiManager::handleRoot() {
  6. DEBUG_WM(F("Handle root"));
  7. if (captivePortal()) { // If caprive portal redirect instead of displaying the page.
  8. return;
  9. }
  10. // 这里就会显示一个通用页面了
  11. String page = FPSTR(HTTP_HEADER);
  12. page.replace("{v}", "Options");
  13. page += FPSTR(HTTP_SCRIPT);
  14. page += FPSTR(HTTP_STYLE);
  15. page += _customHeadElement;
  16. page += FPSTR(HTTP_HEADER_END);
  17. page += String(F("<h1>"));
  18. page += _apName;
  19. page += String(F("</h1>"));
  20. page += String(F("<h3>WiFiManager</h3>"));
  21. page += FPSTR(HTTP_PORTAL_OPTIONS);
  22. page += FPSTR(HTTP_END);
  23. server->sendHeader("Content-Length", String(page.length()));
  24. server->send(200, "text/html", page);
  25. }

注意点

  • 此方法是整个配置页面的入口页面,会包含后面一些列操作的入口
  • 这里拼接了一个web页面返回,包括自定义的 _customHeadElement

Root 页面的HTML+CSS+JS代码(这里是我们后面打造专属自己样式的关键)

  1. const char HTTP_HEADER[] PROGMEM = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/><title>{v}</title>";
  2. 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>";
  3. const char HTTP_SCRIPT[] PROGMEM = "<script>function c(l){document.getElementById('s').value=l.innerText||l.textContent;document.getElementById('p').focus();}</script>";
  4. const char HTTP_HEADER_END[] PROGMEM = "</head><body><div style='text-align:left;display:inline-block;min-width:260px;'>";
  5. 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>";
  6. const char HTTP_ITEM[] PROGMEM = "<div><a href='#p' onclick='c(this)'>{v}</a>&nbsp;<span class='q {i}'>{r}%</span></div>";
  7. 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/>";
  8. const char HTTP_FORM_PARAM[] PROGMEM = "<br/><input id='{i}' name='{n}' maxlength={l} placeholder='{p}' value='{v}' {c}>";
  9. const char HTTP_FORM_END[] PROGMEM = "<br/><button type='submit'>save</button></form>";
  10. const char HTTP_SCAN_LINK[] PROGMEM = "<br/><div class=\"c\"><a href=\"/wifi\">Scan</a></div>";
  11. 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>";
  12. const char HTTP_END[] PROGMEM = "</div></body></html>";

Root页面效果

这里包含了多个功能入口

  • Configure WiFi、Configure WiFi(No Scan)—— handleWifi
  • Info —— handleInfo
  • Reset —— handleReset

3.2.2.2 handleWifi —— 配置Wifi信息

用户点击 Configure WiFi、Configure WiFi(No Scan) 就会响应此方法。

函数说明

  1. /** Wifi config page handler */
  2. /**
  3. * 功能描述:wifi配置页面
  4. * @param scan true or false,是否开启扫描
  5. */
  6. void WiFiManager::handleWifi(boolean scan) {
  7. String page = FPSTR(HTTP_HEADER);
  8. page.replace("{v}", "Config ESP");
  9. page += FPSTR(HTTP_SCRIPT);
  10. page += FPSTR(HTTP_STYLE);
  11. page += _customHeadElement;
  12. page += FPSTR(HTTP_HEADER_END);
  13. // 判断是否扫描
  14. if (scan) {
  15. // 获取扫描结果
  16. int n = WiFi.scanNetworks();
  17. DEBUG_WM(F("Scan done"));
  18. if (n == 0) {
  19. DEBUG_WM(F("No networks found"));
  20. page += F("No networks found. Refresh to scan again.");
  21. } else {
  22. //sort networks
  23. int indices[n];
  24. for (int i = 0; i < n; i++) {
  25. indices[i] = i;
  26. }
  27. // RSSI SORT
  28. // old sort 排序信号强度,高的放在前面
  29. for (int i = 0; i < n; i++) {
  30. for (int j = i + 1; j < n; j++) {
  31. if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) {
  32. std::swap(indices[i], indices[j]);
  33. }
  34. }
  35. }
  36. /*std::sort(indices, indices + n, [](const int & a, const int & b) -> bool
  37. {
  38. return WiFi.RSSI(a) > WiFi.RSSI(b);
  39. });*/
  40. // remove duplicates ( must be RSSI sorted )
  41. // 是否去掉重复的AP
  42. if (_removeDuplicateAPs) {
  43. String cssid;
  44. for (int i = 0; i < n; i++) {
  45. if (indices[i] == -1) continue;
  46. cssid = WiFi.SSID(indices[i]);
  47. for (int j = i + 1; j < n; j++) {
  48. if (cssid == WiFi.SSID(indices[j])) {
  49. DEBUG_WM("DUP AP: " + WiFi.SSID(indices[j]));
  50. indices[j] = -1; // set dup aps to index -1
  51. }
  52. }
  53. }
  54. }
  55. //display networks in page
  56. // 拼接每一个需要显示的ap热点信息
  57. for (int i = 0; i < n; i++) {
  58. if (indices[i] == -1) continue; // skip dups
  59. DEBUG_WM(WiFi.SSID(indices[i]));
  60. DEBUG_WM(WiFi.RSSI(indices[i]));
  61. int quality = getRSSIasQuality(WiFi.RSSI(indices[i]));
  62. // 判断信号强度是否大于我们设置的最小强度
  63. if (_minimumQuality == -1 || _minimumQuality < quality) {
  64. String item = FPSTR(HTTP_ITEM);
  65. String rssiQ;
  66. rssiQ += quality;
  67. item.replace("{v}", WiFi.SSID(indices[i]));
  68. item.replace("{r}", rssiQ);
  69. if (WiFi.encryptionType(indices[i]) != ENC_TYPE_NONE) {
  70. item.replace("{i}", "l");
  71. } else {
  72. item.replace("{i}", "");
  73. }
  74. //DEBUG_WM(item);
  75. page += item;
  76. delay(0);
  77. } else {
  78. DEBUG_WM(F("Skipping due to quality"));
  79. }
  80. }
  81. page += "<br/>";
  82. }
  83. }
  84. page += FPSTR(HTTP_FORM_START);
  85. char parLength[5];
  86. // add the extra parameters to the form
  87. // 添加我们自定义的参数
  88. for (int i = 0; i < _paramsCount; i++) {
  89. if (_params[i] == NULL) {
  90. break;
  91. }
  92. String pitem = FPSTR(HTTP_FORM_PARAM);
  93. if (_params[i]->getID() != NULL) {
  94. pitem.replace("{i}", _params[i]->getID());
  95. pitem.replace("{n}", _params[i]->getID());
  96. pitem.replace("{p}", _params[i]->getPlaceholder());
  97. snprintf(parLength, 5, "%d", _params[i]->getValueLength());
  98. pitem.replace("{l}", parLength);
  99. pitem.replace("{v}", _params[i]->getValue());
  100. pitem.replace("{c}", _params[i]->getCustomHTML());
  101. } else {
  102. pitem = _params[i]->getCustomHTML();
  103. }
  104. page += pitem;
  105. }
  106. if (_params[0] != NULL) {
  107. page += "<br/>";
  108. }
  109. if (_sta_static_ip) {
  110. String item = FPSTR(HTTP_FORM_PARAM);
  111. item.replace("{i}", "ip");
  112. item.replace("{n}", "ip");
  113. item.replace("{p}", "Static IP");
  114. item.replace("{l}", "15");
  115. item.replace("{v}", _sta_static_ip.toString());
  116. page += item;
  117. item = FPSTR(HTTP_FORM_PARAM);
  118. item.replace("{i}", "gw");
  119. item.replace("{n}", "gw");
  120. item.replace("{p}", "Static Gateway");
  121. item.replace("{l}", "15");
  122. item.replace("{v}", _sta_static_gw.toString());
  123. page += item;
  124. item = FPSTR(HTTP_FORM_PARAM);
  125. item.replace("{i}", "sn");
  126. item.replace("{n}", "sn");
  127. item.replace("{p}", "Subnet");
  128. item.replace("{l}", "15");
  129. item.replace("{v}", _sta_static_sn.toString());
  130. page += item;
  131. page += "<br/>";
  132. }
  133. page += FPSTR(HTTP_FORM_END);
  134. page += FPSTR(HTTP_SCAN_LINK);
  135. page += FPSTR(HTTP_END);
  136. server->sendHeader("Content-Length", String(page.length()));
  137. server->send(200, "text/html", page);
  138. DEBUG_WM(F("Sent config page"));
  139. }

注意点

  • _minimumQualitysetMinimumSignalQuality 设置

上图是启用了scan功能的效果。

上图没有启用scan功能,通常用于隐藏SSID的配置。 关于scan功能,麻烦读者参考 ESP8266开发之旅 网络篇⑤ Scan WiFi——ESP8266WiFiScan库的使用

3.2.2.3 handleWifiSave —— 保存Wifi信息

用户在wifi配置页面点击 save 操作就会响应此方法。

函数说明

  1. /** Handle the WLAN save form and redirect to WLAN config page again */
  2. /**
  3. * 功能描述:保存wifi设置
  4. */
  5. void WiFiManager::handleWifiSave() {
  6. DEBUG_WM(F("WiFi save"));
  7. //SAVE/connect here 保存用户设置的ssid和psw
  8. _ssid = server->arg("s").c_str();
  9. _pass = server->arg("p").c_str();
  10. //parameters
  11. // 保存用户设置的自定义参数
  12. for (int i = 0; i < _paramsCount; i++) {
  13. if (_params[i] == NULL) {
  14. break;
  15. }
  16. //read parameter
  17. String value = server->arg(_params[i]->getID()).c_str();
  18. //store it in array
  19. value.toCharArray(_params[i]->_value, _params[i]->_length + 1);
  20. DEBUG_WM(F("Parameter"));
  21. DEBUG_WM(_params[i]->getID());
  22. DEBUG_WM(value);
  23. }
  24. if (server->arg("ip") != "") {
  25. DEBUG_WM(F("static ip"));
  26. DEBUG_WM(server->arg("ip"));
  27. //_sta_static_ip.fromString(server->arg("ip"));
  28. String ip = server->arg("ip");
  29. optionalIPFromString(&_sta_static_ip, ip.c_str());
  30. }
  31. if (server->arg("gw") != "") {
  32. DEBUG_WM(F("static gateway"));
  33. DEBUG_WM(server->arg("gw"));
  34. String gw = server->arg("gw");
  35. optionalIPFromString(&_sta_static_gw, gw.c_str());
  36. }
  37. if (server->arg("sn") != "") {
  38. DEBUG_WM(F("static netmask"));
  39. DEBUG_WM(server->arg("sn"));
  40. String sn = server->arg("sn");
  41. optionalIPFromString(&_sta_static_sn, sn.c_str());
  42. }
  43. // 拼接一个 wifi 保存的页面通知 确保响应了
  44. String page = FPSTR(HTTP_HEADER);
  45. page.replace("{v}", "Credentials Saved");
  46. page += FPSTR(HTTP_SCRIPT);
  47. page += FPSTR(HTTP_STYLE);
  48. page += _customHeadElement;
  49. page += FPSTR(HTTP_HEADER_END);
  50. page += FPSTR(HTTP_SAVED);
  51. page += FPSTR(HTTP_END);
  52. server->sendHeader("Content-Length", String(page.length()));
  53. server->send(200, "text/html", page);
  54. DEBUG_WM(F("Sent wifi save page"));
  55. connect = true; //signal ready to connect/reset
  56. }

3.2.2.4 handleInfo —— 获取ESP的信息

用户在wifi配置页面点击 Info 操作就会响应此方法。

函数说明

  1. /** Handle the info page */
  2. /**
  3. * 功能描述:展示详情信息
  4. */
  5. void WiFiManager::handleInfo() {
  6. DEBUG_WM(F("Info"));
  7. String page = FPSTR(HTTP_HEADER);
  8. page.replace("{v}", "Info");
  9. page += FPSTR(HTTP_SCRIPT);
  10. page += FPSTR(HTTP_STYLE);
  11. page += _customHeadElement;
  12. page += FPSTR(HTTP_HEADER_END);
  13. page += F("<dl>");
  14. // 芯片id
  15. page += F("<dt>Chip ID</dt><dd>");
  16. page += ESP.getChipId();
  17. page += F("</dd>");
  18. // flash 芯片id
  19. page += F("<dt>Flash Chip ID</dt><dd>");
  20. page += ESP.getFlashChipId();
  21. page += F("</dd>");
  22. // flash大小
  23. page += F("<dt>IDE Flash Size</dt><dd>");
  24. page += ESP.getFlashChipSize();
  25. page += F(" bytes</dd>");
  26. page += F("<dt>Real Flash Size</dt><dd>");
  27. page += ESP.getFlashChipRealSize();
  28. page += F(" bytes</dd>");
  29. page += F("<dt>Soft AP IP</dt><dd>");
  30. // AP ip地址
  31. page += WiFi.softAPIP().toString();
  32. page += F("</dd>");
  33. page += F("<dt>Soft AP MAC</dt><dd>");
  34. // AP mac地址
  35. page += WiFi.softAPmacAddress();
  36. page += F("</dd>");
  37. page += F("<dt>Station MAC</dt><dd>");
  38. page += WiFi.macAddress();
  39. page += F("</dd>");
  40. page += F("</dl>");
  41. page += FPSTR(HTTP_END);
  42. server->sendHeader("Content-Length", String(page.length()));
  43. server->send(200, "text/html", page);
  44. DEBUG_WM(F("Sent info page"));
  45. }

 

3.2.2.5 handleReset —— 重置Wifi模块信息

用户在wifi配置页面点击 Reset 操作就会响应此方法。

函数说明

  1. /** Handle the reset page */
  2. void WiFiManager::handleReset() {
  3. DEBUG_WM(F("Reset"));
  4. String page = FPSTR(HTTP_HEADER);
  5. page.replace("{v}", "Info");
  6. page += FPSTR(HTTP_SCRIPT);
  7. page += FPSTR(HTTP_STYLE);
  8. page += _customHeadElement;
  9. page += FPSTR(HTTP_HEADER_END);
  10. page += F("Module will reset in a few seconds.");
  11. page += FPSTR(HTTP_END);
  12. server->sendHeader("Content-Length", String(page.length()));
  13. server->send(200, "text/html", page);
  14. DEBUG_WM(F("Sent reset page"));
  15. delay(5000);
  16. // 重置信息
  17. ESP.reset();
  18. delay(2000);
  19. }

 

4.官方实例操作

使用WifiManager三部曲:

  • 引入头文件
#include <WiFiManager.h>
  • 配置具体参数
  • 启动WifiManager服务

请读者烧录以下代码: 例子源码

  1. /**
  2. * 功能:测试WifiManager功能demo
  3. * 作者:单片机菜鸟
  4. * 时间:2019-12-13
  5. * 描述:
  6. * 1.启动wifimanager AP配置页面,通过手机连接esp8266生成的AP热点来进入设置页面
  7. * 2.请在手机浏览器上输入 192.168.4.25
  8. * 2.测试官方方法的使用
  9. */
  10. #include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
  11. //needed for library
  12. #include <DNSServer.h>
  13. #include <ESP8266WebServer.h>
  14. #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
  15. #include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
  16. //for LED status
  17. #include <Ticker.h>
  18. void initSystem();
  19. void initWifiManager();
  20. void configModeCallback(WiFiManager *myWiFiManager);
  21. void saveConfigCallback();
  22. void tick();
  23. //flag for saving data
  24. bool shouldSaveConfig = false;
  25. //for LED status
  26. Ticker ticker;
  27. //define your default values here, if there are different values in config.json, they are overwritten.
  28. char mqtt_server[40];
  29. char mqtt_port[6] = "8080";
  30. char api_key[34] = "Your ApiKey";
  31. void setup() {
  32. // put your setup code here, to run once:
  33. initSystem();
  34. initWifiManager();
  35. //if you get here you have connected to the WiFi
  36. Serial.println("connected...so easy :)");
  37. ticker.detach();
  38. //keep LED on
  39. digitalWrite(BUILTIN_LED, LOW);
  40. }
  41. void loop() {
  42. // put your main code here, to run repeatedly:
  43. }
  44. /**
  45. * 功能描述:初始化esp8266
  46. */
  47. void initSystem(){
  48. Serial.begin(115200);
  49. Serial.println();
  50. //set led pin as output
  51. pinMode(BUILTIN_LED, OUTPUT);
  52. // start ticker with 0.5 because we start in AP mode and try to connect
  53. ticker.attach(0.6, tick);
  54. }
  55. /**
  56. * 功能描述:初始化wifimanager
  57. */
  58. void initWifiManager(){
  59. /*** 步骤一:创建 wifimanager对象 **/
  60. WiFiManager wifiManager;
  61. /*************************************/
  62. /*** 步骤二:进行一系列配置,参考配置类方法 **/
  63. // 重置保存的修改 目标是为了每次进来都是去掉配置页面
  64. wifiManager.resetSettings();
  65. // 配置连接超时
  66. wifiManager.setConnectTimeout(60);
  67. // 打印调试内容
  68. wifiManager.setDebugOutput(true);
  69. // 设置最小信号强度
  70. wifiManager.setMinimumSignalQuality(30);
  71. // 设置固定AP信息
  72. IPAddress _ip = IPAddress(192, 168, 4, 25);
  73. IPAddress _gw = IPAddress(192, 168, 4, 1);
  74. IPAddress _sn = IPAddress(255, 255, 255, 0);
  75. wifiManager.setAPStaticIPConfig(_ip, _gw, _sn);
  76. // 设置进入AP模式的回调
  77. wifiManager.setAPCallback(configModeCallback);
  78. // 设置点击保存的回调
  79. wifiManager.setSaveConfigCallback(saveConfigCallback);
  80. // 设置 如果配置错误的ssid或者密码 退出配置模式
  81. wifiManager.setBreakAfterConfig(true);
  82. // 设置过滤重复的AP 默认可以不用调用 这里只是示范
  83. wifiManager.setRemoveDuplicateAPs(true);
  84. // 添加额外的参数 博哥这里只是示范 比如加入 mqtt 服务器地址 port 端口号 apikey 后面可以结合onenet使用
  85. WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
  86. WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
  87. WiFiManagerParameter custom_apikey("apikey", "onenet apikey", api_key, 32);
  88. wifiManager.addParameter(&custom_mqtt_server);
  89. wifiManager.addParameter(&custom_mqtt_port);
  90. wifiManager.addParameter(&custom_apikey);
  91. /*************************************/
  92. /*** 步骤三:尝试连接网络,失败去到配置页面 **/
  93. // ssid 命名为danpianjicainiao pwd是123456
  94. if (!wifiManager.autoConnect("danpianjicainiao","123456")) {
  95. Serial.println("failed to connect and hit timeout");
  96. //reset and try again, or maybe put it to deep sleep
  97. ESP.reset();
  98. delay(1000);
  99. }
  100. /*************************************/
  101. // 读取配置页面配置好的信息
  102. strcpy(mqtt_server, custom_mqtt_server.getValue());
  103. strcpy(mqtt_port, custom_mqtt_port.getValue());
  104. strcpy(api_key, custom_apikey.getValue());
  105. // 保存自定义信息
  106. if (shouldSaveConfig) {
  107. Serial.println("saving config");
  108. DynamicJsonBuffer jsonBuffer;
  109. JsonObject& json = jsonBuffer.createObject();
  110. json["mqtt_server"] = mqtt_server;
  111. json["mqtt_port"] = mqtt_port;
  112. json["api_key"] = api_key;
  113. json.printTo(Serial);
  114. //end save
  115. }
  116. Serial.println("local ip");
  117. Serial.println(WiFi.localIP());
  118. }
  119. /**
  120. * 功能描述:配置进入AP模式通知回调
  121. */
  122. void configModeCallback (WiFiManager *myWiFiManager) {
  123. Serial.println("Entered config mode");
  124. Serial.println(WiFi.softAPIP());
  125. //if you used auto generated SSID, print it
  126. Serial.println(myWiFiManager->getConfigPortalSSID());
  127. //entered config mode, make led toggle faster
  128. ticker.attach(0.2, tick);
  129. }
  130. /**
  131. * 功能描述:设置点击保存的回调
  132. */
  133. void saveConfigCallback () {
  134. Serial.println("Should save config");
  135. shouldSaveConfig = true;
  136. }
  137. /**
  138. * 功能描述:设置LED灯闪烁,提示用户进入配置模式
  139. */
  140. void tick(){
  141. //toggle state
  142. int state = digitalRead(BUILTIN_LED); // get the current state of GPIO1 pin
  143. digitalWrite(BUILTIN_LED, !state); // set pin to the opposite state
  144. }

这里重点讲解了各个方法的使用,并且通过led灯闪烁来表示工作模式,请读者自行下载烧录体会。没有意外情况的下会有以下控制页面(直接看博主截图说明):

输入密码后,就可以连接上新wifi。 由于代码中打开了串口调试功能,所以可以看到以下调试信息:

美中不足

  • 对于习惯于中文的初学者来说,肯定是希望可以支持中文;
  • 对于爱好潮流的人来说,肯定希望打造自己的web配网页面;

下面就是博主基于wifiManger去打造专属自己的web配网,暂且命名为 CustomWifiManager。此库,博主已经上传到QQ技术交流群。

5.打造专属自己的web配网

5.1 CustomWifiManager —— 站在巨人肩膀上

博主基于WifiManger改造了几个方面,适合简单的样式修改。

5.1.1 setHeadImgBase64 —— 支持自定义ICON头像

函数说明

  1. void WiFiManager::setHeadImgBase64(String imgBase64) {
  2. _imgBase64= imgBase64;
  3. }

5.1.2 setButtonBackground—— 自定义按钮背景颜色

函数说明

  1. void WiFiManager::setButtonBackground(const char* backgroundColor){
  2. _backgroundColor= backgroundColor;
  3. }

5.1.3 setButtonTextColor—— 自定义按钮字体颜色

函数说明

  1. void WiFiManager::setButtonTextColor(const char* textColor) {
  2. _textColor= textColor;
  3. }

5.1.4 setPageTitle—— 自定义页面标题

函数说明

  1. void WiFiManager::setPageTitle(const char* pageTitle){
  2. _pageTitle = pageTitle;
  3. }

5.2 案例

例子源码

  1. /**
  2. * 功能:测试WifiManager功能demo
  3. * 作者:单片机菜鸟
  4. * 时间:2019-12-13
  5. * 描述:
  6. * 1.启动wifimanager AP配置页面,通过手机连接esp8266生成的AP热点来进入设置页面
  7. * 2.请在手机浏览器上输入 192.168.4.25
  8. * 3.分别支持大叔黄 萌弟蓝 少女粉
  9. */
  10. #include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
  11. //needed for library
  12. #include <DNSServer.h>
  13. #include <ESP8266WebServer.h>
  14. #include <CustomWiFiManager.h> //https://github.com/tzapu/WiFiManager
  15. #include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
  16. //for LED status
  17. #include <Ticker.h>
  18. // 自定义我的icon 请随便使用一个图片转base64工具转换
  19. const char yellowWifi[] PROGMEM = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4wEJAi4oIVrQDgAADLpJREFUeNrtmntwXNV9xz/n3rsPaVdvrSxvjEEYXMu2AnYVmxo6OCG4U7vgKaS4neCaOonbMbhkAhkwLdS4JRmcqZOSMJNpoUAS2inuZBJ7poUyQyApxNYMmNgIV7IiySroga3XarWve+85/ePc1a4eu5ZdO5sM+ml2dnXPvXt+v+/5nu/5nfNb0XsQxcfYjFI7UGpbAKDUDpTaFgAotQOltgUASu1AqW0BgFI7UGpbAKDUDpTaPvYAWL+qj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Gh1bWI6Ok1pbWV0eXBlAGltYWdlL3BuZz+yVk4AAAAXdEVYdFRodW1iOjpNVGltZQAxNTQ2OTYzODUwFYbWHQAAABJ0RVh0VGh1bWI6OlNpemUAMzY2MDFCMtvoDwAAAGB0RVh0VGh1bWI6OlVSSQBmaWxlOi8vL2hvbWUvd3d3cm9vdC9uZXdzaXRlL3d3dy5lYXN5aWNvbi5uZXQvY2RuLWltZy5lYXN5aWNvbi5jbi9maWxlcy81Mi81MjU5NjgucG5n+YEv+wAAAABJRU5ErkJggg==";
  22. void initSystem();
  23. void initWifiManager();
  24. void configModeCallback(WiFiManager *myWiFiManager);
  25. void saveConfigCallback();
  26. void tick();
  27. //flag for saving data
  28. bool shouldSaveConfig = false;
  29. //for LED status
  30. Ticker ticker;
  31. //define your default values here, if there are different values in config.json, they are overwritten.
  32. char mqtt_server[40];
  33. char mqtt_port[6] = "8080";
  34. char api_key[34] = "Your ApiKey";
  35. void setup() {
  36. // put your setup code here, to run once:
  37. initSystem();
  38. initWifiManager();
  39. //if you get here you have connected to the WiFi
  40. Serial.println("connected...so easy :)");
  41. ticker.detach();
  42. //keep LED on
  43. digitalWrite(BUILTIN_LED, LOW);
  44. }
  45. void loop() {
  46. // put your main code here, to run repeatedly:
  47. }
  48. /**
  49. * 功能描述:初始化esp8266
  50. */
  51. void initSystem(){
  52. Serial.begin(115200);
  53. Serial.println();
  54. //set led pin as output
  55. pinMode(BUILTIN_LED, OUTPUT);
  56. // start ticker with 0.5 because we start in AP mode and try to connect
  57. ticker.attach(0.6, tick);
  58. }
  59. /**
  60. * 功能描述:初始化wifimanager
  61. */
  62. void initWifiManager(){
  63. /*** 步骤一:创建 wifimanager对象 **/
  64. WiFiManager wifiManager;
  65. /*************************************/
  66. /*** 步骤二:进行一系列配置,参考配置类方法 **/
  67. // 重置保存的修改 目标是为了每次进来都是去掉配置页面
  68. wifiManager.resetSettings();
  69. // 配置连接超时
  70. // wifiManager.setConnectTimeout(240);
  71. // 打印调试内容
  72. wifiManager.setDebugOutput(true);
  73. // 设置个人图标
  74. // 大叔黄
  75. //wifiManager.setHeadImgBase64(FPSTR(yellowWifi));
  76. //wifiManager.setButtonBackground("#E08E00");
  77. // 萌弟蓝
  78. wifiManager.setHeadImgBase64(FPSTR(blueWifi));
  79. wifiManager.setButtonBackground("#2394BC");
  80. // 少女粉
  81. //wifiManager.setHeadImgBase64(FPSTR(pinkWifi));
  82. //wifiManager.setButtonBackground("#D5BADB");
  83. // 设置最小信号强度
  84. wifiManager.setMinimumSignalQuality(40);
  85. // 设置固定AP信息
  86. IPAddress _ip = IPAddress(192, 168, 4, 25);
  87. IPAddress _gw = IPAddress(192, 168, 4, 1);
  88. IPAddress _sn = IPAddress(255, 255, 255, 0);
  89. wifiManager.setAPStaticIPConfig(_ip, _gw, _sn);
  90. // 设置进入AP模式的回调
  91. wifiManager.setAPCallback(configModeCallback);
  92. // 设置点击保存的回调
  93. wifiManager.setSaveConfigCallback(saveConfigCallback);
  94. // 设置 如果配置错误的ssid或者密码 退出配置模式
  95. wifiManager.setBreakAfterConfig(true);
  96. // 设置过滤重复的AP 默认可以不用调用 这里只是示范
  97. wifiManager.setRemoveDuplicateAPs(true);
  98. // 添加额外的参数 博哥这里只是示范 比如加入 mqtt 服务器地址 port 端口号 apikey 后面可以结合onenet使用
  99. WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
  100. WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
  101. WiFiManagerParameter custom_apikey("apikey", "onenet apikey", api_key, 32);
  102. wifiManager.addParameter(&custom_mqtt_server);
  103. wifiManager.addParameter(&custom_mqtt_port);
  104. wifiManager.addParameter(&custom_apikey);
  105. /*************************************/
  106. /*** 步骤三:尝试连接网络,失败去到配置页面 **/
  107. // ssid 命名为danpianjicainiao pwd是123456
  108. if (!wifiManager.autoConnect("danpianjicainiao","123456")) {
  109. Serial.println("failed to connect and hit timeout");
  110. //reset and try again, or maybe put it to deep sleep
  111. ESP.reset();
  112. delay(1000);
  113. }
  114. /*************************************/
  115. // 读取配置页面配置好的信息
  116. strcpy(mqtt_server, custom_mqtt_server.getValue());
  117. strcpy(mqtt_port, custom_mqtt_port.getValue());
  118. strcpy(api_key, custom_apikey.getValue());
  119. // 保存自定义信息
  120. if (shouldSaveConfig) {
  121. Serial.println("saving config");
  122. DynamicJsonBuffer jsonBuffer;
  123. JsonObject& json = jsonBuffer.createObject();
  124. json["mqtt_server"] = mqtt_server;
  125. json["mqtt_port"] = mqtt_port;
  126. json["api_key"] = api_key;
  127. json.printTo(Serial);
  128. //end save
  129. }
  130. Serial.println("local ip");
  131. Serial.println(WiFi.localIP());
  132. }
  133. /**
  134. * 功能描述:配置进入AP模式通知回调
  135. */
  136. void configModeCallback (WiFiManager *myWiFiManager) {
  137. Serial.println("Entered config mode");
  138. Serial.println(WiFi.softAPIP());
  139. //if you used auto generated SSID, print it
  140. Serial.println(myWiFiManager->getConfigPortalSSID());
  141. //entered config mode, make led toggle faster
  142. ticker.attach(0.2, tick);
  143. }
  144. /**
  145. * 功能描述:设置点击保存的回调
  146. */
  147. void saveConfigCallback () {
  148. Serial.println("Should save config");
  149. shouldSaveConfig = true;
  150. }
  151. /**
  152. * 功能描述:设置LED灯闪烁,提示用户进入配置模式
  153. */
  154. void tick(){
  155. //toggle state
  156. int state = digitalRead(BUILTIN_LED); // get the current state of GPIO1 pin
  157. digitalWrite(BUILTIN_LED, !state); // set pin to the opposite state
  158. }

请读者安装好自定义库之后烧录以上代码进行测试,不出意外的话,就是以下页面效果:

大叔黄(博主命名请勿喷)

萌弟蓝(博主命名请勿喷)

少女粉(博主命名请勿喷

这里,博主仅仅是列举了三个样式,读者可以自行打造专属自己的web配网。但是博主需要提醒读者几个小点:

  • icon不宜太复杂太大,建议使用小图标,比如博主从 这里 下载。下载完图标之后需要转成base64,可以通过 图片在线转换 来获取。
  • 最好是图标的颜色和button的颜色一样,读者可以通过 传图识色 来获取颜色值。

6.总结

本篇主要是讲解wifimanger的源码解析,并且尝试去打造专属自己的web配网。 如果你觉得本篇对你有帮助,麻烦点赞关注,谢谢支持。本篇内容涵盖了多方面知识,希望读者可以打好基础,多去阅读博主关于esp8266系列的文章,我敢保证肯定收益匪浅。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/211539
推荐阅读
相关标签
  

闽ICP备14008679号