Ana*_*har 4 arduino rabbitmq consumer producer arduino-uno
我是第一次在 Arduino 上使用 RabbitMQ,我需要发布数据。所以我使用了 PubSubCLient 类。这是代码:
#include <SPI.h>
#include <PubSubClient.h>
#include <Dhcp.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <Dns.h>
#include <EthernetServer.h>
#include <EthernetClient.h>
//declare variables
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xDE, 0xDE, 0xDD };
byte server[] = { 127, 0, 0, 1 };
byte ip[] = { 192, 168, 1, 22 };
String stringone = "localhost";
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println(topic);
//convert byte to char
payload[length] = '\0';
String strPayload = String((char*)payload);
Serial.println(strPayload);
int valoc = strPayload.lastIndexOf(',');
String val = strPayload.substring(valoc+1);
Serial.println(val);
}
EthernetClient ethClient;
PubSubClient client(server, 5672, callback, ethClient);
void setup() {
// client is now configured for use
Serial.begin(9600);
Serial.println("==STARTING==");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
boolean con = client.connect("arduinoMQTT123");
while(con != 1) {
Serial.println("no con-while");
con = client.connect("arduinoMQTT123");
}
if(con) {
Serial.println("got con");
client.subscribe("/v2/feeds/FEED_ID.csv");
} else Serial.println("no con");
}
void loop() {
client.loop();
}
Run Code Online (Sandbox Code Playgroud)
我一直收到错误,没有连接。我想那是因为我不知道如何将 Arduino 与 RabbitMQ 一起使用。
这两行是你麻烦的根源:
byte server[] = { 127, 0, 0, 1 };
...
PubSubClient client(server, 5672, callback, ethClient);
Run Code Online (Sandbox Code Playgroud)
server[] 必须指定您的 RabbitMQ 服务器的地址。127.0.0.1 是本地主机的地址。这永远是不可路由的。
此外,PubSubClient 是 MQTT 客户端,而不是 RabbitMQ (AMQP) 客户端。因此,您指定的 AMQP 端口 5672 将不起作用。
您需要在 RabbitMQ 中启用和配置 MQTT 适配器,然后使用适当的 MQTT 端口,通常是 1883。
| 归档时间: |
|
| 查看次数: |
4149 次 |
| 最近记录: |