From bf45fcd69ad890fd7d212258cbe0b6ba66242482 Mon Sep 17 00:00:00 2001 From: James Muscat Date: Thu, 8 Aug 2024 22:01:24 +0100 Subject: [PATCH] Use single state payload and HA value templates. --- HADiscovery.py | 12 +++--------- hc2mqtt.py | 8 +++----- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/HADiscovery.py b/HADiscovery.py index 60748af..c25864c 100644 --- a/HADiscovery.py +++ b/HADiscovery.py @@ -12,13 +12,6 @@ def decamelcase(str): HA_DISCOVERY_PREFIX = "homeassistant" -def publish_ha_states(state, client, mqtt_topic): - for key, value in state.items(): - state_topic = f"{mqtt_topic}/{key}" - print(f"{now()} Publishing state for {key} at {state_topic}") - client.publish(state_topic, json.dumps(value)) - - def publish_ha_discovery(device, client, mqtt_topic): print(f"{now()} Publishing HA discovery for {device}") @@ -56,13 +49,14 @@ def publish_ha_discovery(device, client, mqtt_topic): component_type = "sensor" # TODO use appropriate types discovery_topic = f"{HA_DISCOVERY_PREFIX}/{component_type}/hcpy/{device_ident}_{name}/config" - state_topic = f"{mqtt_topic}/{name}" # print(discovery_topic, state_topic) discovery_payload = json.dumps({ "name": decamelcase(name), "device": device_info, - "state_topic": state_topic, + "state_topic": f"{mqtt_topic}/state", + "availability_topic": f"{mqtt_topic}/LWT", + "value_template": "{{value_json." + name + "}}", "object_id": f"{device_ident}_{name}", "unique_id": f"{device_ident}_{name}", }) diff --git a/hc2mqtt.py b/hc2mqtt.py index 76b46ce..32b96ab 100755 --- a/hc2mqtt.py +++ b/hc2mqtt.py @@ -13,7 +13,7 @@ import paho.mqtt.client as mqtt from HCDevice import HCDevice from HCSocket import HCSocket, now -from HADiscovery import publish_ha_states, publish_ha_discovery +from HADiscovery import publish_ha_discovery @click.command() @@ -153,7 +153,7 @@ def hc2mqtt( for device in devices: mqtt_topic = mqtt_prefix + device["host"] thread = Thread( - target=client_connect, args=(client, device, mqtt_topic, domain_suffix, debug, ha_discovery) + target=client_connect, args=(client, device, mqtt_topic, domain_suffix, debug) ) thread.start() @@ -164,7 +164,7 @@ global dev dev = {} -def client_connect(client, device, mqtt_topic, domain_suffix, debug, ha_discovery): +def client_connect(client, device, mqtt_topic, domain_suffix, debug): host = device["host"] name = device["name"] @@ -198,8 +198,6 @@ def client_connect(client, device, mqtt_topic, domain_suffix, debug, ha_discover msg = json.dumps(state) print(now(), name, f"publish to {mqtt_topic} with {msg}") client.publish(f"{mqtt_topic}/state", msg, retain=True) - if ha_discovery: - publish_ha_states(state, client, mqtt_topic) else: print( now(),