使用 PubSubClient.h 回调函数的 NodeMCU esp8266 被忽略

NodeMCU esp8266 using PubSubClient.h callback function gets ignored

编辑: 发布和订阅的主题是正确的,即使它们看起来不同。随着我的发布,我在领域 4 上写作。此外,我 运行 也 MQTT.fx 在 sub/pub 模式下使用相同的主题并且它完美地工作。

我想在我的 NodeMCU 和 esp8266 上使用 mqtt。我将 simple MQTT example 改编为我的最小项目。在我的代码(附在下面)中,我正在尝试发布和订阅 ThingSpeak 频道。 publish函数没有任何问题,每次调用都会发布。但是回调函数被忽略了,我的代码从来没有进入过。

要在此处提供更多信息,您有我的设置:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "*****";
const char* password = "*****";
const char* mqtt_server = "mqtt.thingspeak.com";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Ciao sono la callback1\n");
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    Serial.print("Ciao sono la callback2\n");
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    Serial.print("Ciao sono la callback3\n");
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("channels/517055/publish/V4ZW4Y01ZLFD5XYR", "field5=7&status=MQTTPUBLISH");
      // ... and resubscribe
      client.subscribe("channels/517055/subscribe/fields/field4");
      Serial.print("Ciao sono subscribe 01\n");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  Serial.print("Ciao sono la callback 10\n");
  client.subscribe("channels/517055/subscribe/fields/field4");
  Serial.print("Ciao subscribe 10\n");
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "field4= %ld&status=MQTTPUBLISH", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("channels/517055/publish/V4ZW4Y01ZLFD5XYR", msg);
  }
}

此外这里还有我的串行监视器输出:

Connecting to ZICHICHI
scandone
scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt 

connected with ZICHICHI, channel 1
dhcp client start...
............ip:192.168.1.68,mask:255.255.255.0,gw:192.168.1.254
.
WiFi connected
IP address: 
192.168.1.68
Ciao sono la callback 10
Ciao subscribe 10
Attempting MQTT connection...connected
Ciao sono subscribe 01
Publish message: field4= 1&status=MQTTPUBLISH
Publish message: field4= 2&status=MQTTPUBLISH
pm open,type:2 0
Publish message: field4= 3&status=MQTTPUBLISH
Publish message: field4= 4&status=MQTTPUBLISH
Publish message: field4= 5&status=MQTTPUBLISH
Publish message: field4= 6&status=MQTTPUBLISH
Publish message: field4= 7&status=MQTTPUBLISH
Publish message: field4= 8&status=MQTTPUBLISH
Publish message: field4= 9&status=MQTTPUBLISH
Publish message: field4= 10&status=MQTTPUBLISH
Publish message: field4= 11&status=MQTTPUBLISH
Publish message: field4= 12&status=MQTTPUBLISH
Publish message: field4= 13&status=MQTTPUBLISH
Publish message: field4= 14&status=MQTTPUBLISH
Publish message: field4= 15&status=MQTTPUBLISH
Publish message: field4= 16&status=MQTTPUBLISH
Publish message: field4= 17&status=MQTTPUBLISH

我希望有人知道我做错了什么。

您订阅的主题与您要发布的主题不同。当您订阅 "channels/517055/subscribe/fields/field4" 时,您的发布主题是 "channels/517055/publish/V4ZW4Y01ZLFD5XYR"。

实际上,您的代码几乎是正确的,但是 loop() 函数正在执行到 Infinity。 基本上,代码卡在了循环函数中,所以这就是它无法订阅的原因。即使它也订阅了,循环函数将主导回调函数并且不会调用回调函数,它将充当 NULL

这是代码,我做了一些修改。试试看

**这段代码不会每次都发布payload,如果需要可以在client.loop()

之前的loop()中添加client.plublish
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "*****";
const char* password = "*****";
const char* mqtt_server = "mqtt.thingspeak.com";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Ciao sono la callback1\n");
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    Serial.print("Ciao sono la callback2\n");
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    Serial.print("Ciao sono la callback3\n");
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("channels/517055/publish/V4ZW4Y01ZLFD5XYR", "field5=7&status=MQTTPUBLISH");
      // ... and resubscribe
      client.subscribe("channels/517055/subscribe/fields/field4");
      Serial.print("Ciao sono subscribe 01\n");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  Serial.print("Ciao sono la callback 10\n");
  connectmqtt();
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }


  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "field4= %ld&status=MQTTPUBLISH", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
  }
     client.loop();
}

void connectmqtt()
{
  client.connect("ESP8266Client-");
  {
      Serial.println("connected");
      // Once connected, publish an announcement...

      // ... and resubscribe
      client.subscribe("channels/517055/subscribe/fields/field4");
       client.publish("channels/517055/publish/V4ZW4Y01ZLFD5XYR", msg);

       if (!client.connected()) 
  {
    reconnect();
  }
}
}

已解决

我贴的代码和@karan贴的代码是正确的。我遇到的问题是通过 thingspeak Broker 连接和 Thingspeak 文档解决的,当时没有更新。特别是需要通过 MQTT_APIKEY 和 USERNAME 与 mqtt 代理建立连接,即使是 PUBLIC 通道。

问题已解决,在连接步骤中传递这 2 个参数,如下所示:

    client.connect("ESP8266Client-", "Your_username", "MQTT_APIKEY");

非常感谢@karan 帮助了我,改进了我的代码。