我正在做一个演示用的小项目。
我正在使用ESP8266将数据发布到IoT扩展,该扩展使用MQTT功能,如here所述。我正在发布s/us主题,它工作得很好。
现在我想让另一个ESP8266订阅相同的频道。
这个是可能的吗?如果是,那么正确的方法是什么呢?我已经尝试订阅s/us主题(使用arduino pubsubclient lib),但这不起作用,并且我找不到有关此主题的任何信息。
以下是请求的代码:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "ssid";
const char* password = "Password";
const char* mqtt_Server = "mciotextension.eu-central.mindsphere.io";
const int mqtt_Port = 1883;
const char* mqtt_user = "User";
const char* mqtt_password = "Password";
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void reconnect() {
// Loop until reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "0da4cfbb-4ea2-488d-8a89-739ec04acf1e";
// Attempt to connect
if (client.connect(clientId.c_str(), mqtt_user, mqtt_password)) {
Serial.println("connected");
} else {
Serial.print("failed, rc= ");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to WiFi network");
client.setServer(mqtt_Server, mqtt_Port);
reconnect();
client.setCallback(callback);
client.subscribe("s/us"); //I also tryed s/ds
}
void loop() {
client.loop();
delay(1000);
reconnect();
} 发布于 2019-01-23 06:41:22
现在,我想让另一个ESP8266订阅相同的频道。
这个是可能的吗?
是-通过连接PC上运行的独立MQTT客户端,您可以确认已正确配置发布客户端和代理。然后让MQTT客户端订阅该通道。
您的订阅代码至少有一个潜在问题。它只在第一次连接到代理时订阅主题。默认的PubSubClient连接将使用清洁会话-当客户端断开连接并重新连接时,以前的任何订阅都不会持久。
因此,如果订阅者失去了与代理的初始连接,那么它将不会在后续连接中订阅该主题。
您可以通过将订阅代码移动到重新连接函数来修复此问题,如下面的代码片段所示。
if (client.connect(clientId.c_str(), mqtt_user, mqtt_password)) {
Serial.println("connected");
client.subscribe("s/us");
} else {我还建议您在设置第一次连接之前调用setCallback()。例如在setup()中
client.setServer(mqtt_Server, mqtt_Port);
client.setCallback(callback);
reconnect();https://stackoverflow.com/questions/54303284
复制相似问题