def __init__(self, event_mqtt_publish): log.info('MQTT:init') self.event_mqtt_publish = event_mqtt_publish self.feedname_pm25 = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'pm25'), 'utf-8') self.feedname_o3 = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'o3'), 'utf-8') self.feedname_no2 = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'no2'), 'utf-8') self.feedname_temp = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'tdegc'), 'utf-8') self.feedname_humidity = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'humidity'), 'utf-8') self.feedname_dba_avg = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'dba_avg'), 'utf-8') self.feedname_dba_max = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'dba_max'), 'utf-8') self.feedname_vbat_avg = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'vbat_avg'), 'utf-8') self.feedname_vbat_min = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'vbat_min'), 'utf-8') self.wifi_status = 'unknown' self.client = MQTTClient(server='io.adafruit.com', ssid=mqtt_config['ssid'], wifi_pw=mqtt_config['wifi_pw'], user=mqtt_config['user'], password=mqtt_config['password']) loop = asyncio.get_event_loop() try: loop.create_task(self.run_mqtt()) finally: self.client.close() # Prevent LmacRxBlk:1 errors
async def serviceMqtt(): config['wifi_coro'] = handleBrokerState config['connect_coro'] = handleConnection config['subs_cb'] = handleMessage publishPeriod = 60 client = MQTTClient(config) try: try: await client.connect() while True: await publishLiveness(client) printReport() await async_sleep_ms(publishPeriod) except OSError: print('Connection failed.') raise finally: # Prevent LmacRxBlk:1 hang? client.close() except KeyboardInterrupt: raise except Exception as e: print("Exception in serviceMqtt()") sys.print_exception(e) hardreset()
def __init__(self): MQTTClient.DEBUG = True # Optional: print diagnostic messages config['server'] = env.MQTT_BROKER config['ssid'] = env.WIFI_SSID config['wifi_pw'] = env.WIFI_PASSWORD config['connect_coro'] = self.conn_han self.client = MQTTClient(config) self.pending_messages = [] print('MqttService: Client created')
def __init__(self, config: dict): config["subs_cb"] = self.sub_cb config["connect_coro"] = self.subscribe_topics config["wifi_coro"] = self.on_wifi self.config = config self.client = MQTTClient(config) self.stopped = False self.ir_handler = IRHandler(config) self.last_lifesign = None self.iscp_handler = ISCPHandler()
def setupmqttas(self, wifiname, wifipassword, mqttbroker): config['ssid'] = wifiname config['wifi_pw'] = wifipassword config['server'] = mqttbroker config['subs_cb'] = self.callback config['connect_coro'] = self.conn_han MQTTClient.DEBUG = True self.client = MQTTClient(config)
class MqttService: def __init__(self): MQTTClient.DEBUG = True # Optional: print diagnostic messages config['server'] = env.MQTT_BROKER config['ssid'] = env.WIFI_SSID config['wifi_pw'] = env.WIFI_PASSWORD config['connect_coro'] = self.conn_han self.client = MQTTClient(config) self.pending_messages = [] print('MqttService: Client created') async def connect(self): print('MqttService: Going to connect to '+ config['ssid']) await self.client.connect() print('MqttService: Was connected as ' + self.client._sta_if.ifconfig()[0]) def callback(self, topic, msg, retained): print((topic, msg, retained)) async def conn_han(self, client): print('MqttService: MQTT connected') await self.client.publish(env.LOG_TOPIC, 'CML ESP32 connected with IP ' + self.client._sta_if.ifconfig()[0], qos = 1) #await client.subscribe('foo_topic', 1) while len(self.pending_messages) > 0: topic, msg = self.pending_messages[0] print('MqttService: processing pending messages, sending topic ' + topic) await self.client.publish(topic, msg, qos = 1) self.pending_messages.pop(0) async def publish(self, topic, msg): if self.client.isconnected(): print('MqttService: publish to ' + topic) # If WiFi is down the following will pause for the duration. await self.client.publish(topic, msg, qos = 1) else: print('MqttService: adding topic to pending messages ' + topic) self.pending_messages.append((topic, msg)) def close(self): self.client.close() # Prevent LmacRxBlk:1 errors
def __init__(self, server, topic, config, update_ms): self._config = config self._config['subs_cb'] = self.callback self._config['connect_coro'] = self.conn_han self._config['server'] = server self._topic = topic self._update_ms = update_ms self._adj_update_ms = update_ms MQTTClient.DEBUG = True # Optional: print diagnostic messages self._client = MQTTClient(self._config) loop = asyncio.get_event_loop() loop.create_task(self.run())
def __init__(self, settings): self.debug = getattr(settings, "DEBUG", False) self._state = STATE_INIT self._version = __version__ self._fw_name = "Microhomie" self._extensions = getattr(settings, "EXTENSIONS", []) self._bc_enabled = getattr(settings, "BROADCAST", False) self._wifi = getattr(settings, "WIFI_CREDENTIALS", False) self._wifi_rescan_delay = getattr(settings, "WIFI_RESCAN_DELAY", MAIN_DELAY) self.first_start = True self.stats_interval = getattr(settings, "DEVICE_STATS_INTERVAL", 60) self.device_name = getattr(settings, "DEVICE_NAME", "") self.callback_topics = {} # Registered homie nodes self.nodes = [] # Generate unique id if settings has no DEVICE_ID self.device_id = getattr(settings, "DEVICE_ID", get_unique_id()) # Base topic self.btopic = getattr(settings, "MQTT_BASE_TOPIC", "homie") # Device base topic self.dtopic = "{}/{}".format(self.btopic, self.device_id) # mqtt_as client self.mqtt = MQTTClient( client_id=self.device_id, server=settings.MQTT_BROKER, port=getattr(settings, "MQTT_PORT", 1883), user=getattr(settings, "MQTT_USERNAME", None), password=getattr(settings, "MQTT_PASSWORD", None), keepalive=getattr(settings, "MQTT_KEEPALIVE", 30), ping_interval=getattr(settings, "MQTT_PING_INTERVAL", 0), ssl=getattr(settings, "MQTT_SSL", False), ssl_params=getattr(settings, "MQTT_SSL_PARAMS", {}), response_time=getattr(settings, "MQTT_RESPONSE_TIME", 10), clean_init=getattr(settings, "MQTT_CLEAN_INIT", True), clean=getattr(settings, "MQTT_CLEAN", True), max_repubs=getattr(settings, "MQTT_MAX_REPUBS", 4), will=("{}/{}".format(self.dtopic, DEVICE_STATE), "lost", True, QOS), subs_cb=self.subs_cb, wifi_coro=None, connect_coro=self.connection_handler, ssid=getattr(settings, "WIFI_SSID", None), wifi_pw=getattr(settings, "WIFI_PASSWORD", None), )
def __init__(self, settings): self.debug = getattr(settings, "DEBUG", False) self._state = STATE_INIT self._extensions = getattr(settings, "EXTENSIONS", []) self._extensions.append("org.microhomie.mpy:0.1.0:[4.x]") self._first_start = True self.stats_interval = getattr(settings, "DEVICE_STATS_INTERVAL", 60) self.nodes = [] self.callback_topics = {} self.device_name = getattr(settings, "DEVICE_NAME", b"mydevice") # Generate unique id if settings has no DEVICE_ID try: device_id = settings.DEVICE_ID except AttributeError: device_id = utils.get_unique_id() # Base topic self.btopic = getattr(settings, "MQTT_BASE_TOPIC", "homie") # Device base topic self.dtopic = "{}/{}".format(self.btopic, device_id) self.mqtt = MQTTClient( client_id=device_id, server=settings.MQTT_BROKER, port=getattr(settings, "MQTT_PORT", 1883), user=getattr(settings, "MQTT_USERNAME", None), password=getattr(settings, "MQTT_PASSWORD", None), keepalive=getattr(settings, "MQTT_KEEPALIVE", 30), ping_interval=getattr(settings, "MQTT_PING_INTERVAL", 0), ssl=getattr(settings, "MQTT_SSL", False), ssl_params=getattr(settings, "MQTT_SSL_PARAMS", {}), response_time=getattr(settings, "MQTT_RESPONSE_TIME", 10), clean_init=getattr(settings, "MQTT_CLEAN_INIT", True), clean=getattr(settings, "MQTT_CLEAN", True), max_repubs=getattr(settings, "MQTT_MAX_REPUBS", 4), will=("{}/{}".format(self.dtopic, DEVICE_STATE), "lost", True, QOS), subs_cb=self.sub_cb, wifi_coro=None, connect_coro=self.connection_handler, ssid=getattr(settings, "WIFI_SSID", None), wifi_pw=getattr(settings, "WIFI_PASSWORD", None), )
def __init__(self, settings): self._state = STATE_INIT self._extensions = getattr(settings, "EXTENSIONS", []) self._first_start = True self.async_tasks = [] self.stats_interval = getattr(settings, "DEVICE_STATS_INTERVAL", 60) self.nodes = [] self.callback_topics = {} self.device_name = getattr(settings, "DEVICE_NAME", b"mydevice") device_id = getattr(settings, "DEVICE_ID", get_unique_id()) self.btopic = getattr(settings, "MQTT_BASE_TOPIC", b"homie") self.dtopic = SLASH.join((self.btopic, device_id)) self.mqtt = MQTTClient( client_id=device_id, server=settings.MQTT_BROKER, port=getattr(settings, "MQTT_PORT", 1883), user=getattr(settings, "MQTT_USERNAME", None), password=getattr(settings, "MQTT_PASSWORD", None), keepalive=getattr(settings, "MQTT_KEEPALIVE", 30), ping_interval=getattr(settings, "MQTT_PING_INTERVAL", 0), ssl=getattr(settings, "MQTT_SSL", False), ssl_params=getattr(settings, "MQTT_SSL_PARAMS", {}), response_time=getattr(settings, "MQTT_RESPONSE_TIME", 10), clean_init=getattr(settings, "MQTT_CLEAN_INIT", True), clean=getattr(settings, "MQTT_CLEAN", True), max_repubs=getattr(settings, "MQTT_MAX_REPUBS", 4), will=(SLASH.join((self.dtopic, DEVICE_STATE)), b"lost", True, QOS), subs_cb=self.sub_cb, wifi_coro=None, connect_coro=self.connection_handler, ssid=getattr(settings, "WIFI_SSID", None), wifi_pw=getattr(settings, "WIFI_PASSWORD", None), )
def __init__(self, settings): self._state = "init" self._stime = time() self.stats_interval = settings.DEVICE_STATS_INTERVAL self.nodes = [] self.callback_topics = {} self.device_name = settings.DEVICE_NAME self.btopic = settings.MQTT_BASE_TOPIC self.dtopic = SLASH.join( (settings.MQTT_BASE_TOPIC, settings.DEVICE_ID) ) # setup networking utils.setup_network(settings.WIFI_PASSWORD) utils.wifi_connect(settings.WIFI_SSID) self.mqtt = MQTTClient( client_id=settings.DEVICE_ID, server=settings.MQTT_BROKER, port=settings.MQTT_PORT, user=settings.MQTT_USERNAME, password=settings.MQTT_PASSWORD, keepalive=settings.MQTT_KEEPALIVE, ssl=settings.MQTT_SSL, ssl_params=settings.MQTT_SSL_PARAMS, subs_cb=self.sub_cb, connect_coro=self.connection_handler, will=(SLASH.join((self.dtopic, DEVICE_STATE)), b"lost", True, QOS), ) # Start coros loop = get_event_loop() loop.create_task(self.publish_stats())
# TODO How does machine.wdt cope with deepsleep? async def main(client): try: await run_task(client) except (asyncio.TimeoutError, OSError): # Mandatory timeout error trapping return False # Connect fail or timeout return True # Define configuration and set up client config["subs_cb"] = sub_cb config["will"] = (TOPIC, "Goodbye cruel world!", False, 0) config["clean"] = False # Ensure we can receive subscriptions config["clean_init"] = False # Exit from deepsleep is like a power cycle MQTTClient.DEBUG = True # Enable optional debug statements. client = MQTTClient(config) def test(has_usb=True, delay=60, retry=60): global debug debug = has_usb wt = asyncio.run(main(client)) # True == success # wt allows different wait time in case of failure. client.close() tim = delay if wt else retry if debug: # In testing with USB don't deepsleep sleep(tim) soft_reset( ) # Assumes main.py imports this module and calls this function deepsleep(tim * 1000)
try: await client.connect() except OSError: print('Connection failed.') return n = 0 while True: await asyncio.sleep(5) print('publish', n) # If WiFi is down the following will pause for the duration. await client.publish('result', '{} {}'.format(n, client.REPUB_COUNT), qos = 1) n += 1 # Define configuration config['subs_cb'] = sub_cb config['wifi_coro'] = wifi_han config['connect_coro'] = conn_han config['clean'] = True config['server'] = SERVER # Set up client MQTTClient.DEBUG = True # Optional client = MQTTClient(config) loop = asyncio.get_event_loop() loop.create_task(heartbeat()) try: loop.run_until_complete(main(client)) finally: client.close() # Prevent LmacRxBlk:1 errors
#print("pub:", data) #await client.publish(TOPIC+"/sensors", json.dumps(data), qos = 1) #await asyncio.sleep(1) # Define configuration #config['subs_cb'] = sub_cb config['wifi_coro'] = wifi_cb config['connect_coro'] = conn_cb config['keepalive'] = 120 # power config #machine.freq(80000000, min_freq=10000000) #config['listen_interval']=5 # Set up client. Enable optional debug statements. #MQTTClient.DEBUG = True client = MQTTClient(config) #import uasyncio, logging #logging.basicConfig(level=logging.DEBUG) #uasyncio.set_debug(True) print("Starting loop...") try: loop.run_until_complete(main(client)) finally: # Prevent LmacRxBlk:1 errors. client.close() blue_led(True)
gui.set_value(sensor.max_value, "TEMP_MAX") loop = asyncio.get_event_loop() loop.create_task(pub_mqtt("TEMP/IN/CURRENT", sensor.current_value)) elif sensor.serial == external_temp_sensor.serial: gui.set_value(sensor.current_value, "TEMP_OUT") loop = asyncio.get_event_loop() loop.create_task(pub_mqtt("TEMP/OUT/CURRENT", sensor.current_value)) elif sensor.serial == internal_humidity_sensor.serial: gui.set_value(sensor.current_value, "HUMID_IN") gui.set_value(sensor.min_value, "HUMID_MIN") gui.set_value(sensor.max_value, "HUMID_MAX") loop = asyncio.get_event_loop() loop.create_task(pub_mqtt("HUMIDITY/IN/CURRENT", sensor.current_value)) mc = MQTTClient(config) gui = guicontroller.GUI(128, 64, I2C(-1, scl=Pin(25), sda=Pin(33))) s = sensorcontroller.SensorController(on_sensor_change) internal_temp_sensor = s.add_sensor(sensorcontroller.DallasTempSensor, Pin(14), serial=b'(yd\x84\x07\x00\x00\xb3') external_temp_sensor = s.add_sensor(sensorcontroller.DallasTempSensor, Pin(14), serial=b'(\x84tV\xb5\x01<\xdb') internal_humidity_sensor = s.add_sensor(sensorcontroller.DHT22Sensor, Pin(27), serial=b'INTERNAL_HUMIDITY') loop = asyncio.get_event_loop() try: loop.run_until_complete(connect_mqtt(mc))
class Handler: def __init__(self, config: dict): config["subs_cb"] = self.sub_cb config["connect_coro"] = self.subscribe_topics config["wifi_coro"] = self.on_wifi self.config = config self.client = MQTTClient(config) self.stopped = False self.ir_handler = IRHandler(config) self.last_lifesign = None self.iscp_handler = ISCPHandler() def stop(self): self.ir_handler.stop() self.stopped = True async def start(self): await self.client.connect() loop.create_task(self.ir_handler.start()) while not self.stopped: if self.ir_handler.is_listening: sleep_ms = 1 else: sleep_ms = 1000 await uasyncio.sleep_ms(sleep_ms) await self.send_lifesign_if_necessary() async def send_command(self, data: dict) -> None: try: await self._send_command(data) except Exception as e: print(e) await self.send_error(str(e), data) async def _send_command(self, data: dict) -> None: data_type = data.get("type", "").upper() if data_type == "NEC": await self.send_nec_command(data) if data_type == "RC6": await self.send_rc6_command(data) elif data_type == "ISCP": await self.send_iscp_command(data) elif data_type == "SCENE": await self.play_scene(data) elif data_type == "WAIT": await uasyncio.sleep_ms(data.get("ms", data.get("s", 1) * 1000)) elif data_type == "REPEAT": await self.play_repeat(data) else: await self.send_error("Unknown command type", data) async def iscp_discover(self) -> None: try: print("Searching for ISCP devices on network") result = await self.iscp_handler.discover() print("ISCP devices found: {}".format(result)) await self.client.publish(self.topic_name("iscp/discover/result"), json.dumps(result), False, 0) except Exception as error: print("Failed Discovering ISCP devices with error {}".format(error)) await self.send_error("Failed discovering iscp devices with error {}".format(error)) async def send_iscp_command(self, data: dict) -> None: if "identifier" not in data or "command" not in data or "argument" not in data: await self.send_error("No identifier, command or argument provided in iscp payload", data) identifier: str = data["identifier"] command: str = data["command"] argument: str = data["argument"] retries = 0 check = False result = None while not check: try: result = await self.iscp_handler.send(identifier, command, argument) check = True except Exception as error: await self.send_error( "Could not send ISCP command ({}, {}={}). Error: {}. Retry: {}".format( identifier, command, argument, error, retries ), data, ) retries += 1 if retries > 3: raise error if result is None: await self.send_error("Could not send ISCP command ({}, {}={})".format(identifier, command, argument), data) data["result"] = result data["type"] = "ISCP" await self._record_send_command(data) async def send_nec_command(self, data: dict) -> None: if "command" not in data and "device_id" not in data: await self.send_error("No command or device_id added in nec command", data) return await self.ir_handler.send_nec(data["device_id"], data["command"]) await self._record_send_command(data) async def send_rc6_command(self, data: dict) -> None: if "control" not in data or "information" not in data: await self.send_error("No control or information added in rc9 command", data) await self.ir_handler.send_rc6( mode=data.get("mode", 0), control=data["control"], information=data["information"] ) await self._record_send_command(data) async def _record_send_command(self, data: dict) -> None: await self.client.publish(self.topic_name("ir/last-sent-command"), json.dumps(data), False, 0) async def play_scene(self, data: dict) -> None: if "scene" not in data or not isinstance(data["scene"], list): await self.send_error("No scene in payload") return for item in data["scene"]: await self._send_command(item) async def play_repeat(self, data: dict) -> None: repeats = data.get("count", 1) if "item" not in data: await self.send_error("No item in repeat configuration {}".format(data)) for _ in range(repeats): await self._send_command(data["item"]) async def send_error(self, error_message: str, context: dict = None) -> None: context = context or {} await self.client.publish( self.topic_name("error"), json.dumps({"message": error_message, "context": context}), False, 0 ) gc.collect() def sub_cb(self, topic: bytes, message: bytes, retained: bool) -> None: try: topic = topic.decode() message = message.decode() print("Topic = {} Payload = {} Retained = {}".format(topic, message, retained)) if topic.endswith("ir/command"): loop.create_task(self.send_command(json.loads(message))) elif topic.endswith("ir/listening-mode"): loop.create_task(self.start_listening_mode(message)) elif topic.endswith("iscp/command"): loop.create_task(self.send_iscp_command(json.loads(message))) elif topic.endswith("iscp/discover"): loop.create_task(self.iscp_discover()) else: print("Unknown MQTT topic for subscription {}".format(topic)) except Exception as e: print(e) raise async def on_wifi(self, state: bool): await wifi_han(state) self.iscp_handler.reset() async def subscribe_topics(self, client: MQTTClient): await client.subscribe(self.topic_name("ir/listening-mode"), 1) await client.subscribe(self.topic_name("ir/command"), 1) await client.subscribe(self.topic_name("iscp/discover"), 1) await client.subscribe(self.topic_name("iscp/command"), 1) await self.send_lifesign() print("Subscribed to topics and published livesign to {}".format(self.topic_name("livesign"))) async def send_lifesign_if_necessary(self) -> None: if self.last_lifesign is None or self.last_lifesign + 5 * 1000 < time.ticks_ms(): await self.send_lifesign() async def send_lifesign(self) -> None: await self.client.publish( self.topic_name("livesign"), json.dumps({"ticks": time.ticks_ms(), "datetime": current_isotime()}), True, 0 ) self.last_lifesign = time.ticks_ms() def topic_name(self, name: str) -> str: return topic_name(self.config, name) async def start_listening_mode(self, mode: str) -> None: self.record_mode(mode) def record_mode(self, mode: str) -> None: self.ir_handler.record_mode(mode, self._on_message_callback) def _on_message_callback(self, message): print("Captured IR Command", message) message_dict = message.as_dict() message_dict["ticks"] = time.ticks_ms() loop.create_task( self.client.publish(self.topic_name("ir/last-captured-command"), json.dumps(message_dict), False, 1) ) def run_forever(self) -> None: loop.run_until_complete(self.start())
await asyncio.sleep_ms(10) os.dupterm(mqrepl, 0) await asyncio.sleep_ms(10) # TODO: wait for time sync # launch tasks #loop.create_task(query_sensors(client)) #loop.create_task(poll_uarts(client)) # play watchdog while True: print("Still running...") await asyncio.sleep(10) # Start MQTT (and Wifi) config['subs_cb'] = sub_cb config['wifi_coro'] = wifi_cb config['connect_coro'] = conn_cb config['keepalive'] = 120 #MQTTClient.DEBUG = True mqclient = MQTTClient(config) #import uasyncio, logging #logging.basicConfig(level=logging.DEBUG) #uasyncio.set_debug(True) print("Starting loop...") try: loop.run_until_complete(main()) finally: # Prevent LmacRxBlk:1 errors. mqclient.close() board.blue_led(True)
class MQTTPublish(): def __init__(self, event_mqtt_publish): log.info('MQTT:init') self.event_mqtt_publish = event_mqtt_publish self.feedname_pm25 = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'pm25'), 'utf-8') self.feedname_o3 = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'o3'), 'utf-8') self.feedname_no2 = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'no2'), 'utf-8') self.feedname_temp = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'tdegc'), 'utf-8') self.feedname_humidity = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'humidity'), 'utf-8') self.feedname_dba_avg = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'dba_avg'), 'utf-8') self.feedname_dba_max = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'dba_max'), 'utf-8') self.feedname_vbat_avg = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'vbat_avg'), 'utf-8') self.feedname_vbat_min = bytes('{:s}/feeds/{:s}'.format(b'MikeTeachman', b'vbat_min'), 'utf-8') self.wifi_status = 'unknown' self.client = MQTTClient(server='io.adafruit.com', ssid=mqtt_config['ssid'], wifi_pw=mqtt_config['wifi_pw'], user=mqtt_config['user'], password=mqtt_config['password']) loop = asyncio.get_event_loop() try: loop.create_task(self.run_mqtt()) finally: self.client.close() # Prevent LmacRxBlk:1 errors async def run_mqtt(self): await self.client.connect() log.info('MQTT:turn WiFi off') self.client.pause() while True: await self.event_mqtt_publish log.info('MQTT:turn WiFi on') self.wifi_status = 'on' self.client.resume() await self.client.publish(self.feedname_pm25, '{}'.format(repo.get('pm25').current), qos = 0) await self.client.publish(self.feedname_o3, '{}'.format(repo.get('o3').current), qos = 0) await self.client.publish(self.feedname_no2, '{}'.format(repo.get('no2').current), qos = 0) await self.client.publish(self.feedname_temp, '{:.2f}'.format(repo.get('tdegc').current), qos = 0) await self.client.publish(self.feedname_humidity, '{:.1f}'.format(repo.get('rh').current), qos = 0) await self.client.publish(self.feedname_dba_avg, '{:.1f}'.format(repo.get('dba').avg), qos = 0) await self.client.publish(self.feedname_dba_max, '{:.1f}'.format(repo.get('dba').max), qos = 0) await self.client.publish(self.feedname_vbat_avg, '{:.2f}'.format(repo.get('vbat').avg), qos = 0) await self.client.publish(self.feedname_vbat_min, '{:.2f}'.format(repo.get('vbat').min), qos = 0) # pausing the MQTT client will turn off the WiFi radio # which reduces the processor power usage log.info('MQTT:turn WiFi off') self.wifi_status = 'off' self.client.pause() self.event_mqtt_publish.clear() # TODO need a better place to perform measurement stat clearing (another event sync object?) repo.clear_stats('pm25') repo.clear_stats('o3') repo.clear_stats('o3_vgas') repo.clear_stats('o3_vref') repo.clear_stats('no2') repo.clear_stats('no2_vgas') repo.clear_stats('no2_vref') repo.clear_stats('tdegc') repo.clear_stats('rh') repo.clear_stats('dba') repo.clear_stats('vusb') repo.clear_stats('vbat') await asyncio.sleep(0)