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



我正在使用MQTTESP8266Raspberry Pi之间进行通信,并且我正在从ESP8266向Raspberrry 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();
}

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

文档中的第二个:

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

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

参数:

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

返回

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

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

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

相关内容

最新更新