From 2afae103d95365b467c99c58483352f4f4ccd70c Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Thu, 10 Jun 2021 08:51:18 -0500 Subject: [PATCH] sensor: Set retain on config/availability messages When Home Assistant restarts, it puts the sensor in "Unavailable" state until it receives an "online" message. Since the sensor has no idea Home Assistant is waiting for such a message, it will never send one. By setting the "retain" flag on availability and configuration messages, the broker will automatically resend them to Home Assistant when it subscribes to the topic again, which resolves this issue. --- src/thermostat/sensor.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/thermostat/sensor.py b/src/thermostat/sensor.py index da341bd..96f6864 100644 --- a/src/thermostat/sensor.py +++ b/src/thermostat/sensor.py @@ -82,7 +82,7 @@ class Daemon: signal.signal(signal.SIGTERM, self.on_signal) client = mqtt.Client() - client.will_set(AVAILABILITY_TOPIC, "offline") + client.will_set(AVAILABILITY_TOPIC, "offline", retain=True) client.on_connect = self.on_connect client.on_message = self.on_message client.on_disconnect = self.on_disconnect @@ -105,7 +105,7 @@ class Daemon: if self.quitpipe[0] in ready: os.close(self.quitpipe[0]) break - client.publish(AVAILABILITY_TOPIC, "offline") + client.publish(AVAILABILITY_TOPIC, "offline", retain=True) client.disconnect() client.loop_stop() @@ -120,9 +120,11 @@ class Daemon: for key, value in SENSOR_CONFIG.items(): value["unique_id"] = f"sensor.{key}" client.publish( - f"homeassistant/sensor/{key}/config", json.dumps(value) + f"homeassistant/sensor/{key}/config", + json.dumps(value), + retain=True, ) - client.publish(AVAILABILITY_TOPIC, "online") + client.publish(AVAILABILITY_TOPIC, "online", retain=True) self._ready.set() def on_disconnect(self, client, userdata, rc):