我想在家里进行 MQTT 通信。我有带 MQTT Broker (mosquitto) 的 RPI4,并试图通过 W5500 lite 以太网模块连接 Arduino mega。
MQTT 代理通过手机中的“MyMQTT”应用程序和 Openhab 应用程序进行测试 - 它的工作就像一个魅力。
我在循环后使用 PubSubClient 库中的 delay() 示例(我如何在此处的另一个主题中找到...):
/*
Basic MQTT example
*/
#include \<SPI.h\>
#include \<Ethernet3.h\>
#include \<PubSubClient.h\>
// Update these with values suitable for your network.
byte mac\[\] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02};
IPAddress ip(192, 168, 0, 101);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 0, 0);
void callback(char\* topic, byte\* payload, unsigned int length) {
Serial.print("Message arrived \[");
Serial.print(topic);
Serial.print("\] ");
for (int i=0;i\<length;i++) {
Serial.print((char)payload\[i\]);
}
Serial.println();
}
EthernetClient ethClient;
PubSubClient client(ethClient);
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient9", "user", "pass")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic","hello world");
// ... and resubscribe
client.subscribe("/hello");
delay(100);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(200);
}
}
}
void setup() {
Serial.begin(115200);
client.setServer("192.168.0.99", 1883);
client.setCallback(callback);
Ethernet.begin(mac, ip);
// Allow the hardware to sort itself out
delay(1500);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
delay(100);
}
Arduino 仍在重新连接 - 我认为这是一个问题(mosquitto.log):
看起来
client.connected()
经常是假的。但为什么? :-(