#include <WiFi.h>
#include <PubSubClient.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT Broker settings
const char* mqtt_server = "broker.hivemq.com";
const char* topic = "alarm_system";
// Create WiFi and MQTT client objects
WiFiClient espClient;
PubSubClient client(espClient);
// Pins
const int ledPin = 12; // Pin for LED
const int buzzerPin = 4; // Pin for Buzzer
// Timing
long lastMessageTime = 0;
const long delayAfterOpening = 3000; // 3 seconds delay
bool eyesClosed = false; // Variable to store the state of the message
void setup_wifi() {
delay(10);
Serial.print("Connecting to ");
Serial.println(ssid);
// Start WiFi connection
WiFi.begin(ssid, password);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
bool reconnect() {
if (client.connect("espclient")) {
Serial.println("MQTT connected");
client.subscribe(topic); // Subscribe to the topic after connecting
return true;
} else {
Serial.print("Failed to connect, rc=");
Serial.print(client.state());
Serial.println(". Trying again in 5 seconds.");
return false;
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("]: ");
// Convert payload to string and then to integer
String message = "";
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
int numericMessage = message.toInt();
Serial.println(numericMessage);
// Update eyesClosed state based on message content
if (numericMessage == 1) {
eyesClosed = true;
lastMessageTime = millis(); // Store the time when the message was received
} else if (numericMessage == 0) {
eyesClosed = false;
lastMessageTime = millis(); // Store the time when the message was received
}
}
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
setup_wifi();
client.setServer(mqtt_server, 1883); // Set MQTT server and port
client.setCallback(callback); // Set callback function to handle messages
// Set MQTT keep-alive to 60 seconds to avoid frequent disconnections
client.setKeepAlive(3600);
}
void loop() {
// Ensure WiFi connection is active
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi lost. Reconnecting...");
setup_wifi();
}
// If the client is disconnected, attempt to reconnect
if (!client.connected()) {
if (reconnect()) {
// Successful reconnect
lastMessageTime = millis(); // Reset timer
}
} else {
// Maintain the MQTT connection
client.loop();
// Handle the behavior based on the eyesClosed state
if (eyesClosed) {
digitalWrite(ledPin, HIGH);
tone(buzzerPin, 1000); // Play sound at 1000 Hz
} else {
if (millis() - lastMessageTime >= delayAfterOpening) {
digitalWrite(ledPin, LOW);
noTone(buzzerPin); // Stop sound
}
}
}
}