Improve MQTT disconnection handling
This commit is contained in:
20
hc2mqtt
20
hc2mqtt
@@ -48,6 +48,10 @@ def hc2mqtt(
|
|||||||
elif rc == 0:
|
elif rc == 0:
|
||||||
print(now(), f"MQTT connection established: {rc}")
|
print(now(), f"MQTT connection established: {rc}")
|
||||||
client.publish(f"{mqtt_prefix}LWT", payload="Online", qos=0, retain=True)
|
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:
|
else:
|
||||||
print(now(), f"ERROR MQTT connection failed: {rc}")
|
print(now(), f"ERROR MQTT connection failed: {rc}")
|
||||||
|
|
||||||
@@ -119,6 +123,7 @@ def client_connect(client, device, mqtt_topic):
|
|||||||
|
|
||||||
host = device["host"]
|
host = device["host"]
|
||||||
device_topics = topics
|
device_topics = topics
|
||||||
|
client.on_message = on_message
|
||||||
|
|
||||||
for value in device["features"]:
|
for value in device["features"]:
|
||||||
if (
|
if (
|
||||||
@@ -136,10 +141,6 @@ def client_connect(client, device, mqtt_topic):
|
|||||||
if not topic.isdigit(): # We only want the named topics
|
if not topic.isdigit(): # We only want the named topics
|
||||||
state[device_topics[topic]] = None
|
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:
|
while True:
|
||||||
try:
|
try:
|
||||||
@@ -175,12 +176,15 @@ def client_connect(client, device, mqtt_topic):
|
|||||||
if not update:
|
if not update:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
msg = json.dumps(state)
|
if client.is_connected():
|
||||||
print(now(), device["name"], f"publish to {mqtt_topic} with {msg}")
|
msg = json.dumps(state)
|
||||||
client.publish(mqtt_topic + "/state", msg)
|
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:
|
except Exception as e:
|
||||||
print("ERROR", host, e, file=sys.stderr)
|
print("ERROR", device["name"], e, file=sys.stderr)
|
||||||
|
|
||||||
time.sleep(5)
|
time.sleep(5)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user