#include <WiFi.h>
#include <ArduinoWebsockets.h>
using namespace websockets;
WebsocketsClient client;
// Pin Definitions
#define BUZZER_PIN 23
#define LED_PIN 2 // Built-in LED
// WiFi Credentials
const char* ssid = "ZTE_2.4G_4nuKRp";
const char* password = "9g3bvuTP";
// WebSocket server details
const char* websocket_server = "ws://127.0.0.1:9090/";
// State variables
unsigned long buzzerStartTime = 0;
bool buzzerActive = false;
void onMessageCallback(WebsocketsMessage message) {
String msg = message.data();
Serial.print("Got Message: ");
Serial.println(msg);
if (msg == "fall_detected") {
Serial.println("🚨 Fall detected! Activating buzzer...");
buzzerStartTime = millis();
buzzerActive = true;
digitalWrite(BUZZER_PIN, HIGH);
digitalWrite(LED_PIN, HIGH); // Visual indication
}
}
void onEventsCallback(WebsocketsEvent event, String data) {
if(event == WebsocketsEvent::ConnectionOpened) {
Serial.println("Connection Opened");
digitalWrite(LED_PIN, HIGH);
} else if(event == WebsocketsEvent::ConnectionClosed) {
Serial.println("Connection Closed");
digitalWrite(LED_PIN, LOW);
}
}
void setup() {
Serial.begin(115200);
// Setup pins
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
// Setup Websocket callbacks
client.onMessage(onMessageCallback);
client.onEvent(onEventsCallback);
// Connect to websocket server
bool connected = client.connect(websocket_server);
if(connected) {
Serial.println("Connected to Websocket server");
client.send("ESP32 Client Connected");
} else {
Serial.println("Failed to connect to Websocket server!");
}
}
void loop() {
if(client.available()) {
client.poll();
}
// Handle buzzer timeout (3 seconds)
if (buzzerActive && (millis() - buzzerStartTime >= 3000)) {
digitalWrite(BUZZER_PIN, LOW);
digitalWrite(LED_PIN, LOW);
buzzerActive = false;
Serial.println("Buzzer deactivated");
}
// Reconnect if connection is lost
if (!client.available()) {
Serial.println("Connection lost. Attempting to reconnect...");
client.connect(websocket_server);
}
delay(10);
}