【问题标题】:Attempting MQTT connection...failed, rc=-4 try again in 5 seconds正在尝试 MQTT 连接...失败,rc=-4 5 秒后重试
【发布时间】:2019-10-02 16:27:44
【问题描述】:

我使用 aREST 访问我的 NODEMCU,但它在串行监视器上显示“正在尝试 MQTT 连接...失败,rc=-4 5 秒后重试”

我的代码:

// Control ESP8266 anywhere

// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
#include <aREST.h>

// Clients
WiFiClient espClient;
PubSubClient client(espClient);

// Create aREST instance
aREST rest = aREST(client);

// Unique ID to identify the device for cloud.arest.io
char* device_id = "aliziveh79";

// WiFi parameters
const char* ssid = "Samsung J7";
const char* password = "Movahed12341234";

// Functions
void callback(char* topic, byte* payload, unsigned int length);

void setup(void)
{
  // Start Serial
  Serial.begin(115200);

  // Set callback
  client.setCallback(callback);

  // Give name and ID to device
  rest.set_id(device_id);
  rest.set_name("relay_anywhere");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Set output topic
  char* out_topic = rest.get_topic();

}

void loop() {

  // Connect to the cloud
  rest.loop(client);

}

// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {

  rest.handle_callback(client, topic, payload, length);

}

我使用 aREST 访问我的 NODEMCU,但它在串行监视器上显示 Attempting MQTT connection...failed, rc=-4 try again in 5 seconds"

【问题讨论】:

    标签: arduino mqtt


    【解决方案1】:

    Return code -4 是尝试连接到代理的超时

    // Possible values for client.state()
    #define MQTT_CONNECTION_TIMEOUT     -4
    #define MQTT_CONNECTION_LOST        -3
    #define MQTT_CONNECT_FAILED         -2
    #define MQTT_DISCONNECTED           -1
    #define MQTT_CONNECTED               0
    #define MQTT_CONNECT_BAD_PROTOCOL    1
    #define MQTT_CONNECT_BAD_CLIENT_ID   2
    #define MQTT_CONNECT_UNAVAILABLE     3
    #define MQTT_CONNECT_BAD_CREDENTIALS 4
    #define MQTT_CONNECT_UNAUTHORIZED    5
    

    这很可能意味着您的代理地址错误(但我看不到您在提供的代码中指定的位置)

    【讨论】:

      【解决方案2】:

      当你连接客户端时,你必须更改设备的名称:

       if (client.connect("CHANGE_THIS_IT_HAS_TO_BE_DIFFERENT_FOR_EACH_DEVICE"))
      

      我使用 MAC 地址来动态更改它

      【讨论】:

      • 为什么客户端 id 冲突会导致超时错误?
      • 我真的不知道...但是当我更改“客户端名称”时,连接成功
      猜你喜欢
      • 2022-12-10
      • 2022-07-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多