def initMQTT(): topic = config.MQTT_TOPIC bTopic = bytes(topic, 'UTF-8') c = MQTTClient(config.MQTT_CLIENT_ID, config.MQTT_SERVER, user=secrets.MQTT_USER, password=secrets.MQTT_PASS) # Print diagnostic messages when retries/reconnects happens c.DEBUG = False c.set_callback(sub_cb) # Connect to server, requesting not to clean session for this # client. If there was no existing session (False return value # from connect() method), we perform the initial setup of client # session - subscribe to needed topics. Afterwards, these # subscriptions will be stored server-side, and will be persistent, # (as we use clean_session=False). # # There can be a problem when a session for a given client exists, # but doesn't have subscriptions a particular application expects. # In this case, a session needs to be cleaned first. See # example_reset_session.py for an obvious way how to do that. # # In an actual application, it's up to its developer how to # manage these issues. One extreme is to have external "provisioning" # phase, where initial session setup, and any further management of # a session, is done by external tools. This allows to save resources # on a small embedded device. Another extreme is to have an application # to perform auto-setup (e.g., clean session, then re-create session # on each restart). This example shows mid-line between these 2 # approaches, where initial setup of session is done by application, # but if anything goes wrong, there's an external tool to clean session. if not c.connect(clean_session=True): c.subscribe(bTopic) return c
class MQTTlocal: __slots__ = ('host', 'port', 'topic', 'client') def __init__(self, name, host, port, pub_topic, sub_topic): self.sub_topic = sub_topic self.pub_topic = pub_topic self.host = host self.port = port self.client = MQTTClient(name, host, port) self.client.set_callback(sub_cb) self._connect() self.client.subscribe(topic=self.sub_topic) def _connect(self): print("Connecting to %s:%s" % (self.host, self.port)) self.client.connect() print("Connection successful") def on_next(self, x): data = bytes(json.dumps(x), 'utf-8') self.client.publish(bytes(self.pub_topic, 'utf-8'), data) def on_completed(self): print("mqtt_completed, disconnecting") self.client.disconnect() def on_error(self, e): print("mqtt on_error: %s, disconnecting" % e) self.client.disconnect() def check_msg(self): print("Check messages") self.client.check_msg()
def main(): led = Pin(2, Pin.OUT, value=1) def sub_cb(topic, msg): led.off() # actually on utime.sleep_ms(500) led.on() # actually off sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect(WLAN_ESSID, WLAN_PASSWORD) while not sta_if.isconnected(): utime.sleep_ms(1) print("WLAN Connected") c = MQTTClient(MQTT_ID, MQTT_SERVER, user=MQTT_USERNAME, password=MQTT_PASSWORD) c.DEBUG = True c.set_callback(sub_cb) c.connect(clean_session=False) c.subscribe(MQTT_TOPIC) print("MQTT Connected") gc.collect() while True: c.check_msg() utime.sleep_ms(10) c.disconnect()
def initialise(settings=configuration.mqtt.settings): global client, keepalive, topic_path client_id = get_unique_id() keepalive = settings["keepalive"] topic_path = settings["topic_path"] if topic_path == "$me": topic_path = get_topic_path(namespace) client = MQTTClient(client_id, settings["host"], settings["port"], keepalive=keepalive) client.set_callback(on_message) client.set_last_will(topic_path + "/state", "nil") client.connect() # TODO: Catch exception event.add_timer_handler(mqtt_ping_handler, keepalive * 1000) if settings["mqtt_insecure_exec"]: add_message_handler(on_exec_message, "$me/exec") for topic in settings["topic_subscribe"]: if topic.startswith("$all/"): topic = "+/+/+" + topic[4:] if topic.startswith("$me/"): topic = topic_path + topic[3:] client.subscribe(topic) print(" ###### MQTT: Connected to %s: %s" % (settings["host"], topic_path))
class MQTTReader: __slots__ = ('host', 'port', 'topic', 'client') def __init__(self, name, host, port, topic): self.topic = topic self.host = host self.port = port self.client = MQTTClient(name, host, port) self.client.set_callback(sub_cb) self._connect() self.client.subscribe(topic=self.topic) def _connect(self): print("Connecting to %s:%s" % (self.host, self.port)) self.client.connect() print("Connection successful") def on_completed(self): print("mqtt_completed, disconnecting") self.client.disconnect() def on_error(self, e): print("mqtt on_error: %s, disconnecting" % e) self.client.disconnect() def disconnect(self): self.client.disconnect() def wait_msg(self): self.client.wait_msg()
def main(): machine.freq(160000000) c = MQTTClient("HSBNE-small-sign", "10.0.1.253", user="", password="") c.set_callback(sub_cb) c.set_last_will("devices/small-sign/state", "offline", retain=True) c.connect() c.subscribe("devices/small-sign/#") c.publish("devices/small-sign/state", "online", retain=True) c.publish("devices/main-sign/ip", network.WLAN(network.STA_IF).ifconfig()[0], retain=True) sign = SignMatrix() try: while True: while c.check_msg(): pass if enable != 0: sign.set_delay(delay) sign.scroller(text) else: c.wait_msg() except KeyboardInterrupt: c.publish("devices/small-sign/state", "offline", retain=True, qos=1) c.disconnect()
def mqtt_client(server): # setup the BUTton and LED global led import machine, ubinascii, utime machine_id = b'ESP8266-%s' % ubinascii.hexlify( machine.unique_id() ) led = machine.Pin(2) led.init(machine.Pin.OUT) button = machine.Pin(0) button.init(machine.Pin.IN, machine.Pin.PULL_UP) # setup Mosquitto from umqtt.robust import MQTTClient mqttc = MQTTClient(machine_id, server) mqttc.connect() mqttc.set_last_will(b'test/bradley_edu', b'%s signoff 1' % ( machine_id ) ) mqttc.set_callback(callback_function) mqttc.subscribe(b'test/#') # run Mosquitto butstate = button.value() while True: if button.value()!=butstate: butstate = button.value() mqttc.publish(b'test/bradley_edu', b'%s B0 %s' % ( machine_id , str(butstate) ) ) mqttc.check_msg() # this will check for messages and call the callback function if needed utime.sleep_ms(20) # time to allow the callback function to do its job to avoid calling multiple instances # we actually never quit but this is how shutdown should look like mqttc.disconnect()
def connect_mqtt(): try: with open(KEY_FILE, "r") as f: key = f.read() print("MQTT received KEY") with open(CERT_FILE, "r") as f: cert = f.read() print("MQTT received CERTIFICATE") mqtt_client = MQTTClient(client_id=MQTT_CLIENT_ID, server=MQTT_HOST, port=MQTT_PORT, keepalive=5000, ssl=True, ssl_params={"cert":cert, "key":key, "server_side":False}) mqtt_client.connect() mqtt_client.set_callback(sub_cb) print("MQTT is connected") mqtt_client.subscribe(SHADOW_GET_TOPIC) print("Subscribed to %s topic" % (SHADOW_GET_TOPIC)) while True: mqtt_client.publish(SHADOW_UPDATE_TOPIC, str(read_sensor_value())) mqtt_client.wait_msg() except Exception as e: print('Cannot connect to MQTT ' + str(e)) raise
def connect_and_subscribe(sub_callback=None): """Connectes to MQTT-Host and subscribes to topics. MQTT-IP, -Port and Topics must be defined in credentials.json. Args: sub_callback (func(topic, msg), optional): Callback-Function when message is recieved. Returns: MQTT-Client """ with open("credentials.json", "r") as f: credentials = ujson.load(f) try: from umqtt.robust import MQTTClient except ImportError as e: import upip upip.install('micropython-umqtt.simple') upip.install('micropython-umqtt.robust') from umqtt.robust import MQTTClient # Set Options for MQTT-Broker client = MQTTClient(ubinascii.hexlify(machine.unique_id()), credentials["mqtt"]["host"], credentials["mqtt"]["port"]) # Set callback to handle Messages if sub_callback is not None: client.set_callback(sub_callback) # Connect client.connect(clean_session=False) for topic in credentials["mqtt"]["topics"]: client.subscribe(topic) time.sleep(3) client.check_msg() return client
class AsyncMqttMessages(object): def __init__(self): config = Config() self.heatmessage = {'Heating': ''} self.tempMessage = {'TempIN': '', 'TempOUT': ''} self.mqttID = config.mqttID self.mqttBroker = config.mqttBroker self.user = config.mqttUser self.password = config.mqttPassword self.client = MQTTClient(self.mqttID, self.mqttBroker, 1883, self.user, self.password) self.client.connect() self.client.set_callback(sub_cb) self.client.subscribe(topic="home/attackHeater/stat") def publishHeat(self, message): self.heatmessage['Heating'] = message m = ujson.dumps(self.heatmessage) self.client.publish(topic="home/attacHeater/heating", msg=m) def publishTemp(self, temp_in, temp_out): self.tempMessage['TempIN'] = temp_in self.tempMessage['TempOUT'] = temp_out m = ujson.dumps(self.tempMessage) self.client.publish(topic="home/attacHeater/heating", msg=m)
def mqtt_server(): global client global client_int if client == None: client = MQTTClient(client_id='1ebe9d4c-9e49-4bf4-8abb-f322009c377c', server='m16.cloudmqtt.com', port=17330, user='******', password='******') #client = MQTTClient(client_id='1ebe9d4c-9e49-4bf4-8abb-f322009c377c', server='m16.cloudmqtt.com', port=17661, user='******', password='******') client.set_callback(sub_cb) client.connect() print("Connected to MQTT Client") # the first argument is the topic, the second is the message client.subscribe("Sensor_Data") client_int = Timer(3) client_int.init(period=1000, mode=Timer.PERIODIC, callback=client_interrupt) #client.publish("SessionID", b"four"*8, True, 0) client.publish("SessionID", AES.sessionID, True, 0) client_interrupt(None)
class Connect: def __init__(self): self.sta = network.WLAN(network.STA_IF) self.ConnectWiFi() self.c = MQTTClient("umqtt_client", "192.168.110.51") self.ConnectMQTT() def ConnectMQTT(self): print("connecting to mqtt ROBUST") self.c.set_callback(self.deb) self.c.connect() self.c.subscribe("test/msg") def Emit(self): emi = MQTTClient('emiter', "192.168.110.51") emi.connect() emi.publish("test/msg", "from nodeMCU !") emi.disconnect() def deb(self, topic, msg): print((topic, msg)) def ConnectWiFi(self): self.sta.active(True) self.sta.connect('g.tec', '#g.tec#17!') print("connecting to WiFi at gtec") while self.sta.isconnected() == False: pass print("Connection successful") print(self.sta.ifconfig())
def device_connect(): global MQTT_CLIENT try: #all this below runs once ,equivalent to Arduino's "setup" function) with open(KEY_FILE, "r") as f: key = f.read() print("set private Key") with open(CERT_FILE, "r") as f: cert = f.read() print("set client Cert") MQTT_CLIENT = MQTTClient(client_id=MQTT_CLIENT_ID, server=MQTT_HOST, port=MQTT_PORT, keepalive=5000, ssl=True, ssl_params={ "cert": cert, "key": key, "server_side": False }) MQTT_CLIENT.connect() print('MQTT Connected') MQTT_CLIENT.set_callback(sub_cb) MQTT_CLIENT.subscribe(SUB_TOPIC) print('Subscribed to %s as the incoming topic' % (SUB_TOPIC)) return MQTT_CLIENT except Exception as e: print('Cannot connect MQTT: ' + str(e)) raise
def connect_and_subscribe(): global client_id, mqtt_server, topic_sub client = MQTTClient(client_id, mqtt_server) client.set_callback(sub_cb) client.connect() client.subscribe(topic_sub) print('Connected to: %s \nSubscribed to: %s' % (mqtt_server, topic_sub)) return client
def init_mqtt(): log("MQTT Connecting") cli = MQTTClient(config.mqtt_name, config.mqtt_server) cli.DEBUG = True cli.set_callback(sub_cb) cli.connect() cli.subscribe(config.mqtt_subscribe) log("MQTT Connected") return cli
def connect_and_subscribe(): global client print('Connecting to {}:{} as user {} with password {}'.format(config.broker, config.port, config.user, config.password)) client = MQTTClient(client_id, config.broker, port=config.port, user=config.user, password=config.password) client.set_callback(callback) if not client.connect(clean_session=False): print("Created new session to {}".format(config.broker)) topic = b"/" + machine_id + b"/cmd/+" client.subscribe(topic) print("Subscribed to {}".format(topic))
class MessageBus: def __init__(self, on_message_handler): self._on_message_handler = on_message_handler self._device_id = config["device_id"] self._client = MQTTClient(client_id=self._device_id, server=config["broker"], ssl=False) self._client.set_message_received_handler(self._on_message) self._client.set_connected_handler(self._on_connected) def connect(self): connected = False while not connected: try: self._client.connect() connected = True except Exception as exc: logger.log("E9 %r" % exc) time.sleep(0.5) # The callback for when MQTT client has connected def _on_connected(self): self._client.subscribe("to/{}/#".format(self._device_id)) def publish(self, component_id, payload): payload = str(payload) self._client.publish( "from/{}/{}".format(self._device_id, component_id), payload) def service(self): self._client.check_msg() # The callback for when a PUBLISH message is received from the server. def _on_message(self, topic, payload): try: topic = str(topic, "ascii") payload = self._coerce_payload(str(payload, "ascii")) parts = topic.split("/") component_id = parts[2] is_set = True if len(parts) == 4 and parts[3] == "set" else False payload = payload if is_set else None self._on_message_handler(component_id, payload) except Exception as exc: logger.log("E8 %s" % exc) @staticmethod def _coerce_payload(payload: str): bool_test = payload.lower() if bool_test == "true": payload = True elif bool_test == "false": payload = False return payload
def connectMQTT(): try: client = MQTTClient(mqttClientId, mqttHost, mqttPort, mqttUsername, mqttPassword) client.set_callback(alarm) client.connect() client.subscribe('alarm') return client except: return False
def mqttCollectMessages( inMqttBroker=CONFIG["mqttBroker"], inMqttClientUniqueId=CONFIG["mqttClientUniqueId"], inMqttTopic=CONFIG["mqttConfigTopic"], ): global MQTTRECEIVED MQTTRECEIVED = [] outMqttData = [] countMsg = 0 mqttClient = MQTTClient( inMqttClientUniqueId, inMqttBroker, ssl=CONFIG["mqttSSL"], user=CONFIG["mqttUser"], password=CONFIG["mqttPassword"], ) mqttLastWill = ("-1, -1, -1, -1, -1, -1, -1, -1, -1, " + inMqttClientUniqueId + ", " + MESSAGE_TYPES["mqttErrorMessage"] + ", " + "UngracefulDisconnect, " + "Ungraceful disruption of MQTT collect, ") mqttClient.set_last_will(inMqttTopic, mqttLastWill) mqttClient.set_callback(mqttCallback) print("Trying to collect the MQTT Messages.", inMqttTopic) print("MQTTSTATS", MQTTSTATS) try: mqttClient.connect() print("Subscribe to", inMqttTopic) mqttClient.subscribe(topic=inMqttTopic) while CONFIG["mqttReceivedMax"] > countMsg: print("Checking for MQTT message") mqttClient.check_msg() countMsg += 1 time.sleep_ms(200) MQTTSTATS["receivedMsgs"] += len(MQTTRECEIVED) print("MQTTRECEIVED", MQTTRECEIVED) mqttProcess() print("Message(s) of MQTT were processed.") print("MQTTSTATS", MQTTSTATS) time.sleep(1) mqttClient.disconnect() except Exception as e: print("MQTT collections failed.") sys.print_exception(e) errorMessage = mqttErrorMessage( inMqttClientUniqueId, "Exception", "MQTTClientConnectError", str(e), ) outMqttData.append(errorMessage) return outMqttData
class MQTTData: def __init__(self, server, user, password, sname): self.topic = bytes('{}/feeds/{}-{{:s}}'.format(user, sname.lower()), 'utf-8').format client_id = hexlify(unique_id()).upper() self.client = MQTTClient(client_id, server, user=user, password=password) self.client.set_callback(self.buttons_cb) self.client.connect() # Subscribe to topics LOG.debug("Subscribe: %s", self.topic('force')) self.client.subscribe(self.topic('force')) def buttons_cb(self, topic, value): LOG.info('Button pressed: %s %s', topic.decode(), value.decode()) if topic == self.topic('force') and value.upper() == b'TRUE': FAN().status(FAN.ON) elif topic == self.topic('force') and value.upper() == b'FALSE': FAN().status(FAN.AUTOMATIC) async def run(self): sensor = EnvSensor() if SAMPLING > 20: nb_samples = 7 sampling = 1000 * (SAMPLING / nb_samples) else: nb_samples = 1 sampling = SAMPLING sampling = int(sampling) while True: try: for key in ['temperature', 'pressure', 'humidity']: value = "{:.2f}".format(getattr(sensor, key)) self.client.publish(self.topic(key), bytes(value, 'utf-8')) LOG.info('Publishing: %s: %s', key, value) await asyncio.sleep_ms(10) self.client.check_msg() except OSError as exc: LOG.error('MQTT %s %s', type(exc).__name__, exc) await asyncio.sleep_ms(750) finally: for _ in range(nb_samples): self.client.check_msg() await asyncio.sleep_ms(sampling) gc.collect()
def connect(): global value global pvalue value = {} pvalue = {} client = MQTTClient('ev3', SERVER) client.connect() client.set_callback(on_message) client.subscribe(ev3) send_state() check_message_thread = Thread(target=check_message, args=(client, )) check_message_thread.start()
def Conexion_MQTT(): #client_id = b"Covid_1" + ubinascii.hexlify(machine.unique_id()) client_id = CONFIG["client_id"] mqtt_server = CONFIG["broker"] port_mqtt = 1883 user_mqtt = None #Si su servidor no necesita usuario escribe None sin comillas pswd_mqtt = None #Si su servidor no necesita contraseña escribe None sin comillas client = MQTTClient(client_id, mqtt_server,port_mqtt,user_mqtt,pswd_mqtt) client.DEBUG = True client.set_callback(form_sub) client.connect(True) client.subscribe(CONFIG["subscribe"]) print('Conectado a %s' % mqtt_server) return client
def connect_and_subscribe(client_id, broker_ip, broker_port, sub_callback=None, sub_topics=[]): # Set Options for MQTT-Broker client = MQTTClient(client_id, broker_ip, broker_port) # Set callback to handel Messages if sub_callback is not None: client.set_callback(sub_callback) # Connect client.connect(clean_session=False) for topic in sub_topics: client.subscribe(topic) time.sleep(3) client.check_msg() return client
def _create_client(self): try: client = MQTTClient('terrarium', config.MQTT_HOST, user=config.MQTT_USER, password=config.MQTT_PASSWORD, port=config.MQTT_PORT) client.set_callback(self.on_message) if not client.connect(clean_session=False): print("MQTT new session being set up.") client.subscribe('cmnd/terrarium/#', qos=1) return client except Exception as e: print(e) return None
def start_mqtt(self, server="ops-senpai.5z.fyi"): c = MQTTClient("dog", "ops-senpai.5z.fyi", port=30001, user="******", password="******") c.set_callback(self._sub_cb) c.connect() c.subscribe(b"printme") try: while True: # Blocking wait for message c.wait_msg() finally: c.disconnect()
def mqtt_reconnect(): # Create an instance of MQTTClient global client client = MQTTClient(CONFIG['CLIENT_ID'], CONFIG['MQTT_BROKER'], user=CONFIG['USER'], password=CONFIG['PASSWORD'], port=CONFIG['PORT']) # Attach call back handler to be called on receiving messages client.DEBUG = True client.set_callback(onMessage) client.connect(clean_session=True) client.subscribe(CONFIG['TOPIC']) print("ESP8266 is Connected to %s and subscribed to %s topic" % (CONFIG['MQTT_BROKER'], CONFIG['TOPIC']))
def main(): mqtt = MQTTClient(CLIENT_ID, mqtt_broker, user=mqtt_user, password=mqtt_pass) mqtt.set_callback(sub_cb) print('connecting MQTT') mqtt.connect() mqtt.subscribe('fmi/kumpula/t2m') mqtt.check_msg() time.sleep(1) #mqtt.check_msg() while True: mqtt.check_msg() time.sleep(300) mqtt.disconnect()
def initialise(settings): global client, keepalive client_id = get_unique_id() keepalive = settings["keepalive"] topic_path = settings["topic_path"] client = MQTTClient(client_id, settings["host"], settings["port"], keepalive=keepalive) client.set_callback(on_message) client.set_last_will(topic_path + "/state", "nil") client.connect() for topic in settings["topic_subscribe"]: client.subscribe(topic) print("Connected to MQTT: %s: %s" % (settings["host"], topic_path))
class MQTTData: def __init__(self, server, user, password, sname): self.topic = bytes('/'.join([user, 'feeds/{}_{{:s}}'.format(sname)]), 'utf-8') client_id = hexlify(unique_id()).upper() self.client = MQTTClient(client_id, server, user=user, password=password) self.client.set_callback(self.buttons_cb) self.client.connect() # Subscribe to topics for topic in ['btn', 'sampling']: mqtt_button = self.topic.format(topic) self.client.subscribe(mqtt_button) self.sampling = SAMPLING mqtt_sampling = self.topic.format('sampling') self.client.publish(mqtt_sampling, bytes(str(self.sampling), 'utf-8')) async def check_msg(self): while True: LOG.info('MQTT check message') self.client.check_msg() await asyncio.sleep_ms(5000) def buttons_cb(self, topic, value): LOG.info('Button pressed: %s %s', topic.decode(), value.decode()) if topic == self.topic.format('sampling'): self.sampling = int(value) elif topic == self.topic.format('btn') and value == b'reset': reset() async def run(self, sensor): while True: try: data = sensor.get() for key, value in data.items(): topic = self.topic.format(key) self.client.publish(topic, bytes(str(value), 'utf-8')) LOG.info('Publishing: (%s, %f)', key, value) except OSError as exc: LOG.error('MQTT %s %s', type(exc).__name__, exc) await asyncio.sleep_ms(750) else: LOG.info("Sampling time: %d", self.sampling) await asyncio.sleep(self.sampling)
def main(server="broker.hivemq.com", topic=b"testtopic/1"): global msgRxd global msgTime msgCnt = 0 connectOut = machine.Pin(13, machine.Pin.OUT) updateLedState(connectOut, msgCnt) print("Connecting to MQTT server: ", server) c = MQTTClient("umqtt_client", server) c.set_callback(sub_cb) c.connect() print("Subscribing to: ", topic) c.subscribe(topic) lastMsgTime = msgTime while True: # Set to True/False depending on whether you want to test # blocking I/O or not. NOTE: Setting to True makes it # difficult to Control-C when using WebREPL. if False: # Blocking wait for message print("Waiting for new message from topic: ", topic) c.wait_msg() else: # Non-blocking wait for message print("Checking for new message from topic: ", topic) c.check_msg() mtime = msgTime msg = msgRxd if mtime != lastMsgTime and msgRxd != None: print((topic, msg)) lastMsgTime = mtime msgCnt = msgCnt + 1 updateLedState(connectOut, msgCnt) else: # Then need to sleep to avoid 100% CPU usage (in a real # app other useful actions would be performed instead) time.sleep_ms(1000) c.disconnect()
class DoorAlarm(object): def __init__(self): self.config = None self.p0 = machine.Pin(2, machine.Pin.OUT) def load_config(self): with open('cfg.json', 'r') as cfg: self.config = ujson.load(cfg) def connect_wifi(self): ap_if = network.WLAN(network.AP_IF) ap_if.active(False) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) if sta_if.isconnected(): sta_if.disconnect() sta_if.connect(self.config['ssid'], self.config['passwd']) for _ in range(20): time.sleep(1) if sta_if.isconnected(): return print('Unable to connect to AP: {}'.format(ssid)) sys.exit(1) def mqtt_callback(self, topic, msg): self.p0.value(not self.p0.value()) def mqtt_subscribe(self): client_id = b'tom_' + ubinascii.hexlify(machine.unique_id()) self.mqtt = MQTTClient(client_id, self.config['host'], port=int(self.config['port'])) self.mqtt.set_callback(self.mqtt_callback) self.mqtt.connect() self.mqtt.subscribe(self.config['topic'])
c.set_callback(sub_cb) # Connect to server, requesting not to clean session for this # client. If there was no existing session (False return value # from connect() method), we perform the initial setup of client # session - subscribe to needed topics. Afterwards, these # subscriptions will be stored server-side, and will be persistent, # (as we use clean_session=False). # # There can be a problem when a session for a given client exists, # but doesn't have subscriptions a particular application expects. # In this case, a session needs to be cleaned first. See # example_reset_session.py for an obvious way how to do that. # # In an actual application, it's up to its developer how to # manage these issues. One extreme is to have external "provisioning" # phase, where initial session setup, and any further management of # a session, is done by external tools. This allows to save resources # on a small embedded device. Another extreme is to have an application # to perform auto-setup (e.g., clean session, then re-create session # on each restart). This example shows mid-line between these 2 # approaches, where initial setup of session is done by application, # but if anything goes wrong, there's an external tool to clean session. if not c.connect(clean_session=False): print("New session being set up") c.subscribe(b"foo_topic") while 1: c.wait_msg() c.disconnect()