From 074a7837d85396baf538ef5818eddef815ffe614 Mon Sep 17 00:00:00 2001 From: zewelor Date: Fri, 19 Apr 2019 18:01:49 +0200 Subject: [PATCH] Improve mqtt lwt on reconnect --- mqtt.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/mqtt.py b/mqtt.py index fd4d2cb..5ef35c2 100644 --- a/mqtt.py +++ b/mqtt.py @@ -11,7 +11,7 @@ def __init__(self, config): self._config = config self._mqttc = mqtt.Client(client_id=self.client_id, clean_session=False, - userdata = {'global_topic_prefix': self.topic_prefix}) + userdata={'global_topic_prefix': self.topic_prefix}) if self.username and self.password: self.mqttc.username_pw_set(self.username, self.password) @@ -61,7 +61,14 @@ def availability_topic(self): def mqttc(self): return self._mqttc + def on_connect(self, client, userdata, flags, rc): + if self.availability_topic: + self.publish([MqttMessage(topic=self.availability_topic, payload=LWT_ONLINE, retain=True)]) + + def callbacks_subscription(self, callbacks): + self.mqttc.on_connect = self.on_connect + self.mqttc.connect(self.hostname, port=self.port) for topic, callback in callbacks: @@ -72,9 +79,6 @@ def callbacks_subscription(self, callbacks): self.mqttc.loop_start() - if self.availability_topic: - self.publish([MqttMessage(topic=self.availability_topic, payload=LWT_ONLINE, retain=True)]) - def __del__(self): if self.availability_topic: self.publish([MqttMessage(topic=self.availability_topic, payload=LWT_OFFLINE, retain=True)])