Add methods for callbacks to the mqtt client.

This commit is contained in:
DSTO\pivatom
2019-01-10 14:55:31 +10:30
parent 5e7e79e9a9
commit ccc252e5b9

View File

@@ -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: