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()
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
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)
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)
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)) finally: mc.close() # Prevent LmacRxBlk:1 errors