Fix on_connect callback

This commit is contained in:
Nicolas Duhamel 2021-03-16 09:08:41 +01:00
parent 20bbd9661a
commit cdb8b5a222

View File

@ -6,6 +6,12 @@ from typing import NoReturn
import paho.mqtt.client as mqtt import paho.mqtt.client as mqtt
class Configuration:
user: str
password: str
host: str
port: int
class Client(mqtt.Client): class Client(mqtt.Client):
def __init__(self, logger: logging.Logger=None): def __init__(self, logger: logging.Logger=None):
super().__init__() super().__init__()
@ -15,6 +21,9 @@ class Client(mqtt.Client):
self.logger = logging.getLogger('mqtt') self.logger = logging.getLogger('mqtt')
self._subscribe_callbacks = [] self._subscribe_callbacks = []
self._on_connect_callbacks = []
self.on_connect = self._on_connect2
def setup(self, host: str, port: int, username: str, password: str): def setup(self, host: str, port: int, username: str, password: str):
self._username = username self._username = username
@ -37,18 +46,22 @@ class Client(mqtt.Client):
self._subscribe_callbacks.append((topic,callback)) self._subscribe_callbacks.append((topic,callback))
self.message_callback_add(topic, callback) self.message_callback_add(topic, callback)
@property def _on_connect2(self, *args):
def on_connect(self):
#TODO: called twice because of a boolean check before call
for (topic, callback) in self._subscribe_callbacks: for (topic, callback) in self._subscribe_callbacks:
self.subscribe(topic) self.subscribe(topic)
return self._on_connect for func in self._on_connect_callbacks:
func(self, *args)
@on_connect.setter def add_on_connect_callback(self, func):
with self._callback_mutex:
self._on_connect_callbacks.append(func)
@mqtt.Client.on_connect.setter
def on_connect(self, func): def on_connect(self, func):
with self._callback_mutex: with self._callback_mutex:
self._on_connect = func self._on_connect = func
class MQTTApp: class MQTTApp:
""" Manage MQTT connection and on topic callback with help of the @topic decorator """ """ Manage MQTT connection and on topic callback with help of the @topic decorator """