async def _async_publish_to_hass_discovery( client: Client, data: dict, discovery_manager: HassDiscovery) -> None: """Publish data to appropriate topics for Home Assistant Discovery.""" LOGGER.debug( "Publishing according to Home Assistant MQTT Discovery standard") try: async with client: tasks = [] for key, value in data.items(): config_payload = discovery_manager.get_config_payload(key) config_topic = discovery_manager.get_config_topic(key) tasks.append( client.publish(config_topic, _generate_payload(config_payload))) tasks.append( client.publish( config_payload["availability_topic"], _generate_payload("online"), )) tasks.append( client.publish(config_payload["state_topic"], _generate_payload(value))) await asyncio.gather(*tasks) except MqttError as err: LOGGER.error("Error while publishing to HASS Discovery: %s", err) return LOGGER.info("Published to HASS discovery: %s", data)
async def advanced_example(): # We 💛 context managers. Let's create a stack to help # us manage them. async with AsyncExitStack() as stack: # Keep track of the asyncio tasks that we create, so that # we can cancel them on exit tasks = set() stack.push_async_callback(cancel_tasks, tasks) # Connect to the MQTT broker client = Client("144.217.242.17") await stack.enter_async_context(client) #client.will_set(serial_no+"/connection","Offline",1,retain=False) # Messages that doesn't match a filter will get logged here messages = await stack.enter_async_context( client.unfiltered_messages()) task = asyncio.create_task(log_messages(client, messages)) tasks.add(task) # Subscribe to topic(s) # 🤔 Note that we subscribe *after* starting the message # loggers. Otherwise, we may miss retained messages. await client.subscribe(serial_no + "/check_connection") task = asyncio.create_task(publish(client, "connection", "Online")) tasks.add(task) task = asyncio.create_task(post_gps(client, "gps")) tasks.add(task) # Wait for everything to complete (or fail due to, e.g., network # errors) await asyncio.gather(*tasks)
async def advanced_example(): # We 💛 context managers. Let's create a stack to help # us manage them. async with AsyncExitStack() as stack: # Keep track of the asyncio tasks that we create, so that # we can cancel them on exit tasks = set() stack.push_async_callback(cancel_tasks, tasks) tls_ctx = ssl.create_default_context( cafile="/srv/security/iot-hub-ca.pem") tls_ctx.load_cert_chain( "/srv/security/device-home-office-crt.pem", keyfile="/srv/security/device-home-office-key.pem", ) # Connect to the MQTT broker client = Client( "iot.fr-par.scw.cloud", port=8883, client_id="50ce1f12-ef04-4e25-806c-3c51aa3f044a", tls_context=tls_ctx, ) await stack.enter_async_context(client) # You can create any number of topic filters topic_filters = ( "floors/+/humidity", "floors/rooftop/#" # 👉 Try to add more filters! ) for topic_filter in topic_filters: # Log all messages that matches the filter manager = client.filtered_messages(topic_filter) messages = await stack.enter_async_context(manager) template = f'[topic_filter="{topic_filter}"] {{}}' task = asyncio.create_task(log_messages(messages, template)) tasks.add(task) # Messages that doesn't match a filter will get logged here messages = await stack.enter_async_context( client.unfiltered_messages()) task = asyncio.create_task(log_messages(messages, "[unfiltered] {}")) tasks.add(task) # Subscribe to topic(s) # 🤔 Note that we subscribe *after* starting the message # loggers. Otherwise, we may miss retained messages. await client.subscribe("floors/#") # Publish a random value to each of these topics topics = ( "floors/basement/humidity", "floors/rooftop/humidity", "floors/rooftop/illuminance", # 👉 Try to add more topics! ) task = asyncio.create_task(post_to_topics(client, topics)) tasks.add(task) # Wait for everything to complete (or fail due to, e.g., network # errors) await asyncio.gather(*tasks)
async def startSim(): global client, stack # change entries to modify test beds = [ ("W1", "1"), ("W1", "2"), ("W1", "3"), ("W1", "4"), ] async with AsyncExitStack() as stack: # Connect to the MQTT broker client = Client(BROKER_ADDRESS) await stack.enter_async_context(client) tasks = set() stack.push_async_callback(cancel_tasks, tasks) outbound_topics = [ "+/+/patientDetails", "+/+/HR", "+/+/spO2", "+/+/diaBP", "+/+/sysBP", "+/+/ppg", "+/+/ecg", ] for ot in outbound_topics: manager = client.filtered_messages(ot) messages = await stack.enter_async_context(manager) template = f'Outbound -- [topic="{{}}"] {{}}' task = asyncio.create_task(log_messages(messages, template)) tasks.add(task) inbound_topics = ["+/+/sendDetails"] for it in inbound_topics: manager = client.filtered_messages(it) messages = await stack.enter_async_context(manager) template = f'Inbound -- [topic="{{}}"] {{}}' task = asyncio.create_task(log_messages(messages, template)) tasks.add(task) # Messages that doesn't match a filter will get logged here messages = await stack.enter_async_context( client.unfiltered_messages()) task = asyncio.create_task( log_messages(messages, f'Other -- [topic="{{}}"] {{}}')) tasks.add(task) await client.subscribe('#') # subscribe to all messages for bed in beds: tasks.add(asyncio.create_task(onboardPatient(bed, client))) tasks.add(asyncio.create_task(startHRProducer(bed, client))) tasks.add(asyncio.create_task(startBPProducer(bed, client))) tasks.add(asyncio.create_task(startSpO2Producer(bed, client))) tasks.add(asyncio.create_task(startECGProducer(bed, client))) await asyncio.gather(*tasks)
async def listen(self): async with AsyncExitStack() as stack: # Track tasks tasks = set() stack.push_async_callback(cancel_tasks, tasks) # Connect to the MQTT broker client = Client(self.host, self.port, username=self.username, password=self.password) await stack.enter_async_context(client) logging.info(f'MQTT client connected') # Add tasks for each data source handler for ds in self.data_sources: # Get handlers from data source ds_listeners = ds.listeners() # Iterate through data source listeners and convert to # 'prime' listeners for each topic for listener in ds_listeners: topic = listener.topic funcs = listener.handlers if topic in self.topics: # Add these handlers to existing top level topic handler logging.debug( f'Adding handlers for existing prime Listener: {topic}' ) ext_topic = self.topics[topic] ext_topic.handlers.extend(funcs) else: # Add this instance as a new top level handler logging.debug( f'Creating new prime Listener for topic: {topic}') self.topics[topic] = MQTTListener(topic, funcs) # Add handlers for each topic as a filtered topic for topic, listener in self.topics.items(): manager = client.filtered_messages(topic) messages = await stack.enter_async_context(manager) task = asyncio.create_task(self.parse_messages(messages)) tasks.add(task) # Subscribe to all topics # Assume QoS 0 for now all_topics = [(t, 0) for t in self.topics.keys()] logging.info(f'Subscribing to MQTT {len(all_topics)} topic(s)') logging.debug(f'Topics: {all_topics}') try: await client.subscribe(all_topics) except ValueError as err: logging.error(f'MQTT Subscribe error: {err}') # Gather all tasks await asyncio.gather(*tasks) logging.info(f'Listening for MQTT updates')
async def main_loop(): global stop_gracefully # https://pypi.org/project/asyncio-mqtt/ logger.debug("Starting main event processing loop") cfg = Cfg() mqtt_broker_ip = cfg.mqtt_host or const.MQTT_DEFAULT_BROKER_IP mqtt_client_id = cfg.mqtt_client_id or const.MQTT_CLIENT_ID_DEFAULT mqtt_send_q = asyncio.Queue(maxsize=256) events_q = asyncio.Queue(maxsize=256) # We 💛 context managers. Let's create a stack to help # us manage them. async with AsyncExitStack() as stack: # Keep track of the asyncio tasks that we create, so that # we can cancel them on exit tasks = set() stack.push_async_callback(cancel_tasks, tasks) # Connect to the MQTT broker client = Client(mqtt_broker_ip, client_id=mqtt_client_id) await stack.enter_async_context(client) messages = await stack.enter_async_context(client.unfiltered_messages()) task = asyncio.create_task(handle_mqtt_messages(messages, events_q)) tasks.add(task) run_state = RunState() for topic, attrs in cfg.topics.items(): run_state.states[topic] = TopicState(topic, **attrs) await client.subscribe(topic) task = asyncio.create_task(handle_mqtt_publish(client, mqtt_send_q)) tasks.add(task) task = asyncio.create_task(periodic_timer_refresh_publish(events_q)) tasks.add(task) task = asyncio.create_task(periodic_timer_expirations(events_q)) tasks.add(task) task = asyncio.create_task(periodic_timer_reelection(events_q)) tasks.add(task) task = asyncio.create_task(handle_jobs(run_state, events_q, mqtt_send_q)) tasks.add(task) # Wait for everything to complete (or fail due to, e.g., network errors) await asyncio.gather(*tasks) logger.debug("all done!")
async def advanced_example(): # We 💛 context managers. Let's create a stack to help # us manage them. async with AsyncExitStack() as stack: # Keep track of the asyncio tasks that we create, so that # we can cancel them on exit tasks = set() stack.push_async_callback(cancel_tasks, tasks) # Connect to the MQTT broker client = Client(broker) await stack.enter_async_context(client) # You can create any number of topic filters topic_filters = ( "Battle/#/Trainer1/", "Battle/#/Trainer2/" # 👉 Try to add more filters! ) for topic_filter in topic_filters: # Log all messages that matches the filter manager = client.filtered_messages(topic_filter) messages = await stack.enter_async_context(manager) template = f'[topic_filter="{topic_filter}"] {{}}' task = asyncio.create_task(log_messages(messages, template)) tasks.add(task) # Messages that doesn't match a filter will get logged here messages = await stack.enter_async_context( client.unfiltered_messages()) task = asyncio.create_task(log_messages(messages, "[unfiltered] {}")) tasks.add(task) # Subscribe to topic(s) # 🤔 Note that we subscribe *after* starting the message # loggers. Otherwise, we may miss retained messages. await client.subscribe("Battle/#") # Publish a random value to each of these topics topics = ( "Battle/BattleLog", "Battle/Trainer1/", "Battle/Trainer2/", # 👉 Try to add more topics! ) task = asyncio.create_task(post_to_topics(client, topics)) tasks.add(task) # Wait for everything to complete (or fail due to, e.g., network # errors) await asyncio.gather(*tasks)
async def handler(mqtt_hostname, mqtt_port, logger, context, topics, router): # defining an AsyncExitStack as stack to use with the asynccontextmanager async with AsyncExitStack() as stack: #set up a set of tasks the asyncio shall work through tasks = set() #defining what the asynccontextmanager shall do upon exit. stack.push_async_callback(cancel_tasks, tasks) #using the clientID as both clientID and base topic clientID = topics["clientID"] #TODO: Fix the asyncio_MQTT library with tuples to pass the certificates. #initializing a MQTT client LOG.info("Connect to MQTT-broker") client = Client(mqtt_hostname, port=mqtt_port, logger=logger, tls_context=context, client_id=clientID) router = teltonikaRUT9x(router["hostname"], router["username"], router["password"]) position = ColumbusV800() #putting the client into the asynccontextmanager await stack.enter_async_context(client) #Loop through all topics that we shall subscribe to topic_filters = topics["subscribe"] for topic_filter in topic_filters: #Use the filtered_messages to make an async generator manager = client.filtered_messages(topic_filter) #put the generator into the asynccontextmanager messages = await stack.enter_async_context(manager) template = f'[topic_filter="{topic_filter}"] {{}}' #set up a task task = asyncio.create_task(log_messages(messages, template)) tasks.add(task) #Make a list of topics with Qos 1 to feed into the client.subscribe subscribe_topics = [] for i in topic_filters: subscribe_topics.append((i, 1)) await client.subscribe(subscribe_topics) #create a task that sends the position on the MQTT with the clientID as a basis for topic task = asyncio.create_task( sendPosition(client, position, 0.2, clientID)) tasks.add(task) #add the signallogging to the async tasks task = asyncio.create_task(logSignal(router, 1)) tasks.add(task) # Wait for everything to complete (or fail due to, e.g., network # errors) await asyncio.gather(*tasks)
async def connect_to_mqtt_server(config): async with AsyncExitStack() as stack: # Keep track of the asyncio tasks that we create, so that # we can cancel them on exit tasks = set() stack.push_async_callback(cancel_tasks, tasks) if config.has_section('MQTT'): # Connect to the MQTT broker # client = Client("10.0.1.20", username="******", password="******") client = Client(config.get('MQTT', 'broker_address'), username=config.get('MQTT', 'usr'), password=config.get('MQTT', 'pswd')) await stack.enter_async_context(client) # Create angle fsm fsm = AngleFSM(config) # Messages that doesn't match a filter will get logged here messages = await stack.enter_async_context( client.unfiltered_messages()) task = asyncio.create_task( log_messages(messages, "[unfiltered] {}")) tasks.add(task) # Subscribe to chairState await client.subscribe("sensors/chairState") manager = client.filtered_messages('sensors/chairState') messages = await stack.enter_async_context(manager) task = asyncio.create_task( handle_sensors_chair_state(client, messages, fsm)) tasks.add(task) # Subscribe to config notification settings changes await client.subscribe("goal/update_data") manager = client.filtered_messages('goal/update_data') messages = await stack.enter_async_context(manager) task = asyncio.create_task( handle_goal_update_data(client, messages, fsm)) tasks.add(task) # Start periodic publish of chair state task = asyncio.create_task(publish_angle_fsm(client, fsm)) tasks.add(task) # Wait for everything to complete (or fail due to, e.g., network errors) await asyncio.gather(*tasks)
async def main(): while True: async with Client(**MQTT_CONF) as client: try: await announce(client) await client.publish( topic=ONLINE_TOPIC, payload='online', ) done, pending = await asyncio.wait([ process_msgs(client, topic_patt=SWITCH_SUBSCRIPTION, response_template=SWITCH_RESPONSE, parser=parse_msg), process_msgs(client, topic_patt=RAW_SUBSCRIPTION, response_template=RAW_RESPONSE, parser=parse_raw), process_noolite(client), ], return_when=FIRST_EXCEPTION) for x in done: await x except Exception as exc: lg.exception('in main loop') finally: await client.publish(**OFFLINE) lg.warning('reconnecting') await asyncio.sleep(RECONNECT_TIME)
def create_client(self) -> None: """Create the asyncio client.""" self.asyncio_client = AsyncioClient( self.host, self.port, **self.client_options, )
async def init_client(self, cbpi): async with Client("localhost", will=Will(topic="cbpi/diconnect", payload="MY CLIENT")) as client: async with client.filtered_messages("cbpi/#") as messages: await client.subscribe("cbpi/#") async for message in messages: await self.cbpi.actor.on("YwGzXvWMpmbLb6XobesL8n")
async def _send_event(self, event: BarcodeEvent): json = barcode_event_to_json(event) async with Client(hostname=self.host, port=self.port, username=self.user, password=self.password, client_id=self.client_id) as client: await client.publish(self.topic, json, self.qos, self.retain) LOGGER.debug(f"Notified {self.host}:{self.port}: {event.barcode}")
async def main(): position = 100 angle = 45 async with Client("test.mosquitto.org") as client: for topic in topics: message = {"pos": position, "ang": angle} angle += 10 print(f"topic:{topic} {message}") await client.publish(topic, json.dumps(message), qos=1) await asyncio.sleep(1)
async def run(self) -> None: async with Client(self.args.mqtt_host, port=self.args.mqtt_port) as client: self.logger.info( f"Connected to {self.args.mqtt_host}:{self.args.mqtt_port}" ) tasks = [ self.handle_detection_events(client), self.handle_snapshot_events(client), ] await client.subscribe(f"{self.args.mqtt_prefix}/#") await asyncio.gather(*tasks)
async def init_client(self, cbpi): async def log_messages(messages, template): async for message in messages: print(template.format(message.payload.decode())) async def cancel_tasks(tasks): for task in tasks: if task.done(): continue task.cancel() try: await task except asyncio.CancelledError: pass async with AsyncExitStack() as stack: tasks = set() stack.push_async_callback(cancel_tasks, tasks) self.client = Client("localhost", will=Will(topic="cbpi/diconnect", payload="CBPi Server Disconnected")) await stack.enter_async_context(self.client) topic_filters = ("cbpi/sensor/#", "cbpi/actor/#") for topic_filter in topic_filters: # Log all messages that matches the filter manager = self.client.filtered_messages(topic_filter) messages = await stack.enter_async_context(manager) task = asyncio.create_task(self.handle_message(messages)) tasks.add(task) messages = await stack.enter_async_context( self.client.unfiltered_messages()) task = asyncio.create_task(self.handle_unfilterd_message(messages)) tasks.add(task) await self.client.subscribe("cbpi/#") await asyncio.gather(*tasks)
async def init_client(self, cbpi): async def cancel_tasks(tasks): for task in tasks: if task.done(): continue task.cancel() try: await task except asyncio.CancelledError: pass while True: try: async with AsyncExitStack() as stack: self.tasks = set() stack.push_async_callback(cancel_tasks, self.tasks) self.client = Client(self.host, port=self.port, username=self.username, password=self.password, will=Will(topic="cbpi/diconnect", payload="CBPi Server Disconnected")) await stack.enter_async_context(self.client) for topic_filter in self.topic_filters: topic = topic_filter[0] method = topic_filter[1] manager = self.client.filtered_messages(topic) messages = await stack.enter_async_context(manager) task = asyncio.create_task(method(messages)) self.tasks.add(task) for topic_filter in self.topic_filters: topic = topic_filter[0] await self.client.subscribe(topic) self.logger.info("MQTT Connected to {}:{}".format(self.host, self.port)) await asyncio.gather(*self.tasks) except MqttError as e: self.logger.error("MQTT Exception: {}".format(e)) except Exception as e: self.logger.error("MQTT General Exception: {}".format(e)) await asyncio.sleep(5)
async def mqtt_agent(): while 1: try: async with Client("192.168.1.200") as client: async with client.unfiltered_messages() as messages: await client.subscribe("home/#") async for message in messages: print(message.payload.decode()) except KeyboardInterrupt: import sys sys.exit(1) await asyncio.sleep(5)
def __init__( self, broker: str, *, port: int = DEFAULT_MQTT_PORT, username: Optional[str] = None, password: Optional[str] = None, ) -> None: """Initialize.""" self._client = Client(broker, port=port, username=username, password=password)
async def mqtt_broker(self): async with Client(MQTT_HOST, port=MQTT_PORT) as client: # use shared subscription for HA/balancing await client.subscribe("$share/telemetry/#") async with client.unfiltered_messages() as messages: async for message in messages: payload = json.loads(message.payload.decode('utf-8')) device = await self.get_device(message.topic) if device is not None: await self.store_telemetry(device, payload) else: self.stdout.write( self.style.ERROR('DEBUG: message discarded'))
async def mqtt_stack(self): async with AsyncExitStack() as stack: self._mqtt_tasks = set() stack.push_async_callback(self.cancel_tasks, self._mqtt_tasks) username = self.cfg["user"] or None password = self.cfg["pass"] or None self._mqtt_client = Client(self.cfg["host"],port=self.cfg["port"],username=username,password=password) await stack.enter_async_context(self._mqtt_client) topics = [] for o in self.obj_list: topic = o["topic"] topics.append(topic) manager = self._mqtt_client.filtered_messages(topic) messages = await stack.enter_async_context(manager) task = asyncio.create_task(self.mqtt_handle(messages, o)) self._mqtt_tasks.add(task) for topic in topics: await self._mqtt_client.subscribe(topic) await asyncio.gather(*self._mqtt_tasks)
async def bed_loop(ble): async with AsyncExitStack() as stack: # Keep track of the asyncio tasks that we create, so that # we can cancel them on exit tasks = set() stack.push_async_callback(cancel_tasks, tasks) # Connect to the MQTT broker client = Client( MQTT_SERVER, port=MQTT_SERVER_PORT, username=MQTT_USERNAME, password=MQTT_PASSWORD, ) await stack.enter_async_context(client) # Set up the topic filter manager = client.filtered_messages(MQTT_TOPIC) messages = await stack.enter_async_context(manager) task = asyncio.create_task(bed_command(ble, messages)) tasks.add(task) # Subscribe to topic(s) await client.subscribe(MQTT_TOPIC) # let everyone know we are online if DEBUG: print("Going online") await client.publish(MQTT_CHECKIN_TOPIC, MQTT_ONLINE_PAYLOAD, qos=1) # let everyone know we are still alive task = asyncio.create_task( check_in(client, MQTT_CHECKIN_TOPIC, MQTT_CHECKIN_PAYLOAD) ) tasks.add(task) # Wait for everything to complete (or fail due to, e.g., network # errors) await asyncio.gather(*tasks)
async def mqtt_connection(ca, url, username, password): logger.info('Connecting to MQTT...') reconnect_interval = 3 #seconds mqtt = None h = None while True: try: if username and password: mqtt = Client(url, username=username, password=password) else: mqtt = Client(url) h = ComfoAirHandler(mqtt) # FIXME ugly hack!!! # set the LWT message in case of disconnect mqtt._client.will_set(TOPIC_AVAILABILITY, payload="Offline", qos=0, retain=True) await mqtt.connect() await send_ha_config(mqtt) await mqtt.publish(TOPIC_AVAILABILITY, "Online", qos=0, retain=True) add_ca_listeners(ca, h) logger.info('Connected to MQTT') await handle_mqtt_message( mqtt, ca, { TOPIC_SET_FAN_SPEED: h.handle_set_speed, TOPIC_SET_FAN_STATE: h.handle_set_fan_state }) except MqttError as error: logger.error( f'Error "{error}". Reconnecting in {reconnect_interval} seconds.' ) remove_ca_listeners(ca, h) await asyncio.sleep(reconnect_interval)
async def connect_to_mqtt_server(config): async with AsyncExitStack() as stack: # Keep track of the asyncio tasks that we create, so that # we can cancel them on exit tasks = set() stack.push_async_callback(cancel_tasks, tasks) if config.has_section('MQTT'): # Connect to the MQTT broker # client = Client("10.0.1.20", username="******", password="******") client = Client(config.get('MQTT', 'broker_address'), username=config.get('MQTT', 'usr'), password=config.get('MQTT', 'pswd')) await stack.enter_async_context(client) # Create PWM3901 driver # travel = PMW3901() # Create mpu6050 driver travel = mpu6050(address=0x68) # Create Travel State state = TravelState(config) # Messages that doesn't match a filter will get logged here messages = await stack.enter_async_context( client.unfiltered_messages()) task = asyncio.create_task( log_messages(messages, "[unfiltered] {}")) tasks.add(task) # Start periodic publish of travel state task = asyncio.create_task( travel_loop(client, travel, state, config)) tasks.add(task) # Wait for everything to complete (or fail due to, e.g., network errors) await asyncio.gather(*tasks)
async def run(self, broker: str, listen: str, connect: str) -> None: p = urlparse(broker, scheme="mqtt") if p.scheme not in ("mqtt", "mqtts") or not p.hostname: raise ValueError tls_context = None if p.scheme == "mqtts": tls_context = ssl.create_default_context() will = None async with Client( p.hostname, port=p.port or p.scheme == "mqtt" and 1883 or 8883, username=p.username, password=p.password, logger=logger, tls_context=tls_context, will=will, ) as mqtt: xmlrpc_local = self._xmlrpc_listen_url(listen) xmlrpc_remote = self._xmlrpc_connect_url(connect) homematic = HMConnection( interface_id=HM_INTERFACE_ID, local=xmlrpc_local.hostname, localport=xmlrpc_local.port or 0, remotes={ HM_REMOTE: { "ip": xmlrpc_remote.hostname, "port": xmlrpc_remote.port, "path": xmlrpc_remote.path or "", "username": xmlrpc_remote.username or "Admin", "password": xmlrpc_remote.password or "", } }, eventcallback=partial(self._event_callback, mqtt), systemcallback=partial(self._system_callback, mqtt), ) try: homematic.start() except AttributeError: sys.exit(1) async with mqtt.unfiltered_messages() as messages: async for message in messages: await self._process_packet(message, homematic) homematic.stop()
async def main(): device = await get_device(CAST_NAME) q = asyncio.Queue() listenerCast = StatusListener(device.name, q) device.register_status_listener(listenerCast) device.media_controller.register_status_listener(listenerCast) ev = Events(q) async with Client("iot.labs") as client: logger.info("Connected to MQTT!") async for is_running, title in ev: await client.publish(f'chromecast/{listenerCast.name}/playing', is_running) await client.publish(f'chromecast/{listenerCast.name}/title', title)
async def mqtt_task(): attempts = 1 while MQTT_LIVE: try: async with Client(MQTT_URL) as client: logging.info(f'connected to client at {MQTT_URL}') attempts = 1 await client.subscribe(TOPIC_FILTER) async with client.filtered_messages(TOPIC_FILTER) as messages: async for message in messages: await dispatch_message(message) except MqttError as err: logging.error(err) timeout = max(5 * attempts, 30) logging.info(f'Will attempt reconnect #{attempt} to {MQTT_URL} in {timeout}') await asyncio.sleep(timeout) attempts += 1
async def test(): while True: try: logger.info("Connecting to MQTT") async with Client("localhost") as client: logger.info("Connection to MQTT open") async with client.unfiltered_messages() as messages: await client.subscribe("#") async for message in messages: logger.info("Message %s %s", message.topic, message.payload.decode()) # await asyncio.sleep(2) except MqttError as e: logger.error("Connection to MQTT closed: " + str(e)) except Exception: logger.exception("Connection to MQTT closed") await asyncio.sleep(3)
async def run(self) -> None: event = partial(self._event, None) self._proto.add_listener(event, ["SmlGetListResponse"]) await self._proto.connect() p = urlparse(self._cfg["broker"], scheme="mqtt") if p.scheme not in ("mqtt", "mqtts") or not p.hostname: raise ValueError tls_context = None if p.scheme == "mqtts": tls_context = ssl.create_default_context() will = Will( await self._base_topic("availability"), payload=b"offline", qos=2, retain=True, ) self._proto.remove_listener(event, ["SmlGetListResponse"]) async with Client( p.hostname, port=p.port or p.scheme == "mqtt" and 1883 or 8883, username=p.username, password=p.password, logger=logger, tls_context=tls_context, will=will, ) as mqtt: watchdog_callback = partial(self._publish_availability, mqtt) self._wdt.start(watchdog_callback) event = partial(self._event, mqtt) self._proto.add_listener(event, ["SmlGetListResponse"]) if self._cfg["hass"]: await self._publish_hass_config(mqtt) await self._run_mainloop(mqtt) self._proto.remove_listener(event, ["SmlGetListResponse"]) self._wdt.stop() await self._publish_availability(mqtt, False)
async def start( app_config: "config.AppConfig", blind_groups:BlindGroup ): """Start.""" async with Client(app_config.mqtt_address) as client: await client.subscribe("building/#") while True: try: for blind_group in blind_groups: blind_group.start_watching(client) await asyncio.gather(*(blind_group.watch_task for blind_group in blind_groups)) except MqttError as error: _LOGGER.error(error) await asyncio.sleep(3)