Arduino上的MQTT无法正常工作 [英] MQTT on Arduino not working

查看:202
本文介绍了Arduino上的MQTT无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Arduino Uno和Wi-Fi防护罩.我正在尝试实现用于通信的MQTT协议,并且尝试了Arduino的两个库.第一个是Knolleary的PubSubClient: http://pubsubclient.knolleary.net/.我对原始示例进行了一些修改,以使用WiFi模块代替以太网.发送有效,但并非每次都能发送(有时发送消息,有时不发送消息).但是通过回调函数接收完全无效.

I'm using Arduino Uno and Wi-Fi shield. I'm trying to implement MQTT protocol for communication and I tried two libraries for Arduino. First one is Knolleary's PubSubClient: http://pubsubclient.knolleary.net/ . I modified original example a little bit to use WiFi module instead of ethernet. Sending works but not every time (sometimes, the message is sent and sometimes not). But receiving via callback function doesn't work at all.

这是我的代码:

/*
Basic MQTT example with Authentication

  - connects to an MQTT server, providing username
    and password
  - publishes "hello world" to the desired topic
  - subscribes to the desired topic
*/

#include <WiFi.h>
#include <PubSubClient.h>

char ssid[] = "[DELETED]";     //  your network SSID (name) 
char pass[] = "[DELETED]";    // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

// Update these with values suitable for your network.
IPAddress server(85, 119, 83, 194);
WiFiClient WifiClient;

void callbackFunc(char* topic, byte* payload, unsigned int length) {
  Serial.println("test message received");

  /*Serial.println();
  Serial.println("=============== MESSAGE RECEIVED       ================================");
  Serial.print("Topic: ");
  Serial.print(topic);
  Serial.println();
  Serial.println((const char *) payload);*/
}

PubSubClient client(server, 1883, callbackFunc, WifiClient);

void setup()
{
  delay(2000);

  Serial.begin(9600);
  Serial.println("Starting....");

  Serial.println("Initializing Wifi...");

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");    
  }

  // attempt to connect using WPA2 encryption:
  Serial.println("Attempting to connect to WPA network...");
  status = WiFi.begin(ssid, pass);

  // if you're not connected, stop here:
  if (status != WL_CONNECTED) {
    Serial.println("Couldn't get a wifi connection");
    while(true);
  }

  // If you are connected, print out success message
  else
    Serial.println("Connected to network");

  if (client.connect("arduinoClient")) {
    Serial.println("Connected to server! Sending message...");
    client.publish("randy/test","hello world");
    client.subscribe("randy/test");
    Serial.println("Sent!");
  }

  else
  {
    Serial.println("ERROR: Cannot connect to MQTT server!");
    Serial.println(client.state());
  }
}

void loop()
{
  client.loop();
  delay(1000);

  if (!client.connected())
  {
    if(!client.connect("arduinoClient"))
    {
      Serial.println("ERROR: Cannot connect to MQTT server!");
      Serial.println(client.state());
    }

    else
    {
      client.subscribe("randy/test");
      Serial.println("INFO: reconnected!");
    }
  }
}

如您所见,我正在使用 http://test.mosquitto.org/测试.我还在Ubuntu上使用mosquitto,我在其中订阅了相同的主题,而我从何处(另一个终端窗口)发布了相同的主题.这是两个窗口的图片:

As you can see, I'm using http://test.mosquitto.org/ for testing. I'm also using mosquitto on Ubuntu where I'm subscribed to the same topic and from where (another terminal window) I'm publishing to the same topic. Here is the picture of both windows:

如您所见,已成功(但并非每次都)收到来自Arduino的"hello world"消息,并且当我从另一个窗口发布"bla"消息时,已成功在mosquitto上收到了该消息(图像上),但未在Arduino上成功收到该消息.我的代码有问题吗?我在这里发现了类似的问题: Arduino Knolleary PubSubClient将发布消息但无法收到他们

As you can see, "hello world" message from Arduino is received successfully (but not every time), and when I publish "bla" message from another window, it's successfully received on mosquitto (on image) but NOT on Arduino. Is there something wrong with my code or? I found similar problem here: Arduino Knolleary PubSubClient will publish messages but can't receive them

值得注意的是,它一直一直保持着重新连接的状态.如您所见,在loop()中,我放置了一部分代码,如果连接断开,它将连接并再次订阅.在串行监视器上,我得到信息:重新连接!"每2-3秒发送一次消息.

It's worth noticing that it keeps getting reconnected all the time. As you can see, in loop() I put a part of code which will connect and subscribe again if connection is lost. On Serial Monitor I get "INFO: Reconnected!" message every 2-3 seconds.

Adafruit库 然后我尝试了Adafruit库,但是它根本无法连接!我从他们的示例中尝试使用test.mosquitto.org和io.adafruit.com,但是我一直在获取连接失败!"错误.我尝试过进行许多更改和组合,但到目前为止还没有运气.一旦我设法获得无法订阅"而不是连接失败",但这只是一次又一次使用相同的代码,我又一次获得了连接失败".

Adafruit library Then I tried the Adafruit library, but it won't connect at all! I tried with test.mosquitto.org and with io.adafruit.com from their example, but I just keep getting "Connection failed!" error. I tried making many changes and combinations but no luck so far. Once I managed to get "Failed to subscribe" instead of "Connection failed" but this was only once and next time with the same code I get "Connection failed" again.

这是我的代码:

/*
 Basic MQTT example with Authentication

  - connects to an MQTT server, providing username
    and password
  - publishes "hello world" to the topic "outTopic"
  - subscribes to the topic "inTopic"
*/

#include <WiFi.h>
#include <PubSubClient.h>

char ssid[] = "[DELETED]";     //  your network SSID (name) 
char pass[] = "[DELETED]";    // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

// Update these with values suitable for your network.
IPAddress server(85, 119, 83, 194);
WiFiClient WifiClient;

void callbackFunc(char* topic, byte* payload, unsigned int length) {
  Serial.println("test message received");

  /*Serial.println();
  Serial.println("=============== MESSAGE RECEIVED ================================");
  Serial.print("Topic: ");
  Serial.print(topic);
  Serial.println();
  Serial.println((const char *) payload);*/
}

PubSubClient client(server, 1883, callbackFunc, WifiClient);

void setup()
{
  delay(2000);

  Serial.begin(9600);
  Serial.println("Starting....");

  Serial.println("Initializing Wifi...");

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");    
  }

  // attempt to connect using WPA2 encryption:
  Serial.println("Attempting to connect to WPA network...");
  status = WiFi.begin(ssid, pass);

  // if you're not connected, stop here:
  if (status != WL_CONNECTED) {
    Serial.println("Couldn't get a wifi connection");
    while(true);
  }

  // Ff you are connected, print out success message
  else
    Serial.println("Connected to network");

  if (client.connect("arduinoClient")) {
    Serial.println("Connected to server! Sending message...");
    client.publish("randy/test","hello world");
    client.subscribe("randy/test");
    Serial.println("Sent!");
  }

  else
  {
    Serial.println("ERROR: Cannot connect to MQTT server!");
    Serial.println(client.state());
  }
}

void loop()
{
  client.loop();
  delay(1000);

  if (!client.connected())
  {
    if(!client.connect("arduinoClient"))
    {
      Serial.println("ERROR: Cannot connect to MQTT server!");
      Serial.println(client.state());
    }

    else
    {
      client.subscribe("randy/test");
      Serial.println("INFO: reconnected!");
    }
  }
}

您知道这些库或我的代码有什么问题吗?

Any idea what's wrong with those libraries or my code?

推荐答案

如评论中所述

在公共经纪人上使用示例代码时,请确保将客户端ID更改为随机值,因为与其他人发生冲突的几率很高.因为客户端ID必须是唯一的,否则它们将引起重新连接风暴

When using example code on public brokers make sure you change the client id to something random as the odds of clashing with somebody else are pretty high. Because client ids have to be unique else they will cause a reconnection storm

这篇关于Arduino上的MQTT无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆