【发布时间】:2015-11-26 10:45:19
【问题描述】:
我正在尝试通过了解 mqtt 来为我去年的主项目做准备。我已经在我的 RPi 上成功安装了 mosquitto,运行了测试发布和订阅(hello/world)。我还设法使用 android 应用程序 myMQTT 连接到代理,并且一切都可以正常运行。当我尝试使用 knolleary 的 PubSubClient 库使用带有以太网屏蔽的 arduino 连接到代理时,问题就开始了。一切都连接到一个交换机(路由器-Rpi-arduino)。我已经确保 arduino 有一个唯一的 IP 地址和 MAC 地址(我在路由器中检查了它)。服务器 ip-address 也是正确的,因为我正在使用它来 ssh 进入 Rpi。在 arduino 上运行的代码不断返回:
正在尝试 MQTT 连接...失败,rc=-4 5 秒后重试
返回码表示连接超时..
我在 pi 上运行新安装的 mosquitto,因此连接到代理不需要用户名或密码。有谁知道我在这里做错了什么?我已经在互联网上查找了一段时间,但我似乎无法弄清楚。
在 arduino 上运行的代码:
/*
Basic MQTT example
This sketch demonstrates the basic capabilities of the library.
It connects to an MQTT server then:
- publishes "hello world" to the topic "outTopic"
- subscribes to the topic "inTopic", printing out any messages
it receives. NB - it assumes the received payloads are strings not binary
It will reconnect to the server if the connection is lost using a blocking
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
achieve the same result without blocking the main loop.
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xAA };
IPAddress ip(192, 168, 1, 41);
IPAddress server(192, 168, 1, 26);
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("arduinoClient")) {
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("outTopic","hello world");
// ... and resubscribe
client.subscribe("hello/world");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(57600);
client.setServer(server, 1883);
client.setCallback(callback);
Ethernet.begin(mac, ip);
// Allow the hardware to sort itself out
delay(3000);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
【问题讨论】:
标签: raspberry-pi mqtt arduino-uno mosquitto