#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL6kKCIbR6G"
#define BLYNK_TEMPLATE_NAME "TempDHT"
#define BLYNK_AUTH_TOKEN "kVZiHg7rJwBbHA7dnSx9OiotUXL3CW6J" // TOKEN TO CONNECT TO THE DEVICE IN CLOUD
#include <WiFi.h>
#include <PubSubClient.h> // MQTT Library
#include <WiFiClientSecure.h> // For secure connection
#include <BlynkSimpleEsp32.h> // Blynk library
#include "DHTesp.h"
#include <ArduinoJson.h>
#include <ESP32Servo.h>
#include <Blynk.h>
//#include <Servo.h> // مكتبة التحكم في السيرفو
// HiveMQ details
const char* mqtt_server = "31050a712c2246edb3fc6536dc45cbc2.s1.eu.hivemq.cloud";
const int mqtt_port = 8883; // Secure port
const char* mqtt_user = "hivemq.webclient.1733864447095";
const char* mqtt_password = "eO>qhDdE%XI9#H,c8m23";
const char* publish_topic = "wokwi/device2";
const char* subscribe_topic = "wokwi/device1";
// WiFi and MQTT setup
WiFiClientSecure wifiClient; // For SSL connection
PubSubClient mqttClient(wifiClient);
const int led_red = 25;
const int DHT_PIN = 15;
const int servoPin = 18;
const int motionPin= 19 ;
const int buzzerPin = 21 ;
int pirState = LOW;
Servo myServo;
DHTesp dhtSensor;
char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
BlynkTimer timer;
// Function to reconnect to MQTT broker
void reconnectMQTT() {
while (!mqttClient.connected()) {
Serial.print("Connecting to MQTT...");
if (mqttClient.connect("ESP32Client", mqtt_user, mqtt_password)) {
Serial.println("Connected to HiveMQ!");
mqttClient.subscribe(subscribe_topic); // Subscribe to topic
} else {
Serial.print("Failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" Retrying in 5 seconds...");
delay(5000);
}
}
}
float humidity = 0;
float temperature =0;
// void handleMotionSensor() {
// int motionDetected = digitalRead(motionPin);
// if (motionDetected == HIGH && pirState == LOW) {
// pirState = HIGH; // تحديث حالة المستشعر
// digitalWrite(21, HIGH);
// Serial.println("Motion detected!, making sound");
// // إرسال بيانات إلى Blynk
// Blynk.virtualWrite(V6, 1); // افترض أن V6 هو مخرج لعرض حالة الحركة
// // نشر البيانات إلى HiveMQ
// if (mqttClient.connected()) {
// String payload = "{\"motion\": 1}";
// mqttClient.publish(publish_topic, payload.c_str());
// Serial.println("Published motion detection to MQTT.");
// }
// } else if (motionDetected == LOW && pirState == HIGH) {
// pirState = LOW; // تحديث حالة المستشعر
// digitalWrite(21, LOW);
// Serial.println("Motion stopped!, stops making sound");
// // إرسال بيانات إلى Blynk
// Blynk.virtualWrite(V6, 0);
// // نشر البيانات إلى HiveMQ
// if (mqttClient.connected()) {
// String payload = "{\"motion\": 0}";
// mqttClient.publish(publish_topic, payload.c_str());
// Serial.println("Published no motion to MQTT.");
// }
// }
// }
// Function to send sensor data to MQTT and Blynk
void sendSensorData() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("---");
// Send data to Blynk
Blynk.virtualWrite(V0, data.temperature);
Blynk.virtualWrite(V1, data.humidity);
// Send data to HiveMQ
if (mqttClient.connected()) {
// String payload = "{\"temperature\":" + String(data.temperature, 2) + ", \"humidity\":" + String(data.humidity, 1) + "}";
// mqttClient.publish(publish_topic, payload.c_str()); // Publish data to MQTT topic
// Serial.println("Published to MQTT: " + payload);
humidity = dhtSensor.getHumidity();
temperature = dhtSensor.getTemperature();
DynamicJsonDocument doc(1024);
doc["temperature"] = temperature;
doc["humidity"] = humidity;
char buffer[1024];
serializeJson (doc, buffer) ;
mqttClient.publish(publish_topic, buffer);
Serial.print("Publish { temp: "); Serial.print(temperature);
Serial.print(", "); Serial.print("humidity: "); Serial.print(humidity);
Serial.print(" } On Topic <");Serial.print(publish_topic); Serial.println("> ");
}
}
void notifyOnTheft()
{
int isTheftAlert = digitalRead(motionPin);
Serial.println(isTheftAlert);
if (isTheftAlert==1) {
Serial.println("Theft Alert in Home");
//Blynk.email("[email protected]", "Alert", "Theft Alert in Home");
// Blynk.notify("Alert : Theft Alert in Home");
Blynk.logEvent("motion_","Theft Alert in Home");
// flag=1;
}
else if (isTheftAlert==0)
{
// flag=0;
}
}
// Callback function to handle incoming MQTT messages
void mqttCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.println(topic);
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.println("Message: " + message);
}
void setup()
{
Serial.begin(115200);
Blynk.begin(auth, ssid, pass);
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to WiFi!");
// Setup MQTT
wifiClient.setInsecure(); // Remove this in production and use a valid certificate
mqttClient.setServer(mqtt_server, mqtt_port);
mqttClient.setCallback(mqttCallback);
// Setup DHT Sensor
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// Timer to send sensor data every 5 seconds
timer.setInterval(5000, sendSensorData);
myServo.attach(servoPin);
myServo.write(0); // ضبط السيرفو على زاوية البداية
timer.setInterval(5000L, notifyOnTheft);
pinMode(25, OUTPUT); // Setup LED pin
pinMode(19, INPUT); // set ESP32 pin to input mode
pinMode(21, OUTPUT); // set ESP32 pin to output mode
}
void loop() {
// int switchState = digitalRead(led_red);
// Publish raw switch state to MQTT broker
// char message[2]; // Buffer to hold the value as a string
// sprintf(message, "%d", switchState); // Convert integer value to string
// mqttClient.publish(publish_topic, message);
if (!mqttClient.connected()) {
reconnectMQTT();
}
mqttClient.loop(); // Handle MQTT
Blynk.run(); // Handle Blynk
timer.run(); // Handle Timer
int motionDetected = digitalRead(motionPin);
if (motionDetected == HIGH && pirState == LOW) {
pirState = HIGH; // تحديث حالة المستشعر
digitalWrite(21, HIGH);
Serial.println("Motion detected!, making sound");
// إرسال بيانات إلى Blynk
Blynk.virtualWrite(V6, 1); // افترض أن V6 هو مخرج لعرض حالة الحركة
// نشر البيانات إلى HiveMQ
if (mqttClient.connected()) {
String payload = "{\"motion\": 1}";
mqttClient.publish(publish_topic, payload.c_str());
Serial.println("Published motion detection to MQTT.");
}
} else if (motionDetected == LOW && pirState == HIGH) {
pirState = LOW; // تحديث حالة المستشعر
digitalWrite(21, LOW);
Serial.println("Motion stopped!, stops making sound");
// إرسال بيانات إلى Blynk
Blynk.virtualWrite(V6, 0);
// نشر البيانات إلى HiveMQ
if (mqttClient.connected()) {
String payload = "{\"motion\": 0}";
mqttClient.publish(publish_topic, payload.c_str());
Serial.println("Published no motion to MQTT.");
}
}}
//to get data from wokwoi to blynk show the data in label
BLYNK_WRITE(V0) {
int switchState = param.asInt(); // Get the state of the switch (ON = 1, OFF = 0)
Serial.print("V0 Switch state: ");
Serial.println(switchState);
// Send the value to the MQTT broker
if (mqttClient.connected()) {
String payload = "{\"switch\": " + String(switchState) + "}";
mqttClient.publish(publish_topic, payload.c_str()); // Publish data to MQTT topic
Serial.println("Published to MQTT: " + payload);
}
// Control LED based on switch state
digitalWrite(2, switchState ? HIGH : LOW);
}
// لاخذ الداتا من الblynk
BLYNK_WRITE(V2)
{
int pinValue = param.asInt();
Serial.print("V2 Switch value is: ");
Serial.println(pinValue);
}
// لارسال الداتا من السويتش الخاص بالليد في ال blynk الى wokwoi
BLYNK_WRITE(V3)
{
// Set incoming value from pin V0 to a variable
int value = param.asInt();
Serial.println("Value : "+ String(value));
if(value) digitalWrite(25, HIGH);
else digitalWrite(25, LOW);
// Update state
Blynk.virtualWrite(V3, value);
Blynk.virtualWrite(V5, value);//to push data in the led red in blynk
// Send the value to the MQTT broker
if (mqttClient.connected()) {
String payload = "{\"V3\": " + String(value) + "}";
mqttClient.publish(publish_topic, payload.c_str()); // Publish data to MQTT topic
Serial.println("Published to MQTT: " + payload);
}
}
// وظيفة التحكم بالسيرفو من Blynk
BLYNK_WRITE(V4) {
int switchState = param.asInt(); // قراءة حالة المفتاح (ON = 1, OFF = 0)
if (switchState == 1) {
myServo.write(90); // تحريك السيرفو إلى زاوية 90 درجة
Serial.println("Servo moved to 90 degrees");
} else {
myServo.write(0); // إعادة السيرفو إلى زاوية 0 درجة
Serial.println("Servo moved to 0 degrees");
}
// إرسال الزاوية إلى HiveMQ
if (mqttClient.connected()) {
String payload = "{\"swutch servo v4 \": " + String(switchState) + "}";
mqttClient.publish(publish_topic, payload.c_str()); // نشر البيانات إلى HiveMQ
Serial.println("Published to MQTT v4 : " + payload);
}
}