From 7a37afe417c4fb6ff0abf45df0bd9a13fe6b66fd Mon Sep 17 00:00:00 2001 From: Marcel Walter Date: Fri, 16 Jan 2026 23:16:41 +0100 Subject: [PATCH] MQTT: add Homeassistant discovery message --- src/main.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/src/main.cpp b/src/main.cpp index 09d9510..9b7ac54 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -44,6 +44,59 @@ void publishClose() mqtt.publish(FLIPDOT_TEXT_TOPIC "/state", output); } +void publishHomeAssistantDiscovery() +{ + auto mac = WiFi.macAddress(); + mac.replace(":", "_"); + + JsonDocument doc; + + JsonObject device = doc["dev"].to(); + device["ids"] = mac; + device["name"] = "FlipDotDisplay"; + device["mf"] = "-mf-"; + device["mdl"] = "-mdl-"; + device["sw"] = "-sw-"; + device["sn"] = "-sn-"; + device["hw"] = "-hw-"; + + JsonObject origin = doc["o"].to(); + origin["name"] = "Hobbyhimmel"; + origin["sw"] = "-sw-"; + origin["url"] = "https://hobbyhimmel.de"; + + JsonObject components = doc["cmps"].to(); + JsonObject sw = components["FlipDotDisplaySwitch"].to(); + sw["unique_id"] = mac + "FlipDotDisplaySwitch"; + sw["p"] = "switch"; + sw["command_topic"] = FLIPDOT_SWITCH_TOPIC; + sw["state_topic"] = FLIPDOT_SWITCH_TOPIC "/state"; + sw["payload_on"] = "open"; + sw["payload_off"] = "close"; + sw["qos"] = 0; + sw["retain"] = false; + + JsonObject txt = components["FlipDotDisplayText"].to(); + sw["unique_id"] = mac + "FlipDotDisplayText"; + sw["p"] = "text"; + sw["command_topic"] = FLIPDOT_TEXT_TOPIC; + sw["state_topic"] = FLIPDOT_TEXT_TOPIC "/state"; + sw["qos"] = 0; + sw["retain"] = false; + + doc["availability_topic "] = FLIPDOT_AVAILABILITY_TOPIC; + + String jsonString; + serializeJson(doc, jsonString); + + String discoveryTopic = "homeassistant/device/"; + discoveryTopic += mac + "/config"; + + mqtt.publish(discoveryTopic.c_str(), jsonString.c_str()); + Serial.print("Homeassistant Discovery was published: "); + Serial.println(jsonString); +} + /* ------------ OTA section and variables -------------- */ bool OTAStarted; void onOTAStart() @@ -214,6 +267,8 @@ void loop() mqtt.subscribe(FLIPDOT_SWITCH_TOPIC); mqtt.subscribe(FLIPDOT_TEXT_TOPIC); mqtt.publish(FLIPDOT_AVAILABILITY_TOPIC, "available"); + + publishHomeAssistantDiscovery(); } } }