[SOLVED]NodeMCU can't connect to MQTT

Hello, I have the following code for my NodeMCU which had been working ok for a few days:

#include <PubSubClient.h>
#include <UbidotsESPMQTT.h>
#include <DHT.h>

#define DHTPIN 13            //what pin we're connected to
#define DHTPIN2 5
#define DHTPIN3 4
#define DHTPIN4 0`1
#define DHTTYPE DHT21       //DHT 21  (AM2301)
  
DHT dht(DHTPIN, DHTTYPE);   //Initialize DHT sensor for normal 16mhz Arduino
DHT dht2(DHTPIN2, DHTTYPE);
DHT dht3(DHTPIN3, DHTTYPE);
float hum;  //Stores humidity value
float temp; //Stores temperature value
float hum2;  //Stores humidity value
float temp2; //Stores temperature value
float hum3;  //Stores humidity value
float temp3; //Stores temperature valu

#define TOKEN "......" // Your Ubidots TOKEN
#define WIFINAME "..." //Your SSID
#define WIFIPASS "..." // Your Wifi Pass

Ubidots client(TOKEN);

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++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void setup() {

  dht.begin();
  dht2.begin();
  dht3.begin();
  
  // put your setup code here, to run once:
  client.ubidotsSetBroker("industrial.api.ubidots.com"); 
  client.setDebug(true);
  Serial.begin(9600);
  client.wifiConnection(WIFINAME, WIFIPASS);
  client.begin(callback);
  }

void loop() {
  // put your main code here, to run repeatedly:
  if(!client.connected()){
      client.reconnect();
  }

  hum = dht.readHumidity()-3.5;
  temp= dht.readTemperature();
  hum2 = dht2.readHumidity();
  temp2= dht2.readTemperature();
  hum3 = dht3.readHumidity()-1;
  temp3= dht3.readTemperature();
  client.add("temperature", temp);
  client.add("temperature2", temp2);
  client.add("temperature3", temp3); 
  
  client.ubidotsPublish("Node_Home");

  delay(60000);
  client.add("humidity", hum);
  client.add("humidity2", hum2);
  client.add("humidity3", hum3); 

  client.ubidotsPublish("Node_Home");
 
  client.loop();

  delay(60000);

}

Initially, the code worked but after some hours (never for a whole day) sending the data through MQTT I get this error: “Attempting MQTT connection…failed, rc=-2 try again in 3 seconds” and the only way to solve it was resetting my NodeMCU. Sometimes also, after re uploading the same code, I get the same error and it won’t send data as it can’t connect through MQTT. My Ubidots account is STEM. Any help would be appreciated.

Hello @DanielGalindo ,
Thank you for posting at our Community Forum.

After testing this out, it seems that the culprit of the problem is the connection with the Broker, that is, it is being closed and then having problems being opened again.

Since you have 60s delays between sending data, the KeepAlive isn’t being sent to our Broker within the 15s (default value) that it waits before closing the connection. Fortunately, there are two solutions that could easily overcome this.

  1. Rearrange your code so that continues to have the same delay time that you need, but not in 1 single delay, instead split that 60s delay into multiple 10s delays and having the client.loop() line between each delay. This will make sure that the connection is maintained at least every 10s.

  2. Within the library, change the default KeepAlive from 15s to another value greater than the delay that you need (the maximum allowed time for our MQTT Broker is 3 hours or 10800s). To do this, you’d have to go to the folder where your UbidotsESPMQTT library is and from the file UbidotsESPMQTT.cpp add the following 2 lines in the begin object definition:

  _client.setKeepAlive(2*60*60); // KeepAlive in seconds, in this case 7200s or 2h
  Serial.println("Keepalive set to 2 hours"); // debug message to make sure changes are active

It would look something like this:

After that, just save the file and re-compile your code onto your ESP8266.

I hope these two options help you continue with your development.

I’ll be attentive to your response.

Best regards,
Sebastián

Thank you so much Sebastian it really helped us!