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 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(): global client if client is None or host is None: print("Error: Client and/or host are not initialised.") else: 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: client.loop_stop() client.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: client = mqtt.Client() return client