I can't connect to MQTT

Good morning, I’m new here and I come from the Fred.Sensetecnics migration.

I have two ESP8266 that subscribe to various topics. The problem is that from one of them I connect perfectly to MQTT and from the other I can’t.
At the beginning the code was exactly the same, I have been changing to do tests, with other credentials, with the same ones, creating a random client and I can’t find the solution.

I’m using WEMOS D1

At the moment the one that works I already have it migrated but I still have the other one in Fred and I must solve it before… 1/1/2023

Any help please!!!

Este el que no funciona

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <NTPClient.h>
#include <time.h>
#include <TZ.h>
#include <FS.h>
#include <LittleFS.h>
#include <CertStoreBearSSL.h>
#include <HX711.h>



const int DOUT=16;        //GPIO16 - D0
const int CLK=5;          //GPIO05 - D1
const byte lockPin=4;    // GPIO04 - D2 A este pin se le enviará un pulso ALTO cuando se ingrese la solución correcta para abrir cajón

// Modifica estos valores para tu red.
const char* ssid = "Livebox6-CBDD-24G";
//const char* ssid = "Livebox6-CBDD";
const char* password = "3T6nCTfHk59S";
//const char* ssid = "MOVISTAR_FB30";
//const char* password = "D5nPqVXoGo5NmNVCpQGG";
//const char* mqtt_server = "5bf0d6fcdbe44727bd5380b8cba06c15.s2.eu.hivemq.cloud";

// A single, global CertStore which can be used by all connections.
// Needs to stay live the entire time any of the WiFiClientBearSSLs
// are present.
BearSSL::CertStore certStore;

WiFiClientSecure espClient;
PubSubClient * client;
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (500)
char msg[MSG_BUFFER_SIZE];
int value = 0;
int contador = 0;
boolean juegoResuelto=false;

float calibration_factor = -11.59;

// Timers auxiliar variables
//long now = millis();
long lastMeasure = 0;

unsigned long tiempo1 = 0;
unsigned long tiempo2 = 0;
unsigned long tiempoSegundos = 0;

HX711 balanza;

void setup_wifi() {
  delay(10);
  // Arrancamos la conexión via WIFI a la red
  Serial.println();
  Serial.print("Conectando a... ");
  Serial.println(ssid);

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

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

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi conectada");
  Serial.print("Dirección IP: ");
  Serial.println(WiFi.localIP());
}

void setDateTime() {
  // You can use your own timezone, but the exact time is not used at all.
  // Only the date is needed for validating the certificates.
  configTime(TZ_Europe_Berlin, "pool.ntp.org", "time.nist.gov");

  Serial.print("Waiting for NTP time sync: ");
  time_t now = time(nullptr);
  while (now < 8 * 3600 * 2) {
    delay(100);
    Serial.print(".");
    now = time(nullptr);
  }
  Serial.println();

  struct tm timeinfo;
  gmtime_r(&now, &timeinfo);
  Serial.printf("%s %s", tzname[0], asctime(&timeinfo));
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Llega mensaje [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    char receivedChar = (char)payload[i];
    Serial.print(receivedChar);
    ctrlMensajes(topic, receivedChar);
  }
  Serial.println();
/*
  // Switch on the LED if the first character is present
  if ((char)payload[0] != NULL) {
    digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
    delay(500);
    digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH
  } else {
    digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH
  }
*/  
}

void ctrlMensajes(String topic, byte receivedChar){
  if (topic == "peso/desbloquear"){ 
    if(receivedChar == '1'){
      Serial.println("Control wifi resuelve");
      desbloquea();
    }
  }
  if (topic == "peso/reset"){
    if(receivedChar == '1'){
      Serial.println("Control wifi resetea");
      ESP.reset();
    }
  }
  if (topic == "peso/reiniciar"){
    if(receivedChar == '1'){
      Serial.println("Control wifi reinicia balanza");
      iniciarBalanza();
    }
  }
  
}

void reconnect() {
  // Bucle hasta reconectar
  while (!client->connected()) {
    Serial.print("Esperando conexión MQTT...");
    //String clientId = "ESP8266Client - MyClient";
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client->connect(clientId.c_str(), "g152710s", "D99d1b55")) {
      Serial.println("conectado");
      // Una vez conectado, publica...
      // ... y subscribe
      client->subscribe("peso/desbloquear");
      client->subscribe("peso/reiniciar");
      client->subscribe("peso/reset");
    } else {
      Serial.print("fallo, rc=");
      Serial.print(client->state());
      Serial.println(" intentalo de nuevo en 5 segundos");
      delay(5000);
    }
  }
}



void setup() {
  delay(50);
  Serial.begin(115200);
  delay(50);
  
  // Iniciar sensor
  balanza.begin(DOUT, CLK);  
  
  LittleFS.begin();
  setup_wifi();
  setDateTime();

  int numCerts = certStore.initCertStore(LittleFS, PSTR("/certs.idx"), PSTR("/certs.ar"));
  Serial.printf("Numero de certificados leidos: %d\n", numCerts);
  if (numCerts == 0) {
    Serial.printf("No hay certificados. ¿Ejecutó certs-from-mozilla.py y cargó el directorio LittleFS antes de ejecutarlo?\n");
    return; // Can't connect to anything w/o certs!
  }

  BearSSL::WiFiClientSecure *bear = new BearSSL::WiFiClientSecure();
  // Integrate the cert store with this connection
  bear->setCertStore(&certStore);

  client = new PubSubClient(*bear);
  
  client->setServer("5bf0d6fcdbe44727bd5380b8cba06c15.s2.eu.hivemq.cloud", 1883);
  client->setCallback(callback);

  Serial.print("Lectura del valor del ADC:  ");
  Serial.println(balanza.read());
  Serial.println("No ponga ningun  objeto sobre la balanza");
  Serial.println("Destarando...");
  Serial.println("...");

  pinMode(lockPin, OUTPUT);          // Pone el lockPin como salida
  Serial.println("CIERRO ELECTROIMAN");
  digitalWrite(lockPin, HIGH);

  iniciarBalanza();
  
}

void iniciarBalanza() {
  // Aplicar la calibración
  balanza.set_scale(calibration_factor);
  // Iniciar la tara
  // No tiene que haber nada sobre el peso
  balanza.tare();
  Serial.println("Listo para pesar");  
    
}


void loop() {
  if (!client->connected()) {
    reconnect();
  }
  client->loop();

  yield();
  
  unsigned long now = millis();
  // Publica nuevo peso cada 50 milesimas de segundo
  if (now - lastMsg > 50) {
    lastMsg = now;
    ++value;
    char peso[4];
    dtostrf(balanza.get_units(20), 3, 0, peso);
    client->publish("peso/gramos", peso);

    //int contador = 0;
    float pesoFinal = atof(peso);
    Serial.print("Peso: ");
    Serial.println(pesoFinal);
    
    //Si el peso es correcto, espero 3 segundos y si no cambia abro electroiman
    if (((pesoFinal>380) && (pesoFinal<420)) && (juegoResuelto==false)) {
      delay(1000);
      contador = contador + 1;
      Serial.print("PESO CORRECTO...");
      Serial.println(contador);
      if (contador > 3) {
        desbloquea();
      }
    } else {
      contador = 0;
    }
    
  //if (((pesoFinal>345) && (pesoFinal<360)) && (juegoResuelto==false)) {
    //    tiempo1 = millis();
    //    Serial.println("PESO CORRECTO...1");
    //    delay(2000);
    //    if (((pesoFinal>345) && (pesoFinal<360)) && (juegoResuelto==false)) {
    //        Serial.println("PESO CORRECTO...2");
    //        delay(2000);
    //        if (((pesoFinal>345) && (pesoFinal<360)) && (juegoResuelto==false)) {
    //            Serial.println("PESO CORRECTO...3");
    //            desbloquea();
    //        }
    //    }
    // }
  }
}

void desbloquea() {
  juegoResuelto=true;
  digitalWrite(lockPin, LOW);
  delay(50);
  digitalWrite(lockPin, HIGH);
}

Hi g152710s,

Are there any logging messages that give an indication of what is wrong on the device that is not connecting?

This information will help the community better assist. Thanks for your interest in HiveMQ Cloud and MQTT!

Seth - HiveMQ Support

Hello, no, it simply returns rc=2 indicating that it cannot connect to MQTT and retries after 5 seconds.

The same thing happened to me in the sketch that is working, it was resolved because I was connecting to a 5G Wi-Fi network, when I changed the network it started to work.

In this sketch I connect to the correct wifi network (the one from the previous sketch) but it doesn’t connect to the MQTT.

In both sketches I use the same username/password (credentials) to connect. Can’t use the same client to connect to a cluster?

Hi again g152710s,

Thanks for the additional information. MQTT return code 2 is technically “Connection Refused: Identifier rejected” (you may have already seen this in any previous research)

Using the same client credentials shouldn’t be an issue, but using the same client id could be causing this.

Is the code you included being used on both devices? I noticed in reconnect() you generate client ids like this:

    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);

With random functions, these are technically what is called “pseudo-random” (meaning it is an attempt at randomization but still using an algorithm, so it cannot ever be “truly” 100% random). I am wondering if you might still be getting the same client id for both since presumably the algorithm used is the same (it happens).

What happens if you do something like this: set the clientId variable to ESP8266Client1- on one client, and ESP8266Client2- on the other? Then you know whatever is generated with the random function won’t matter, there will still always be distinct clientIds being used.

Thanks,
Seth - HiveMQ Support

Thanks for the answer, but I think I have solved half the problem… I’ll tell you:
1.- I am already using two different clients
2.- I have tried to reproduce the problem at home, 2 different client IDs and it works correctly, connected to MQTT it works ok.
3.- However, at my client’s house, with the same software (I only change the WIFI user/password) I cannot connect to MQTT (rc=2).

I wonder if I have to configure something on the router… I have it at home from the factory…

At home I use a Movistar router. My client has an Orange Livebox

I have not found any incidence in this regard… I am desperate