Esp8266 can't connect to mqtt cloud broker hivemq

Hello, I connected my esp8266 to my wifi network successfuly, but I can’t connect to Hive mq cloud mqtt broker. on my serial port it says that
Attempting MQTT connection…failed, rc=-4 try again in 5 seconds
Attempting MQTT connection…failed, rc=-4 try again in 5 seconds
and so on…

esp8266 code (wemos d1 mini):

#ifdef ESP8266
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#else
#error "Board not found"
#endif

#include <PubSubClient.h>
#include <ModbusRTU.h>

#define SLAVE_ID 2
#define Relay1 0x001
#define Relay2 0x002
#define Relay3 0x003
#define Relay4 0x004
#define Relay5 0x005
#define Relay6 0x006
#define Relay7 0x007
#define Relay8 0x008

#if defined(ESP8266)
#include <SoftwareSerial.h>
 // SoftwareSerial S(D1, D2, false, 256);

// receivePin, transmitPin, inverse_logic, bufSize, isrBufSize
// connect RX to D2 (GPIO4, Arduino pin 4), TX to D1 (GPIO5, Arduino pin 4)
SoftwareSerial S(7, 16); // 3 - RX,     1 - TX  Wemos D1 Mini  ZMIANA NA GPIO13 (D7) - RX, GPIO15 (D8) - TX
#endif

int DE_RE = 5; //D4  (02) For MAX485 chip
ModbusRTU mb;

bool cbWrite(Modbus::ResultCode event, uint16_t transactionId, void * data) {
  #ifdef ESP8266
  Serial.printf_P("Request result: 0x%02X, Mem: %d\n", event, ESP.getFreeHeap());
  #else
  Serial.print("Request result: 0x");
  Serial.print(event, HEX);
  #endif
  return true;
}

// NETWORK CONNECTION

const char * ssid = "xxx";
const char * password = "x";
const char * mqtt_server = "7exxxx1a.s1.eu.hivemq.cloud"; // Local IP address of Raspberry Pi or cloud mqtt broker

const char * username = "xx";
const char * pass = "xxxx";

// Subscribed Topics

#define sub1 "device1/relay1"
#define sub2 "device1/relay2"
#define sub3 "device1/relay3"
#define sub4 "device1/relay4"
#define sub5 "device1/relay5"
#define sub6 "device1/relay6"
#define sub7 "device1/relay7"
#define sub8 "device1/relay8"

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE  (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

// Connecting to WiFi Router

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char * topic, byte * payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  if (!mb.slave()) {
    if (strstr(topic, sub1)) {
      for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
      }
      Serial.println();
      // Switch on the LED if an 1 was received as first character
      if ((char) payload[0] == '1') {

        mb.writeHreg(SLAVE_ID, 0x0001, 0x0100, cbWrite); // 0x001 - relay 1, 0x002 - relay 2 and so on 

        // 0x0100 - turn on relay, 0x0200 turn off relay 

      } else {

        mb.writeHreg(SLAVE_ID, 0x0001, 0x0200, cbWrite); // turn off the light

      }
    } else if (strstr(topic, sub2)) {
      for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
      }
      Serial.println();
      // Switch on the light if an 1 was received as first character
      if ((char) payload[0] == '1') {

        mb.writeHreg(SLAVE_ID, 0x0002, 0x0100, cbWrite);

      } else {

        mb.writeHreg(SLAVE_ID, 0x0002, 0x0200, cbWrite); // turn off the light

      }
    } else if (strstr(topic, sub3)) {
      for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
      }
      Serial.println();
      // Switch on the light if an 1 was received as first character
      if ((char) payload[0] == '1') {

        mb.writeHreg(SLAVE_ID, 0x0003, 0x0100, cbWrite);

      } else {

        mb.writeHreg(SLAVE_ID, 0x0003, 0x0200, cbWrite); // turn off the light

      }
    } else if (strstr(topic, sub4)) {
      for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
      }
      Serial.println();
      // Switch on the light if an 1 was received as first character
      if ((char) payload[0] == '1') {

        mb.writeHreg(SLAVE_ID, 0x0004, 0x0100, cbWrite);

      } else {

        mb.writeHreg(SLAVE_ID, 0x0004, 0x0200, cbWrite); // turn off the light

      }
    } else if (strstr(topic, sub5)) {
      for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
      }
      Serial.println();
      // Switch on the light if an 1 was received as first character
      if ((char) payload[0] == '1') {

        mb.writeHreg(SLAVE_ID, 0x0005, 0x0100, cbWrite);

      } else {

        mb.writeHreg(SLAVE_ID, 0x0005, 0x0200, cbWrite); // turn off the light

      }
    } else if (strstr(topic, sub6)) {
      for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
      }
      Serial.println();
      // Switch on the light if an 1 was received as first character
      if ((char) payload[0] == '1') {

        mb.writeHreg(SLAVE_ID, 0x0006, 0x0100, cbWrite);

      } else {

        mb.writeHreg(SLAVE_ID, 0x0006, 0x0200, cbWrite); // turn off the light

      }
    } else if (strstr(topic, sub7)) {
      for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
      }
      Serial.println();
      // Switch on the light if an 1 was received as first character
      if ((char) payload[0] == '1') {

        mb.writeHreg(SLAVE_ID, 0x0007, 0x0100, cbWrite);

      } else {

        mb.writeHreg(SLAVE_ID, 0x0007, 0x0200, cbWrite); // turn off the light

      }
    } else if (strstr(topic, sub8)) {
      for (int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
      }
      Serial.println();
      // Switch on the light if an 1 was received as first character
      if ((char) payload[0] == '1') {

        mb.writeHreg(SLAVE_ID, 0x0008, 0x0100, cbWrite);

      } else {

        mb.writeHreg(SLAVE_ID, 0x0008, 0x0200, cbWrite); // turn off the light

      }
    } else {
      Serial.println("unsubscribed topic");
    }
  }
}

// Connecting to MQTT broker

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), username, pass)) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe(sub1);
      client.subscribe(sub2);
      client.subscribe(sub3);
      client.subscribe(sub4);
      client.subscribe(sub5);
      client.subscribe(sub6);
      client.subscribe(sub7);
      client.subscribe(sub8);
    } 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(115200);
  setup_wifi();
  
  client.setServer(mqtt_server, 8883);
  client.setCallback(callback);
  
  #if defined(ESP8266)
  S.begin(9600, SWSERIAL_8N1);
  mb.begin( & S, DE_RE);
  mb.master();
  #endif
}

void loop() {
  mb.task();
  yield();
  
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

I use HiveMQ free cloud mqtt broker
In my HiveMQ console I got port 8883 (TLS ), and the url which I put on my node-red node mqtt-broker-node in server attribute and the port 8883 and clicked “Use TLS” and in the Secruity label I enter username and password and I put in on my esp’s code.
I got this on my hive mq console:
Hostname: xxxxxxxxxxxxxxxxxx
Port (TLS): 8883
Port (Websocket + TLS): 8884

esp8266 code related to connection to mqtt

const char * mqtt_server = "7e2xxxxxxxxxxxxx71a.s1.eu.hivemq.cloud"; // Local IP address of Raspberry Pi or cloud mqtt broker

const char * username = "xxxxxxxxxx";
const char * pass = "xxxxxxxxxxxxxxx";
// Connecting to MQTT broker

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), username, pass)) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe(sub1);
      client.subscribe(sub2);
      client.subscribe(sub3);
      client.subscribe(sub4);
      client.subscribe(sub5);
      client.subscribe(sub6);
      client.subscribe(sub7);
      client.subscribe(sub8);
    } 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() {
  setup_wifi();
  client.setServer(mqtt_server, 8883);
  client.setCallback(callback);
}

image

Beacause it is TLS I need to change something in my esp code. I don’t find any example OTI.

Did you see this thread? there are multiple examples for the esp8266

My example for verifying the root ca definitely worked for me, also with the PubSubClient library which you are using.

1 Like