【问题标题】:ESP8266 + WiFiManager + pubsubclientESP8266 + WiFiManager + pubsubclient
【发布时间】:2016-01-27 22:22:20
【问题描述】:

我正在使用 ESP8266,并希望使用 MQTT 来控制它,而 MQTT 服务器是我的 Synology DS415+。我希望 ESP 放置在安装后无法使用串行访问它的地方,因此我需要能够使用 WiFi 配置它的 Wifi-Credentials 和 MQTT-Server IP、端口和凭据。

因此,我决定 WiFiManager-Library 和 PubSubClient-Library 可以为我执行此操作。问题是:我无法让 PubSubClient 使用 WiFiManager 工作,因为我还没有找到如何告诉 PubSubClient 使用正确的“客户端”。

以下示例适用于我的 ESP,但它不允许动态配置 ESP Wifi:https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_esp8266/mqtt_esp8266.ino

我想出了以下几点: http://pastebin.com/t5evEy1i

但这不起作用,它通过串行输出如下:

mounting FS...
mounted file system
reading config file
opened config file
{"mqtt_server":"192.168.1.250","mqtt_port":"9001","switch_token":"BackupSwitch"}
parsed json
*WM: Adding parameter
*WM: server
*WM: Adding parameter
*WM: port
*WM: Adding parameter
*WM: blynk
*WM: 
*WM: AutoConnect
*WM: Reading SSID
*WM: SSID: 
*WM: XXX
*WM: Reading Password
*WM: Password: XXX
*WM: Connecting as wifi client...
*WM: Connection result: 
*WM: 3
*WM: IP Address:
*WM: 192.168.1.74
connected...yeey :)
local ip
192.168.1.74
Attempting MQTT connection...192.168.1.250:9001
failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...192.168.1.250:9001
failed, rc=-2 try again in 5 seconds

我很确定问题在于第 17 行和第 18 行中 PubSubClient 的定义:

WiFiClient espClient;
PubSubClient client(espClient);

但我不知道如何从 WiFiManager 中提取客户端以将其提供给 PubSubClient-Library。

我需要的是如何获取与 WiFiClient 或 EthernetClient 创建的对象相等的对象,WiFiManager 可能会创建该对象,并且我可以将其作为参数提供给 PubSubClient 客户端(espClient);

有谁知道如何实现这一目标?提前致谢。

【问题讨论】:

    标签: arduino mqtt wifimanager esp8266


    【解决方案1】:

    您无需从 WiFiManager 中提取任何内容,因为它使用的是 WiFiClient。您需要做的就是:

    #include <ESP8266WiFi.h>
    #include <WiFiManager.h>
    #include <PubSubClient.h>
    
    WiFiClient espClient;
    PubSubClient client(espClient);
    
    void mqttCallback(char* topic, byte* payload, unsigned int length) {
        // message received
    }
    
    void mqttReconnect() {
        // reconnect code from PubSubClient example
    }
    
    void setup() {
      WiFiManager wifiManager;
      wifiManager.setTimeout(180);
    
      if(!wifiManager.autoConnect("AutoConnectAP")) {
        Serial.println("failed to connect and hit timeout");
        delay(3000);
        ESP.reset();
        delay(5000);
      } 
    
      Serial.println("connected...yeey :)");
    
      client.setServer(mqtt_server, 1883);
      client.setCallback(mqttCallback);
    }
    
    void loop() {
      if (!client.connected()) {
        mqttReconnect();
      }
      client.loop();
      yield();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多