Everything was working well but suddenly I have faced this issue where the it’s not connecting to mqtt and this is the message that appear in the output Failed with state -2The client esp8266-client-84F3EB52FB33 connects to the public MQTT broker
Here is the code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>
const char *ssid = “1078704”; // Enter your WiFi name
const char *password = “Noor”; // Enter WiFi password
// MQTT Broker settings
const char* mqtt_server = “172.20.10.2”;
const char *topic_env = “home/environment”;
const char *topic_ac = “home/ac_control”;
const int mqtt_port = 1883;
const char *mqtt_username = “Noor”;
const char *mqtt_password = “Fatema”;
WiFiClient espClient;
PubSubClient client(espClient);
Servo servoMotor; // Servo motor object
// Define the Servo pin
const int servoPin = D2; // GPIO pin for the Servo
void setup() {
servoMotor.attach(servoPin); // Attach servo motor to its pin
Serial.begin(115200);
// Connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
// Connecting to an MQTT broker
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
// Attempt to connect to the MQTT broker
reconnect();
// Subscribe to the MQTT topics
client.subscribe(topic_ac);
}
String getClientID() {
// Get the MAC address of the ESP8266
String mac = WiFi.macAddress();
// Create a unique client ID by appending the MAC address
String clientId = “esp8266-client-”;
clientId += mac;
// Remove colons from the MAC address
clientId.replace(“:”, “”);
return clientId;
}
void reconnect() {
while (!client.connected()) {
String client_id = getClientID();
Serial.printf(“The client %s connects to the public MQTT broker\n”, client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println(“Public MQTT broker connected”);
} else {
Serial.print("Failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void callback(char *topic, byte payload, unsigned int length) {
payload[length] = ‘\0’; // Null terminate the string
String message = String((char)payload);
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message: ");
Serial.println(message);
// Control Servo based on the message received
if (message == "AC_ON") {
servoMotor.write(90); // Adjust angle as needed to press the AC ON button
} else if (message == "AC_OFF") {
servoMotor.write(0); // Adjust angle as needed to press the AC OFF button
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Hope anyone can help as soon as possible