#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "io.adafruit.com";
const char* aio_username = "sriharish05"; //
const char* aio_key = "aio_zQXf560JS1EuxpauUw8iDWAMzNdA";
#define LOCK1 16
#define LOCK2 17
#define LOCK3 18
WiFiClient espClient;
PubSubClient client(espClient);
// Define MQTT Topics for the Group
String lock_command_topic = String(aio_username) + "/feeds/locks.command";
String lock_status_topic = String(aio_username) + "/feeds/locks.status";
String lock_log_topic = String(aio_username) + "/feeds/locks.log";
void callback(char* topic, byte* payload, unsigned int length) {
String message = "";
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.println("Received MQTT Message: " + message);
int commaIndex = message.indexOf(',');
if (commaIndex == -1) {
Serial.println("Invalid message format!");
return;
}
int lock_id = message.substring(0, commaIndex).toInt();
String action = message.substring(commaIndex + 1);
int pin = 0;
if (lock_id == 1) pin = LOCK1;
else if (lock_id == 2) pin = LOCK2;
else if (lock_id == 3) pin = LOCK3;
if (pin != 0) {
if (action == "lock") {
digitalWrite(pin, HIGH);
} else if (action == "unlock") {
digitalWrite(pin, LOW);
}
sendMQTTResponse(lock_id,action+"ing", "success");
} else {
sendMQTTResponse(lock_id,action+"ing", "failure");
}
}
void sendMQTTResponse(int lock_id, String act ,String status) {
String message = String(lock_id) + "," +act+","+status;
client.publish(lock_status_topic.c_str(), message.c_str());
Serial.println("Published: " + message);
// Log the action
char logMessage[100];
sprintf(logMessage, "Lock %d -> Action: %s | Status: %s", lock_id, act, status);
client.publish(lock_log_topic, logMessage);
Serial.print("Logged: ");
Serial.println(logMessage);
}
void reconnect() {
while (!client.connected()) {
Serial.print("Reconnecting to MQTT...");
if (client.connect("ESP32_Client", aio_username, aio_key)) {
Serial.println("Connected!");
client.subscribe(lock_command_topic.c_str());
} else {
Serial.println("Failed. Retrying...");
delay(2000);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(LOCK1, OUTPUT);
pinMode(LOCK2, OUTPUT);
pinMode(LOCK3, OUTPUT);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi.");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
reconnect();
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}