#include <WiFi.h>
#include <PubSubClient.h>
#include <ESP32Servo.h>
#include <string.h>
#include <ArduinoJson.h>
// wifi et MQTT
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char* mqtt_topic = "door_unlock";
WiFiClient espClient;
PubSubClient client(espClient);
Servo myServo;
int pos = 90;
int myStatus = 0;
const int ledG = 14;
const int ledR = 12;
const int button = 13;
bool buttonPressed = false;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting to Wi-Fi...");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to Wi-Fi");
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "loker-finalproject";
if (client.connect(client_id.c_str())) {
Serial.println("Connected to MQTT Broker");
client.subscribe(mqtt_topic); // Subscribe to the unlock topic
} else {
Serial.println("Failed to connect to MQTT Broker, retrying in 5 seconds...");
delay(5000);
}
}
pinMode(ledG, OUTPUT);
pinMode(ledR, OUTPUT);
pinMode(button, INPUT_PULLUP);
myServo.attach(18);
myServo.write(pos);
digitalWrite(ledG, HIGH);
}
void callback(char *topic, byte *payload, unsigned int length) {
String message = "";
for (int i = 0; i < length; i++) {
message += (char) payload[i];
}
Serial.print("Received message on topic: ");
Serial.println(topic);
Serial.print("Message: ");
Serial.println(message);
if (strcmp(topic, mqtt_topic) == 0) {
if (message.equals("unlock")) {
unlockDoor();
}
}
}
void unlockDoor() {
if (myStatus == 0) {
for (pos = 90; pos >= 0; pos -= 1) {
myServo.write(pos);
delay(10);
}
digitalWrite(ledR, HIGH);
digitalWrite(ledG, LOW);
myStatus = 1;
} else {
for (pos = 0; pos <= 90; pos += 1) {
myServo.write(pos);
delay(10);
}
digitalWrite(ledR, LOW);
digitalWrite(ledG, HIGH);
myStatus = 0;
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Check if the button is pressed
if (digitalRead(button) == LOW && !buttonPressed) {
buttonPressed = true;
unlockDoor(); // Call the unlockDoor function when the button is pressed
} else if (digitalRead(button) == HIGH) {
buttonPressed = false;
}
delay(100);
}
void reconnect() {
while (!client.connected()) {
String client_id = "loker-finalproject";
if (client.connect(client_id.c_str())) {
Serial.println("Reconnected to MQTT Broker");
client.subscribe(mqtt_topic); // Subscribe to the unlock topic
} else {
Serial.println("Failed to reconnect to MQTT Broker, retrying in 5 seconds...");
delay(5000);
}
}
}