From 657a13a12ac61a23d90a2794b9f429e2f87c96f1 Mon Sep 17 00:00:00 2001 From: Nis Wechselberg Date: Sun, 20 May 2018 14:28:20 +0200 Subject: [PATCH] MQTT-BenQ: Added dedicated power state topic --- ESP8266-MQTT-BenQ/ESP8266-MQTT-BenQ.ino | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/ESP8266-MQTT-BenQ/ESP8266-MQTT-BenQ.ino b/ESP8266-MQTT-BenQ/ESP8266-MQTT-BenQ.ino index 71ed3e8..75ca21a 100644 --- a/ESP8266-MQTT-BenQ/ESP8266-MQTT-BenQ.ino +++ b/ESP8266-MQTT-BenQ/ESP8266-MQTT-BenQ.ino @@ -44,7 +44,7 @@ // Timestamp for last publish long lastMsg = 0; -long publishInterval = 10000; +long publishInterval = 5000; // Global mqtt client object WiFiClient espClient; @@ -182,6 +182,28 @@ void updateLamptime() { } } +void updatePowerState() { + // Clean input buffer + clearSerialInput(); + + // Write request to serial + Serial.print("\r*pow=?#\r"); + delay(250); + + // Extract lamp time from response + String message = Serial.readString(); + int startIndex = message.lastIndexOf('='); + int endIndex = message.lastIndexOf('#'); + if (startIndex != -1 && endIndex != -1) { + String state = message.substring(startIndex + 1, endIndex); + if (state.equalsIgnoreCase("off")) { + client.publish(mqtt_topic_powerState, "0"); + } else if (state.equalsIgnoreCase("on")) { + client.publish(mqtt_topic_powerState, "1"); + } + } +} + void loop() { // Check OTA update ArduinoOTA.handle(); @@ -199,5 +221,6 @@ void loop() { if (now - lastMsg > publishInterval) { lastMsg = now; updateLamptime(); + updatePowerState(); } }