From d6d34f0c07d18b1129b20c7fb95aba6e2662732c Mon Sep 17 00:00:00 2001 From: HenrikBojsenNehm Date: Mon, 14 Aug 2023 13:27:22 +0200 Subject: [PATCH] Doorlock on mqtt msg --- src/main.cpp | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index ab765fe..36c420e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -7,7 +7,6 @@ const char *ssid = "PET Aflytningsvogn #43"; const char *password = "zwr33htm"; const char *mqtt_server = "192.168.24.215"; -// const char *mqtt_server = "test.mosquitto.org"; WiFiClient espClient; PubSubClient client(espClient); @@ -41,9 +40,10 @@ void reconnect() { Serial.print("Attempting MQTT connection..."); // Attempt to connect - if (client.connect("ESP8266Client")) + if (client.connect("ESP8266Client2")) { Serial.println("connected"); + client.subscribe("door/lock"); } else { @@ -56,19 +56,41 @@ void reconnect() } } +#define RELAY_ACTIVATION_PIN D6 + +void callback(char* topic, byte* payload, unsigned int length) { + StaticJsonDocument<256> doc; + deserializeJson(doc, payload, length); + + Serial.print("Message arrived ["); + Serial.print(topic); + Serial.print("] "); + for (int i = 0; i < length; i++) { + Serial.print((char)payload[i]); + } + Serial.println(); + + if (doc["deviceId"] == 2 && doc["lock"] == true) { + digitalWrite(RELAY_ACTIVATION_PIN, HIGH); // Turn the relay on + } else { + digitalWrite(RELAY_ACTIVATION_PIN, LOW); // Turn the relay off + } + +} + void setup() { Serial.begin(115200); + pinMode(RELAY_ACTIVATION_PIN, OUTPUT); + setup_wifi(); client.setServer(mqtt_server, 1883); + client.setCallback(callback); + reconnect(); } void loop() { client.loop(); - if (!client.connected()) - { - reconnect(); - } } \ No newline at end of file