import os, logging DEBUG = os.environ.get('DEBUG') logging.basicConfig( format='[%(asctime)s] %(levelname)s %(module)s/%(funcName)s - %(message)s', level=logging.DEBUG if DEBUG else logging.INFO) import time import asyncio import bleak from adafruit_ble import BLERadio from adafruit_ble.advertising.standard import ProvideServicesAdvertisement from adafruit_ble.services.nordic import UARTService from aiomqtt import Client ble = BLERadio() def scan(): logging.info('Disconnected, scanning') for advertisement in ble.start_scan(ProvideServicesAdvertisement, timeout=1): if not advertisement.complete_name.startswith('Feather'): continue ble.connect(advertisement) logging.info('Connected to %s', advertisement.complete_name) break ble.stop_scan() async def read(connection, mqtt_client): uart = connection[UARTService] if uart.in_waiting: res = uart.read(uart.in_waiting) data = res.decode().strip().split() nums = ','.join(data) logging.info('Received data: %s', nums) await mqtt_client.publish('test', payload=nums) async def main(): while True: async with Client('dev.tannercollin.com') as mqtt_client: while ble.connected: for connection in ble.connections: try: await read(connection, mqtt_client) except bleak.exc.BleakError: logging.info('Disconnected, waiting 3 seconds and trying to reconnect...') connection.disconnect() await asyncio.sleep(3) await asyncio.sleep(0.1) scan() if __name__ == '__main__': logging.info('') logging.info('==========================') logging.info('Booting up...') loop = asyncio.get_event_loop() loop.run_until_complete(main())