我正在做一个用于演示目的的小项目。
我正在使用此处描述ESP8266
的功能将数据发布到 IoT 扩展。我正在发布到 s/us 主题,它工作正常。MQTT
现在我想要另一个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();
}