【问题标题】:mqtt error void callback/subscribed on arduinomqtt错误无效回调/在arduino上订阅
【发布时间】:2015-04-20 06:21:12
【问题描述】:

我正在使用我的 arduino 和 MQTT 云进行测试。 为了发布一切顺利,arduino 发布“hello world”

但是使用 void 回调函数没有任何反应。 使用我的 MQTT.fx 客户端,我订阅了主题“状态”和“突击队”。 在“状态”中,我看到 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;
}

【问题讨论】:

    标签: arduino mqtt subscribe


    【解决方案1】:

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

    1. 您为以太网分配静态 IP
    2. 连接到 mqtt 代理,并订阅一个主题
    3. 向 DHCP 查询新 IP。可能此时您的 Arduino 获得的 IP 与静态配置的 IP 不同,并且代理无法再访问您的 Arduino 以发布订阅的主题。

    修复您的以太网处理代码。我喜欢这个公式:

    // 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('.');
      } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 2014-10-21
      • 2016-06-10
      • 2015-02-13
      相关资源
      最近更新 更多