• Skip to main content
  • Skip to primary sidebar

RNTLab.com

The Ultimate Shortcut to Learn Electronics and Programming with Open Source Hardware and Software

  • Courses
  • Forum
    • Forum
    • Ask Question
  • Shop
  • Account
  • Blog
  • Login

MQTT connection problem

Q&A Forum › Category: ESP32 › MQTT connection problem
0 Vote Up Vote Down
mosaddeq billah asked 1 year ago

 This code worked fine. But suddenly stopped to connect mqtt. each time it print
 

Attempting MQTT connection...
Failed, rc=-2 Retrying in 5 seconds...

Here is code

 

// Publish

#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>

// WiFi credential
const char* ssid = “dlink-A69*”;
const char* password = “nutr*nne”;

// MQTT Server Credential
const char* mqtt_server = “rabiulmosaddeq.prozukti.lol”; // MQTT broker address
const int mqtt_port = 1883; // MQTT broker port
const char* mqtt_username = “****”; // MQTT username
const char* mqtt_password = “****”; // MQTT password
char mqtt_topic[50]; // MQTT topic to publish, user input

// MQTT topic to publish, user input
const char* mqtt_subscribe_topic = “101”;

//try to reconnect if connection lost interval
const int reconnectInterval = 5000; // 5 seconds
unsigned long lastReconnectAttempt = 0;

// Declare object
WiFiClient espClient;
PubSubClient client(espClient);

// KEYPAD
#define ROW_NUM     4 // four rows
#define COLUMN_NUM  4 // four columns
char keys[ROW_NUM][COLUMN_NUM] = {
  {‘1’, ‘2’, ‘3’, ‘A’},
  {‘4’, ‘5’, ‘6’, ‘B’},
  {‘7’, ‘8’, ‘9’, ‘C’},
  {‘*’, ‘0’, ‘#’, ‘D’}
};
byte pin_rows[ROW_NUM]      = {4, 16, 17, 5}; // Connection:  Keypad to  Board >> 1- D4, 2-RX2, 3-Tx-2, 4-D5, 5-D18, 6-D19,7-D21, 8-RX0
byte pin_column[COLUMN_NUM] = {18, 19, 21, 3};   //
 
Keypad keypad = Keypad( makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM );

char character;
char numBuffer[4]; // Buffer to store entered digits or characters
int numIndex = 0;  // Index of the buffer

// LCD
#define SDA_PIN 14   // GPIO pin for SDA
#define SCL_PIN 13   // GPIO pin for SCL

const int lcdColumns = 16; // Set the LCD number of columns and rows
const int lcdRows = 2;

LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); // Set LCD address, number of columns and rows

void setup() {
  Serial.begin(115200);
  Wire.begin(SDA_PIN, SCL_PIN);
  lcd.init();
  lcd.backlight();
  lcd.clear();  
  lcd.setCursor(0, 0);
  setup_wifi();
 
}

void setup_wifi() {
  delay(10);
  // Connect to WiFi network
  Serial.println();
  Serial.print(“Connecting to “);
  Serial.println(ssid);

  // LCD PRINT

  lcd.clear();
  // lcd.setCursor(0, 0);
  lcd.print(“WiFi Connecting..”);
  delay(1000);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);

 
 
  //LCD PRINT
    lcd.print(“No internet”);
  }
  Serial.println(“”);
  Serial.println(“WiFi connected”);
  Serial.println(“IP address: “);
  Serial.println(WiFi.localIP());

  // LCD PRINT

  lcd.clear();

  lcd.print(“WiFi Connected”);
  delay(1000);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(“IP address”);
  String ipString = WiFi.localIP().toString();
  lcd.setCursor(0,1);
  lcd.print(ipString);

  // Configure MQTT client
  client.setServer(mqtt_server, mqtt_port);
  // client.subscribe(mqtt_subscribe_topic);
  // client.setCallback(callback);
}

int reconnect() {
  while (!client.connected()) {
    Serial.println(“Attempting MQTT connection…”);

    //LCD PRINT

    lcd.clear();
    lcd.print(“Connecting Server”);

    if (client.connect(“ESP32Client”, mqtt_username, mqtt_password)) {
      Serial.println(“Connected to MQTT broker”);

      // LCD PRINT
       lcd.clear();
       lcd.print(“Server Connected”);
       delay(1000);
       lcd.clear();

      // client.subscribe(mqtt_subscribe_topic);
      // client.setCallback(callback);
      return 1;
    } else {
      Serial.print(“Failed, rc=”);
      Serial.print(client.state());
      Serial.println(” Retrying in 5 seconds…”);
      delay(5000);
      return 0;
    }
  }
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) {
    unsigned long currentMillis = millis();
    if (currentMillis – lastReconnectAttempt >= reconnectInterval) {
      lastReconnectAttempt = currentMillis;
      setup_wifi(); // Reconnect WiFi
    }
  } else {
    if (!client.connected()) {
      reconnect(); // Reconnect MQTT
    }
   
    //client.loop();

    // Publish a message every 5 seconds
    // if (digitalRead(23) == HIGH) {
      publishMessage();
    //   delay(4000); // Delay to avoid repeated publishing due to pin state change
    // }
  }
}

// int getKeypadInput() {
//   char key = keypad.getKey();
//   if (key) {
//     if (key >= ‘0’ && key <= ‘9’) {
//       if (numIndex < 3) { // Check if buffer is not full
//         numBuffer[numIndex++] = key;
//         numBuffer[numIndex] = ‘\0’; // Null-terminate the string
//         int number = atoi(numBuffer); // Convert the string to an integer
//         if (numIndex == 1) { // If the first character of the input
//           Serial.println(numBuffer[0]); // Print the entered character
//         } else if (numIndex == 2) { // If the second character of the input
//           Serial.println(number); // Print the entered number
//         }
//           else if (numIndex == 3) { // If the second character of the input
//           Serial.println(number); // Print the entered number

//       }}
//     } else if (key == ‘#’) {
//       if (numIndex > 0) { // Check if any input was entered
//         int number = atoi(numBuffer); // Convert the string to an integer
//         Serial.println(number); // Print the final entered number
//         numIndex = 0; // Reset index for next input
//         return number; // Return the final entered number
//       }
//     } else if (key == ‘*’) {
//       numIndex = 0; // Clear the buffer
//     }
//      else if (key == ‘A’ || key == ‘B’ || key == ‘C’ || key == ‘D’  ){
//         character = key;
//         return (int)character;
//       }

   
//   }

//   return -1; // Return -1 if no valid input was received
// }
void publishMessage() {
  // Prompt user to enter MQTT topic name
  Serial.println(“Enter MQTT topic name:”);
  lcd.clear();
  lcd.print(“Messege To ..”);

  // Wait for user input
  char inputTopic[50]; // Temporary buffer to store input
  int i = 0;
  lcd.setCursor(0,1);
  while (true) {
    char key = keypad.getKey();
    if (key && key != ‘#’) {
      inputTopic[i++] = key;
      Serial.print(key);
      //lcd.setCursor(0,1);
      lcd.print(key);
    } else if (key == ‘#’) {
      inputTopic[i] = ‘\0’; // Null-terminate the string
      break;
    }
    delay(100);
  }

  // Print the entered MQTT topic for verification
  Serial.print(“\nEntered MQTT topic: “);
  Serial.println(inputTopic);
 
  lcd.clear();
  //lcd.print(inputTopic);
  //lcd.setCursor(0,1);
  lcd.print(” Write msg”);
 

  // Publish message to MQTT broker with the user-defined topic
  if (strlen(inputTopic) > 0) {
    char inputMessage[50];
    int j = 0;
    while (true) {
      char key = keypad.getKey();
      if (key && key != ‘#’) {
        inputMessage[j++] = key;
        Serial.print(key);
        lcd.clear();
        lcd.print(key);

      } else if (key == ‘#’) {
        inputMessage[j] = ‘\0’;
        lcd.clear();
        lcd.print(“Accepted”);
        delay(100);
        break;
      }
      delay(100);
    }
   
    // Retry mechanism for publishing message
    int retryCount = 0;
    while (retryCount < 5) { // Retry up to 3 times
    if(reconnect()){
      if (client.publish(inputTopic, inputMessage)) {
        Serial.println(“Message published successfully”);
        lcd.clear();
        lcd.print(“Msg Delivered”);
        break; // Exit retry loop if successful
      } else {
        Serial.println(“Failed to publish message. Retrying…”);
        lcd.clear();
        lcd.print(“wait”);
        retryCount++;
        delay(1000); // Delay before retrying
      }

    }
    else{
      Serial.println(“No Internet”);
    }
     
    }

    if (retryCount == 3) {
      Serial.println(“Exceeded maximum retry attempts. Message not published.”);
      lcd.print(“Failed”);
    }
  } else {
    Serial.println(“No topic provided”);
  }
}

// void callback(char* topic, byte* payload, unsigned int length) {
//   Serial.println(“Message arrived:”);
//   Serial.print(“Topic: “);
//   Serial.println(topic);
//   Serial.print(“Payload: “);
 
//   // Convert payload to a string
//   String payloadString = “”;
//   for (int i = 0; i < length; i++) {
//     payloadString += (char)payload[i];
//   }

//   // Print payload on LCD
//   lcd.clear();
//   lcd.print(“Room”);
//   lcd.print(topic);
//   lcd.setCursor(0, 1);
//   lcd.print(payloadString);
 
//   Serial.println(payloadString);
 
//   // Add a delay to ensure message is displayed before clearing the LCD
//   delay(5000); // Adjust delay time as needed
// }

3 Answers
0 Vote Up Vote Down
Sara Santos Staff answered 1 year ago

Hi.
Is your network connection strong?
A weak wi-fi signal can result in disconnecting from the broker.
Does it reconnect to the broker after disconnecting?
Regards,
Sara

0 Vote Up Vote Down
mosaddeq billah answered 1 year ago

Thanks for your reply. Network connection is strong. But it continues connecting, disconnecting. I changed several esp32 module. Googled and also searched in chatgpt but no solution I found. Is there any problem in esp32 code? 
Is esp32 a stable board for network related project?

0 Vote Up Vote Down
Sara Santos Staff answered 1 year ago

Hi.
We tested MQTT with the ESP32 several times and it always worked flawlessly for us.
If you have multiple MQTT devices on your setup, make sure each device has a unique MQTT Client ID (“ESP32Client”):
if (client.connect(“ESP32Client”, mqtt_username, mqtt_password)) {

If you uploaded this code to multiple boards, each one must be different. For example ESP32Client1, ESP32lient2 and so on.
 
Regards,
Sara

Primary Sidebar

Login to Ask or Answer Questions

This Forum is private and it’s only available for members enrolled in our Courses.

Login »

Latest Course Updates

  • [New Edition] Build ESP32-CAM Projects eBook – 2nd Edition April 16, 2025
  • [eBook Updated] Learn ESP32 with Arduino IDE eBook – Version 3.2 April 16, 2025

You must be logged in to view this content.

Contact Support - Refunds - Privacy - Terms - MakerAdvisor.com - Member Login

Copyright © 2013-2025 · RandomNerdTutorials.com · All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.