#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid ="Wokwi-GUEST";
const char* password = "";
//const char* ssid = "YourWiFiSSID";
//const char* password = "YourWiFiPassword";
const char* mqtt_server = "91.121.93.94";
const int ledPin =5; // GPIO pin to which the LED is connected
//const char *ssid = "Idoom 4G_ECD58";
//const char *password = "Kerajetconnection4g00";
//const char *mqtt_server = "192.168.0.127";
const char *mqtt_client_id = "mqtt-explorer-791b1ed5";
const char *mqtt_topic = "esp32/led";
const int pinLED = 5;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
pinMode(pinLED, OUTPUT);
digitalWrite(pinLED, LOW);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.println("Message received: ");
Serial.println(topic);
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
if (String(topic) == mqtt_topic) {
if (message == "on") {
digitalWrite(pinLED, HIGH);
} else if (message == "off") {
digitalWrite(pinLED, LOW);
}
}
}
void reconnect() {
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");
if (client.connect(mqtt_client_id)) {
Serial.println("Connected to MQTT broker");
client.subscribe(mqtt_topic);
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" Retrying in 5 seconds...");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}