diff --git a/mqtt.py b/mqtt.py index fd4d2cb..0510b09 100644 --- a/mqtt.py +++ b/mqtt.py @@ -11,7 +11,9 @@ 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}) + + self.mqttc.on_connect = self.on_connect if self.username and self.password: self.mqttc.username_pw_set(self.username, self.password) @@ -61,6 +63,11 @@ def availability_topic(self): def mqttc(self): return self._mqttc + def on_connect(self, 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.connect(self.hostname, port=self.port) @@ -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)])