Arduino Knolleary PubSubClient将发布消息但无法接收消息

时间:2013-10-04 18:06:19

标签: arduino mqtt

我正在使用Knolleary PubSubClient与我的MQTT服务器建立连接。在没有太多工作之后,我已经能够成功进行身份验证并建立连接。我甚至可以向主题发布消息。但是,我遇到的问题是我可以订阅主题并且没有错误,但是当我发布到该主题时(来自我的Mac上的mosquitto),回调没有被调用,并且订阅主题的消息似乎没有出现收到。我曾尝试同时运行同一主题的mosquitto订阅,并确实收到已发布的消息。不确定我的回调代码中是否存在问题或此处发生了什么。任何帮助,将不胜感激。 Arduino代码如下:

/*
 Basic MQTT example 

  - connects to an MQTT server
  - publishes "hello world" to the topic "outTopic"
  - subscribes to the topic "inTopic"
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte server[] = { 10, 2, 63, 123 };
byte ip[]     = { 192, 168, 1, 10 };


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, 1883, callback, ethClient);

void setup()
{
  Serial.begin(19200);
  Serial.println("==STARTING==");

  // start the Ethernet connection:
  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("."); 
  }

  //delay(500);
  boolean con = client.connect("1", "3snzzon5dyade:abc", "OBSCURED_FOR_SEC");
  while(con != 1){
    Serial.println("no con-while");
     con = client.connect("1", "3snzzon5dyade:abc", "OBSCURED_FOR_SEC");
  }
  //Serial.println(con);
  if(con){
    Serial.println("got con");
    client.publish("testq","hello world");
    client.subscribe("testq");
  }else Serial.println("no con");

}

void loop()
{
  client.loop();
}

就像我说的那样,我可以看到蚊子一切正常。我甚至尝试过匹配client_ids而没有运气。任何帮助或想法将不胜感激。

1 个答案:

答案 0 :(得分:-1)

您的订阅主题“testq”必须位于

之类的数组中
char testq[] = {'t', 'e', 's', 't', 'q', '\0'};

请务必使用'\ 0'

完成数组

然后您订阅:

client.subscribe(testq);