From 09d883582c97d1fe773669f086976b3a77504f1a Mon Sep 17 00:00:00 2001 From: Meatballs1 Date: Wed, 20 Mar 2024 13:25:16 +0000 Subject: [PATCH] Improve MQTT disconnection handling --- hc2mqtt | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/hc2mqtt b/hc2mqtt index f9fb5c0..b7ba60e 100755 --- a/hc2mqtt +++ b/hc2mqtt @@ -48,6 +48,10 @@ def hc2mqtt( elif rc == 0: print(now(), f"MQTT connection established: {rc}") client.publish(f"{mqtt_prefix}LWT", payload="Online", qos=0, retain=True) + for device in devices: + mqtt_set_topic = f"{mqtt_prefix}{device['name']}/set" + print(now(), device["name"], f"set topic: {mqtt_set_topic}") + client.subscribe(mqtt_set_topic) else: print(now(), f"ERROR MQTT connection failed: {rc}") @@ -119,6 +123,7 @@ def client_connect(client, device, mqtt_topic): host = device["host"] device_topics = topics + client.on_message = on_message for value in device["features"]: if ( @@ -136,10 +141,6 @@ def client_connect(client, device, mqtt_topic): if not topic.isdigit(): # We only want the named topics state[device_topics[topic]] = None - mqtt_set_topic = mqtt_topic + "/set" - print(now(), device["name"], f"set topic: {mqtt_set_topic}") - client.subscribe(mqtt_set_topic) - client.on_message = on_message while True: try: @@ -175,12 +176,15 @@ def client_connect(client, device, mqtt_topic): if not update: continue - msg = json.dumps(state) - print(now(), device["name"], f"publish to {mqtt_topic} with {msg}") - client.publish(mqtt_topic + "/state", msg) + if client.is_connected(): + msg = json.dumps(state) + print(now(), device["name"], f"publish to {mqtt_topic} with {msg}") + client.publish(mqtt_topic + "/state", msg) + else: + raise Exception("Unable to publish update as mqtt is not connected.") except Exception as e: - print("ERROR", host, e, file=sys.stderr) + print("ERROR", device["name"], e, file=sys.stderr) time.sleep(5)