首页 > 解决方案 > 通过 MQTT 与 Raspberry Pi 通信时 ESP8266 中的错误检测和错误处理

问题描述

我正在使用MQTT在ESP8266Raspberry Pi之间进行通信,并且我正在将多个字符串从 ESP8266 发送到 Raspberry Pi。所以我想知道在向 Raspberry Pi 发送数据(字符串)时是否有任何功能或东西可以检测到错误(如果发生错误)。如果是这样,那么我该如何处理该错误

这是我在 NodeMCU 中的代码

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

SoftwareSerial NodeMCU(D2,D3);  

const char* ssid = "raspi-webgui";           // wifi ssid
const char* password =  "ChangeMe";         // wifi password
const char* mqttServer2= "192.168.43.164";  // IP adress Raspberry Pi
const int mqttPort = 1883;
const char* mqttUser = ""; 
const char* mqttPassword = "";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {

  Serial.begin(115200);
  NodeMCU.begin(4800);

  WiFi.begin(ssid, password);

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

if(!WiFi.status()){
    Serial.println("Connected to the WiFi network with ");
    }else{
      Serial.print("Failed to Connect to the raspberry pi with IP : ");
      Serial.println(mqttServer2);
      }


  client.setServer(mqttServer2, mqttPort);
  client.setCallback(callback);

  while (!client.connected()) {
    Serial.println("Connecting to raspberry pi...");

    if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {

      Serial.print("connected to the raspberry pi whith IP : ");
      Serial.println(mqttServer2);
      Serial.print("Loca IP Address of NodeMCU : ");
      Serial.println(WiFi.localIP());

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);

    }
  }

}



void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("Message from raspberry pi : ");

  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  String Topic_Str(topic);

  if( Topic_Str == "t_data"){

        String a_data = "Send String to raspberry pi.";

        //
        //
        //
        //
        //
        **// So here i am sending string to raspberry pi. Now how could i know that the raspberry pi had got the actual value or string
        // and there is no error , no bit has changed during communication.**
        //
        //
        //
        //
        //


        delay(5000);
        client.publish("a_data", (char*) a_data.c_str());

    }

}

void loop() {

    client.subscribe("t_data");
    delay(1000);
    client.loop();

}

标签: raspberry-pimqttraspberry-pi3esp8266nodemcu

解决方案


首先,消息回调延迟 5 秒是一个非常糟糕的主意,这些回调应该尽快运行,当收到消息时,您当前在每个 client.loop 之间注入 6 秒。

第二个来自文档:

布尔发布(主题,有效负载)

向指定主题发布字符串消息。

参数:

  • topic - 要发布到的主题 (const char[])
  • payload - 要发布的消息 (const char[])

退货

  • false - 发布失败、连接丢失或消息太大
  • true - 发布成功

如果发布成功并且失败,那么client.publish()将返回。truefalse

(我稍微修改了文档,它说返回类型应该是 int,但在检查 src 时它实际上是一个布尔值,并且对于列出的返回选项是有意义的)


推荐阅读