ESP8266中通过MQTT与Raspberry Pi通信时的错误检测和错误处理

问题描述 投票:0回答:1

我正在使用MQTTESP8266Raspberry 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-pi mqtt raspberry-pi3 esp8266 nodemcu
1个回答
0
投票

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

来自文档的第二篇:

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

将字符串消息发布到指定的主题。

参数:

  • topic-要发布到的主题(const char [])
  • 有效负载-要发布的消息(const char [])

返回

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

因此,如果发布成功,client.publish()将返回true,如果发布失败,则返回false

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

© www.soinside.com 2019 - 2024. All rights reserved.