Connection to MQTT Server / esp8266

Hello, I got on my serial port info that ESP8266 (wemos d1 mini) can’t connect to MQTT Server ;/ [but It connectet to my WIFI successfuly]
Got it from COM5

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

#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(3, 1); //     3 - RX,     1 - TX       Wemos D1 Mini
#endif

int DE_RE = 5; // 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 = "xx";
const char * password = "xxxxx";
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";

// 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");
    }
  }
  mb.task();
  yield();
}

// 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);
  #if defined(ESP8266)
  S.begin(9600, SWSERIAL_8N1);
  mb.begin( & S, DE_RE);
  mb.master();
  #endif

  setup_wifi();
  client.setServer(mqtt_server, 8883);
  client.setCallback(callback);
}

void loop() {
  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.

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

Hi, sure that port 8883 is the correct port with the client.setserver command. All my mqtt implementations with ESP8266 and HA are using port 1883.

I got this on my hive mq console:
Hostname: xxxxxxxxxxxxxxxxxx
Port (TLS): 8883
Port (Websocket + TLS): 8884

esp code:

void setup() {
  setup_wifi();
  client.setServer(mqtt_server, 8883);
  client.setCallback(callback);
}

node-red

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

was trying it and I couldn’t create a new fingerprint. I just copied my Hostaname url to: GRC | SSL TLS HTTPS Web Server Certificate Fingerprints   and it didn’t create a fingerprint to my hostname’s url.

/ Change #2: Set the SHA1 fingerprint for the connection -->
static const char *fingerprint PROGMEM = "44 14 9A 3F C3 E9 F1 F3 84 1A B4 9F B6 4D 19 8A B2 92 31 D6";