#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <base64.h> // Include a base64 library for encoding
#include <HTTPClient.h> // Include library for HTTP requests
// WiFi credentials
const char* wifi_ssid = "Wokwi-GUEST";
const char* wifi_password = "";
// yo
// Pre-shared key for authentication
const char* pre_shared_key = "secure_connection";
// Webhook URL
const char* webhook_url = "https://webhookwizard.com/api/webhook/in?key=sk_4738b49d-a08e-433e-bb52-c5673372dd60";
// Sensor Pins
const int motion_sensor_pin = 15;
// Actuator Pins
const int buzzer_pin = 14;
uint32_t timer_update = 0;
int pir_state = LOW;
int motion_value = 0;
void setup() {
Serial.begin(115200);
pinMode(motion_sensor_pin, INPUT);
pinMode(buzzer_pin, OUTPUT);
setup_wifi();
}
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(wifi_ssid);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
motionSensor();
}
void motionSensor() {
motion_value = digitalRead(motion_sensor_pin);
if (motion_value == HIGH && pir_state == LOW) {
triggerBuzzer(true);
Serial.println("Motion detected!");
sendSecureMessage("Motion detected!");
pir_state = HIGH;
} else if (motion_value == LOW && pir_state == HIGH) {
triggerBuzzer(false);
Serial.println("Motion ended!");
sendSecureMessage("Motion ended!");
pir_state = LOW;
}
}
void triggerBuzzer(bool state) {
if (state) {
tone(buzzer_pin, 550);
} else {
noTone(buzzer_pin);
}
}
// Function to send a secure message with basic encryption and authentication
void sendSecureMessage(const char* message) {
// Create a JSON object to hold the message and timestamp
StaticJsonDocument<200> doc;
doc["message"] = message;
doc["timestamp"] = millis();
doc["key"] = pre_shared_key; // Include the pre-shared key for basic authentication
// Serialize JSON to a string
String jsonMessage;
serializeJson(doc, jsonMessage);
// Base64 encode the message
String base64Message = base64::encode(jsonMessage);
// Send the secure message
Serial.println("Sending Secure Message:");
Serial.println(base64Message);
// Post the message to the webhook
postToWebhook(base64Message);
}
void postToWebhook(const String& message) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(webhook_url);
http.addHeader("Content-Type", "application/json");
// Create a JSON object for the payload
StaticJsonDocument<200> payload;
payload["data"] = message;
String payloadStr;
serializeJson(payload, payloadStr);
int httpResponseCode = http.POST(payloadStr);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.print("Webhook Response: ");
Serial.println(response);
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
}