1
0
Fork 0

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.
master
Dustin 2021-06-10 08:51:18 -05:00
parent 257bac9d86
commit 2afae103d9
1 changed files with 6 additions and 4 deletions

View File

@ -82,7 +82,7 @@ class Daemon:
signal.signal(signal.SIGTERM, self.on_signal) signal.signal(signal.SIGTERM, self.on_signal)
client = mqtt.Client() 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_connect = self.on_connect
client.on_message = self.on_message client.on_message = self.on_message
client.on_disconnect = self.on_disconnect client.on_disconnect = self.on_disconnect
@ -105,7 +105,7 @@ class Daemon:
if self.quitpipe[0] in ready: if self.quitpipe[0] in ready:
os.close(self.quitpipe[0]) os.close(self.quitpipe[0])
break break
client.publish(AVAILABILITY_TOPIC, "offline") client.publish(AVAILABILITY_TOPIC, "offline", retain=True)
client.disconnect() client.disconnect()
client.loop_stop() client.loop_stop()
@ -120,9 +120,11 @@ class Daemon:
for key, value in SENSOR_CONFIG.items(): for key, value in SENSOR_CONFIG.items():
value["unique_id"] = f"sensor.{key}" value["unique_id"] = f"sensor.{key}"
client.publish( 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() self._ready.set()
def on_disconnect(self, client, userdata, rc): def on_disconnect(self, client, userdata, rc):