Add async mqtt connection

This commit is contained in:
Tanner Collin 2024-05-09 18:27:32 -06:00
parent a7189d3714
commit cffdf32735
2 changed files with 37 additions and 19 deletions

View File

@ -1,43 +1,62 @@
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():
print("disconnected, scanning")
logging.info('Disconnected, scanning')
for advertisement in ble.start_scan(ProvideServicesAdvertisement, timeout=1):
if not advertisement.complete_name.startswith('Feather'):
continue
ble.connect(advertisement)
print("connected to", advertisement.complete_name)
logging.info('Connected to %s', advertisement.complete_name)
break
ble.stop_scan()
def read(connection):
async def read(connection, mqtt_client):
uart = connection[UARTService]
if uart.in_waiting:
res = uart.read(uart.in_waiting)
print(res)
data = res.decode().strip().split()
logging.info('Received data: %s', data)
def loop():
await mqtt_client.publish('test', payload=str(data))
async def main():
while True:
while ble.connected:
for connection in ble.connections:
try:
read(connection)
except bleak.exc.BleakError:
print('Disconnected, waiting 3 seconds and trying to reconnect...')
connection.disconnect()
time.sleep(3)
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)
time.sleep(0.1)
await asyncio.sleep(0.1)
scan()
scan()
if __name__ == '__main__':
loop()
logging.info('')
logging.info('==========================')
logging.info('Booting up...')
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

View File

@ -3,8 +3,7 @@
#include <InternalFileSystem.h>
#include "HX711.h"
//#define calibration_factor -6980.0 // black wired load cell
#define calibration_factor -5760.0 // orange wired load cell
#define calibration_factor -6980.0 // black wired load cell
#define DOUT 30
#define CLK 27
@ -91,7 +90,7 @@ void loop()
int reading = (int) scale.get_units();
String message = String(reading) + "\n";
message.toCharArray(buf, message.length()+1);
bleuart.write(buf, message.length()+1);
bleuart.write(buf, message.length());
delay(50);
}