mqtt错误无效回调/订阅arduino

时间:2015-04-20 06:21:12

标签: arduino mqtt subscribe

我正在测试我的arduino和MQTT云。 对于发布一切顺利,arduino发布“hello world”

但是使用void回调函数没有任何反应。 使用我的MQTT.fx客户端,我订阅了“status”和“commando”主题。 在“状态”,我看到arduino是一个现场。

当我使用MQTT.fx客户端发布主题“commando”时。 我可以看到它到达我的客户端,但不是在arduino的串行监视器中。

为什么不使用void回调函数?

#include <SPI.h>
#include <PubSubClient.h>
#include <Ethernet.h>

#define server "m20.cloudmqtt.com"
int port = 13365;

// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
byte ip[]     = { 192, 168, 0, 120 };

unsigned long time;
char message_buff[100];

EthernetClient ethClient;
PubSubClient client(server, port, callback, ethClient);

void setup()
{ 
  // init serial link for debugging
  Serial.begin(115200);
  
  Ethernet.begin(mac, ip);
  if (client.connect("arduino-MQTT","test","test")) {
    client.publish("/arduino/status/","hello world");
    client.subscribe("/arduino/commando/");
    Serial.println("Connected");
  }
  
  if (Ethernet.begin(mac) == 0)
  {
      Serial.println("Failed to configure Ethernet using DHCP");
      return;
  }
}

void loop()
{
  // MQTT client loop processing
  client.loop();
}


void callback(char* topic, byte* payload, unsigned int length) {
 
  if (strcmp(topic, "/arduino/commando/") == 0) {
    String msg = toString(payload, length);
    Serial.println(msg);
  }else{
    Serial.println("arduino topic not found");
  }  
}

//
// toString function
//
String toString(byte* payload, unsigned int length) {
  int i = 0;
  char buff[length + 1];
  for (i = 0; i < length; i++) {
    buff[i] = payload[i];
  }
  buff[i] = '\0';
  String msg = String(buff);
  return msg;
}

1 个答案:

答案 0 :(得分:1)

我刚刚使用RSMB代理测试了您的代码并且它可以工作。我的计算机上没有DHCP,因此我不得不注释掉DHCP处理代码 - Ethernet.begin(mac)。我认为这就是你的错误所在。这是因为:

  1. 您为以太网分配静态IP
  2. 连接到mqtt代理,并订阅主题
  3. 查询DHCP以获取新IP。可能在这一点上你的Arduino获得了一个不同于静态配置的IP,并且经纪人无法再访问你的Arduino以发布订阅的主题。
  4. 修复以太网处理代码。我喜欢这个公式:

    // Start the Ethernet connection:
    Serial.println(F("Querying DHCP"));
    if ( Ethernet.begin( mac ) == 0 ) {
        Serial.println(F("DHCP failed, fallback to static IP"));
        // When DHCP fails, fallback to static configuration ;
        Ethernet.begin( mac, ip ) ;
    }
    printIp() ;  
    

    和printIp函数:

    void printIp() {
      // Print local IP address
      Serial.print(F("My IP "));
      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('.');
      } 
    }