Use single state payload and HA value templates.

This commit is contained in:
James Muscat
2024-08-08 22:01:24 +01:00
parent 2186c61b5a
commit bf45fcd69a
2 changed files with 6 additions and 14 deletions

View File

@@ -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}",
})

View File

@@ -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(),