2017-07-01 215 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

我改變服務器,蚊子和工作就好了 –