ESP8266 + WiFiManager + pubsubclient

时间:2016-01-27 22:22:21

标签: arduino mqtt wifimanager esp8266

我正在使用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);

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

1 个答案:

答案 0 :(得分:4)

您不需要从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();
}