Improve MQTT disconnection handling

This commit is contained in:
Meatballs1
2024-03-20 13:25:16 +00:00
parent 7e66669365
commit 09d883582c

20
hc2mqtt
View File

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