2017-07-01 202 views
0

我第一次使用RabbitMQ和Arduino,我需要发布数据。所以我使用了PubSubCLient类。这是代码:RabbitMQ与Arduino Uno

#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(); 
} 

我总是收到一个错误,没有连接。我认为这是因为我不知道如何在RabbitMQ上使用Arduino。

+0

是您的机器/ IDE连接到Arduino? – Parker

+0

是的,我一直在arduino ide上没有连接错误 –

回答

0

这两条线都是你的烦恼来源:

byte server[] = { 127, 0, 0, 1 }; 

    ... 

    PubSubClient client(server, 5672, callback, ethClient); 

服务器[]必须指定的RabbitMQ服务器的地址。 127.0.0.1是localhost的地址。这是永远不可路由的。

此外,PubSubClient是MQTT客户端,而不是RabbitMQ(AMQP)客户端。因此,您指定的AMQP端口5672不起作用。

您需要启用和RabbitMQ的配置MQTT适配器,然后使用适当的MQTT端口,通常为1883

+0

我同意你的意见,这只是一个例子,我使用服务器的真实IP地址,但仍然没有连接 –

+0

并且你安装了MQTT适配器并更改了端口? –

+0

我改变服务器,蚊子和工作就好了 –