From ccc252e5b93801ba5f34e15e297d192743356429 Mon Sep 17 00:00:00 2001 From: "DSTO\\pivatom" Date: Thu, 10 Jan 2019 14:55:31 +1030 Subject: [PATCH] Add methods for callbacks to the mqtt client. --- Messaging/mqttsession.py | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) 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: