【问题标题】:Problem with MQTT server: Attempting MQTT connection...failed, rc=-2 try again in 5 secondsMQTT 服务器问题:尝试 MQTT 连接...失败,rc=-2 5 秒后重试
【发布时间】:2022-07-20 22:38:38
【问题描述】:

我在 rPi 上托管 MQTT 服务器,服务器工作正常,我能够使用不同的机器 (PC-ubuntu) 连接到它,但 arduino(wemos d1 mini) 存在问题。 我已经在配置文件中将 allow_anonymous 设置为 true,然后运行 ​​sudo ufw allow 1883。 似乎没有什么对我有用:c

#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Adafruit_INA219.h>
#include "arduino_secrets.h"
// Connect to the WiFi
const char* ssid = SECRET_SSID;                          
const char* password = SECRET_PASS;               
//const char* mqtt_server = "192.168.0.158"; //at first was using this 


IPAddress ip(192, 168, 1, 100); //then switched to this, but with no effect 
IPAddress server(192, 168, 0, 158);
IPAddress mqtt_server = {192, 168, 0, 158};  
 
WiFiClient espClient;
PubSubClient client(espClient);
 
const byte ledPin = D4; // digital pin 4 on a weMos D1 mini is next to ground so easy to stick a LED in.
 
void callback(char* topic, byte* payload, unsigned int length) {
 Serial.print("Message arrived [");
 Serial.print(topic);
 Serial.print("] ");
 for (int i=0;i<length;i++) {
  char receivedChar = (char)payload[i];
  Serial.print(receivedChar);
  if (receivedChar == '1')
  digitalWrite(ledPin, HIGH);
  if (receivedChar == '0')
   digitalWrite(ledPin, LOW);
  }
  Serial.println();
}
 void reconnect() {
 // Loop until we're reconnected
 while (!client.connected()) {
 Serial.print("Attempting MQTT connection...");
 // Attempt to connect
 if (client.connect("DUPADUPA")) {
  delay(2000);
  Serial.println("connected");
  client.subscribe("real_unique_topic");
 } else {
  Serial.print("failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 5 seconds");
  // Wait 5 seconds before retrying
  delay(5000);
  }
 }
}
void setup()
{
 Serial.begin(9600);
 
 client.setServer(mqtt_server, 1883);
 client.setCallback(callback);
 
 pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, HIGH);
 delay(5000);
 digitalWrite(ledPin, LOW);
}
 
void loop()
{
 if (!client.connected()) {
  reconnect();
 }
 client.loop();
}

还检查了另一个库:,但出现同样的错误。

PS:也尝试过这里的代码:https://docs.arduino.cc/tutorials/uno-wifi-rev2/uno-wifi-r2-mqtt-device-to-device - 适用于“test.mosquitto.org”,但不适用于 rPi ip

【问题讨论】:

  • 您好,如果您已经找到答案,请标记正确答案或关闭此问题。谢谢
  • 您永远不会与 WiFi 建立连接。您的客户端在 WiFi 之上运行。

标签: c++ arduino-esp8266


【解决方案1】:

我也有同样的问题。我的 Nodemcu 工作正常,但突然停止工作。我检查了服务器、端口,还检查了与 pc 的连接一切正常,但我无法连接节点

【讨论】:

    猜你喜欢
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多