From c244f808049ba1b514c5c6e0a7e7a543bcf7970b Mon Sep 17 00:00:00 2001 From: HenrikBojsenNehm Date: Mon, 14 Aug 2023 14:13:08 +0200 Subject: [PATCH] Reed to mqtt --- src/main.cpp | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 36c420e..6fcf0ba 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -8,6 +8,8 @@ const char *password = "zwr33htm"; const char *mqtt_server = "192.168.24.215"; +const int deviceId = 2; + WiFiClient espClient; PubSubClient client(espClient); @@ -57,6 +59,7 @@ void reconnect() } #define RELAY_ACTIVATION_PIN D6 +#define REED_ACTIVATION_PIN D5 void callback(char* topic, byte* payload, unsigned int length) { StaticJsonDocument<256> doc; @@ -70,7 +73,7 @@ void callback(char* topic, byte* payload, unsigned int length) { } Serial.println(); - if (doc["deviceId"] == 2 && doc["lock"] == true) { + if (doc["deviceId"] == deviceId && doc["lock"] == true) { digitalWrite(RELAY_ACTIVATION_PIN, HIGH); // Turn the relay on } else { digitalWrite(RELAY_ACTIVATION_PIN, LOW); // Turn the relay off @@ -83,6 +86,7 @@ void setup() Serial.begin(115200); pinMode(RELAY_ACTIVATION_PIN, OUTPUT); + pinMode(REED_ACTIVATION_PIN, INPUT); setup_wifi(); client.setServer(mqtt_server, 1883); @@ -90,7 +94,30 @@ void setup() reconnect(); } +bool lastReed = 0; + void loop() { + bool reed = !digitalRead(REED_ACTIVATION_PIN); + + if (reed != lastReed) + { + Serial.print("Reed has changed to: "); + Serial.println(reed); + + + DynamicJsonDocument doc(1024); + + doc["deviceId"] = deviceId; + doc["open"] = reed; + + char buffer[1024]; + size_t n = serializeJson(doc, buffer); + + client.publish("door/status", buffer, n); + lastReed = reed; + } + + client.loop(); } \ No newline at end of file