diff --git a/Messaging/mqttsession.py b/Messaging/mqttsession.py index b7366f2..7353eaf 100644 --- a/Messaging/mqttsession.py +++ b/Messaging/mqttsession.py @@ -1,11 +1,28 @@ import paho.mqtt.client as mqtt +""" +Wrapper module for paho mqtt library, providing a singleton instance of the client to be used. +Also adds some convenience functions such as having multiple connected callbacks, +and managing whether the client is still connected. +""" + + client = mqtt.Client() host = None -""" -Wrapper module for paho mqtt library, providing a singleton instance of the client to be used. -""" +connect_callbacks = [] +disconnect_callbacks = [] + +def on_connect(client, userdata, flags, rc): + print("Connected with result code " + str(rc)) + if rc == 0: + global connected + connected = True + + for callback in connect_callbacks: + callback() + + client.subscribe('hello/test', qos=1) # Arguably not needed, just want to make the client static, but here anyway. def connect(): @@ -16,6 +33,14 @@ def connect(): client.connect(host, port=1883, keepalive=60, bind_address="") client.loop_start() +def add_connect_callback(callback): + global connect_callbacks + connect_callbacks += callback + connectted = True + +def add_disconnect_callback(callback): + global + def disconnect(): global client if client is not None: @@ -24,6 +49,13 @@ def disconnect(): else: print("Error: Client is not initialised.") +def on_disconnect(client, userdata, rc): + if rc != 0: + print("Unexpected disconnection.") + + global connected + connected = False + def Client(): global client if client is None: