首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用PubSubClient.h回调函数的NodeMCU esp8266被忽略

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

Stack Overflow用户
提问于 2018-06-22 19:39:41
回答 3查看 3K关注 0票数 0

编辑:要发布和订阅的主题是正确的,即使它们看起来不同。对于我的发布,我在字段4上写作。此外,我还在sub/pub模式下使用相同的主题运行MQTT.fx,它工作得很好。

我想在我的NodeMCU和esp8266中使用mqtt。我让simple MQTT example适应了我的最小项目。在我的代码中(附在下面),我试图发布和订阅一个ThingSpeak频道。publish函数没有任何问题,它在每次调用时都会发布。但是回调函数被忽略了,我的代码永远不会进入回调函数。

要在这里提供更多信息,请参阅我的设置:

代码语言:javascript
复制
#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);
  }
}

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

代码语言:javascript
复制
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

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-06-29 15:37:56

已解决的

我发布的代码和@karan发布的代码都是正确的。我遇到的问题是通过thingspeak代理连接和Thingspeak文档实现的,当时还没有更新。尤其是需要传递MQTT_APIKEY和用户名来建立与mqtt broker连接,即使使用公共通道也是如此。

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

代码语言:javascript
复制
    client.connect("ESP8266Client-", "Your_username", "MQTT_APIKEY");

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

票数 0
EN

Stack Overflow用户

发布于 2018-06-23 05:09:56

您正在订阅的主题与要发布到的主题不同。您的发布主题是"channels/517055/publish/V4ZW4Y01ZLFD5XYR“,而您订阅的是”channels/517055/subscribe/field4/field4“。

票数 0
EN

Stack Overflow用户

发布于 2018-06-23 17:12:09

实际上,您的代码几乎是正确的,但是loop()函数正在无限地执行。基本上,代码卡在循环函数中,这就是它不能订阅的原因。即使它也被订阅,循环函数也将控制回调函数,回调函数将不会被调用,它将充当NULL

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

**此代码不会每次都发布有效负载,如果需要,您可以在client.loop()之前添加循环中的client.plublish ()。

代码语言:javascript
复制
#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();
  }
}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50987129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档