loadcell/btproxy/main.py

64 lines
1.9 KiB
Python
Raw Normal View History

2024-05-10 00:27:32 +00:00
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)
2024-05-08 20:31:38 +00:00
import time
2024-05-10 00:27:32 +00:00
import asyncio
2024-05-08 20:31:38 +00:00
import bleak
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
2024-05-10 00:27:32 +00:00
from aiomqtt import Client
2024-05-08 20:31:38 +00:00
ble = BLERadio()
def scan():
2024-05-10 00:27:32 +00:00
logging.info('Disconnected, scanning')
2024-05-08 20:31:38 +00:00
for advertisement in ble.start_scan(ProvideServicesAdvertisement, timeout=1):
if not advertisement.complete_name.startswith('Feather'):
continue
ble.connect(advertisement)
2024-05-10 00:27:32 +00:00
logging.info('Connected to %s', advertisement.complete_name)
2024-05-08 20:31:38 +00:00
break
ble.stop_scan()
2024-05-10 00:27:32 +00:00
async def read(connection, mqtt_client):
2024-05-08 20:31:38 +00:00
uart = connection[UARTService]
if uart.in_waiting:
res = uart.read(uart.in_waiting)
2024-05-10 00:27:32 +00:00
data = res.decode().strip().split()
2024-05-11 19:32:51 +00:00
nums = ','.join(data)
logging.info('Received data: %s', nums)
2024-05-10 00:27:32 +00:00
2024-05-11 19:32:51 +00:00
await mqtt_client.publish('test', payload=nums)
2024-05-08 20:31:38 +00:00
2024-05-10 00:27:32 +00:00
async def main():
2024-05-08 20:31:38 +00:00
while True:
2024-05-10 00:27:32 +00:00
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)
2024-05-08 20:31:38 +00:00
2024-05-10 00:27:32 +00:00
await asyncio.sleep(0.1)
scan()
2024-05-08 20:31:38 +00:00
if __name__ == '__main__':
2024-05-10 00:27:32 +00:00
logging.info('')
logging.info('==========================')
logging.info('Booting up...')
loop = asyncio.get_event_loop()
loop.run_until_complete(main())