Arduino 上的 MQTT 不工作 [英] MQTT on Arduino not working

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

问题描述

我正在使用 Arduino Uno 和 Wi-Fi 扩展板.我正在尝试实现用于通信的 MQTT 协议,并且我为 Arduino 尝试了两个库.第一个是 Knolleary 的 PubSubClient:

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

值得注意的是,它一直在不断地重新连接.如您所见,在 loop() 中,我放置了一部分代码,如果连接丢失,它将再次连接和订阅.在串行监视器上,我收到信息:已重新连接!"每 2-3 秒发送一条消息.

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

这是我的代码:

/*带身份验证的基本 MQTT 示例- 连接到 MQTT 服务器,提供用户名和密码- 向主题outTopic"发布hello world"- 订阅主题inTopic"*/#include <WiFi.h>#include char ssid[] = "[已删除]";//您的网络 SSID(名称)char pass[] = "[已删除]";//你的网络密码int 状态 = WL_IDLE_STATUS;//Wifi 无线电的状态//使用适合您网络的值更新这些值.IP地址服务器(85、119、83、194);WiFiClient 无线客户端;void callbackFunc(char* topic, byte* payload, unsigned int length) {Serial.println("收到测试消息");/*Serial.println();Serial.println("================收到消息================================");Serial.print("主题:");Serial.print(主题);Serial.println();Serial.println((const char *) payload);*/}PubSubClient 客户端(服务器,1883,callbackFunc,WifiClient);无效设置(){延迟(2000);Serial.begin(9600);Serial.println("开始......");Serial.println("正在初始化无线网络...");//检查屏蔽是否存在:如果(WiFi.status()== WL_NO_SHIELD){Serial.println("WiFi 屏蔽不存在");}//尝试使用 WPA2 加密连接:Serial.println("正在尝试连接到 WPA 网络...");status = WiFi.begin(ssid, pass);//如果你没有连接,停在这里:如果(状态!= WL_CONNECTED){Serial.println("无法连接wifi");同时(真);}//如果你已连接,打印出成功信息别的Serial.println("连接到网络");如果(client.connect(arduinoClient")){Serial.println("已连接服务器!正在发送消息...");client.publish("randy/test","hello world");client.subscribe("兰迪/测试");Serial.println("已发送!");}别的{Serial.println("错误:无法连接到MQTT服务器!");Serial.println(client.state());}}空循环(){客户端循环();延迟(1000);如果 (!client.connected()){if(!client.connect("arduinoClient")){Serial.println("错误:无法连接到MQTT服务器!");Serial.println(client.state());}别的{client.subscribe("兰迪/测试");Serial.println("信息:重新连接!");}}}

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

解决方案

如评论中所述

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

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.

Here is my code:

/*
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!");
    }
  }
}

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:

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

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 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.

Here's my code:

/*
 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?

解决方案

As mentioned in the comments

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天全站免登陆