From 7d25b234d5c3550d165331f58aa4da44a2e7e67c Mon Sep 17 00:00:00 2001 From: Blaz Kristan Date: Wed, 18 May 2022 19:49:49 +0200 Subject: [PATCH] Temperature usermod HA autodicovery. --- usermods/Temperature/usermod_temperature.h | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/usermods/Temperature/usermod_temperature.h b/usermods/Temperature/usermod_temperature.h index 09ffc259..9c932ff1 100644 --- a/usermods/Temperature/usermod_temperature.h +++ b/usermods/Temperature/usermod_temperature.h @@ -46,6 +46,8 @@ class UsermodTemperature : public Usermod { bool enabled = true; + bool HApublished = false; + // strings to reduce flash memory usage (used more than twice) static const char _name[]; static const char _enabled[]; @@ -132,6 +134,28 @@ class UsermodTemperature : public Usermod { return false; } + void publishHomeAssistantAutodiscovery() { + if (!WLED_MQTT_CONNECTED) return; + + char json_str[1024], buf[128]; + size_t payload_size; + StaticJsonDocument<1024> json; + + sprintf_P(buf, PSTR("%s Temperature"), serverDescription); + json[F("name")] = buf; + strcpy(buf, mqttDeviceTopic); + strcat_P(buf, PSTR("/temperature")); + json[F("state_topic")] = buf; + json[F("device_class")] = F("tempearature"); + json[F("unique_id")] = escapedMac.c_str(); + json[F("unit_of_measurement")] = F("°C"); + payload_size = serializeJson(json, json_str); + + sprintf_P(buf, PSTR("homeassistant/sensor/%s/config"), escapedMac.c_str()); + mqtt->publish(buf, 0, true, json_str, payload_size); + HApublished = true; + } + public: void setup() { @@ -206,6 +230,23 @@ class UsermodTemperature : public Usermod { } } + /** + * connected() is called every time the WiFi is (re)connected + * Use it to initialize network interfaces + */ + //void connected() {} + + /** + * subscribe to MQTT topic if needed + */ + void onMqttConnect(bool sessionPresent) { + //(re)subscribe to required topics + //char subuf[64]; + if (mqttDeviceTopic[0] != 0) { + publishHomeAssistantAutodiscovery(); + } + } + /* * API calls te enable data exchange between WLED modules */