From 84af52d8efd65865fb3da97794bc909cdf6a1abe Mon Sep 17 00:00:00 2001 From: Josuah Demangeon Date: Thu, 12 Oct 2023 10:29:56 -0400 Subject: [PATCH] tools/upload_files.py: improve usability and logging --- tools/upload_file.py | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/tools/upload_file.py b/tools/upload_file.py index f41f8565..55bb1082 100644 --- a/tools/upload_file.py +++ b/tools/upload_file.py @@ -5,6 +5,7 @@ import asyncio import sys +import os from bleak import BleakClient, BleakScanner from bleak.backends.characteristic import BleakGATTCharacteristic @@ -29,6 +30,7 @@ def __init__(self): self.DATA_RX_CHAR_UUID: "Monocle Data TX", }) + @classmethod async def run(cls, *args): self = cls() @@ -37,7 +39,6 @@ async def run(cls, *args): if device is None: print("no matching device found\n") exit(1) - print("Connected to the Monocle") async with BleakClient(device, disconnected_callback=self.handle_disconnect) as c: self.client = c @@ -47,13 +48,18 @@ async def run(cls, *args): await self.script(*args) await self.client.write_gatt_char(self.uart_rx_char, b"\x02") + def log(self, msg): + if "DEBUG" in os.environ: + print(msg, flush=True) + def match_uart_uuid(self, device:BLEDevice, adv:AdvertisementData): - print(f"uuids={adv.service_uuids}") + self.log(f"uuids={adv.service_uuids}") return self.UART_SERVICE_UUID.lower() in adv.service_uuids def handle_disconnect(self, _:BleakClient): - print("\nDevice was disconnected.") - exit(0) + self.log("Device was disconnected.") + for task in asyncio.all_tasks(): + task.cancel() def handle_uart_rx(self, _:BleakGATTCharacteristic, data:bytearray): # Here, handle data sent by the Monocle with `print()` @@ -108,7 +114,7 @@ async def init_data_service(self): data_service = self.client.services.get_service(self.DATA_SERVICE_UUID) self.data_rx_char = data_service.get_characteristic(self.DATA_RX_CHAR_UUID) self.data_rx_last = None - + async def set_monocle_raw_mode(self): await self.client.write_gatt_char(self.uart_rx_char, b"\x01 \x04") while await self.getline_uart(delim=b"\r\n\x04") != b">OK": @@ -120,22 +126,18 @@ class UploadFileScript(MonocleScript): Example application: upload a file to the Monocle """ async def script(self, file): - - print(">>> opening a file to write to") + print(f"uploading {file} ", end="") await self.send_command(f"f = open('{file}', 'wb')") - - print(">>> writing the data to the file") with open(file, "rb") as f: while data := f.read(100): print(end=".", flush=True) await self.send_command(f"f.write({bytes(data).__repr__()})") - print("") - - print(">>> closing the file") await self.send_command("f.close()") - - print(">>> script done") - + print(" done") if __name__ == "__main__": - asyncio.run(UploadFileScript.run(sys.argv[1])) + for file in sys.argv[1:]: + try: + asyncio.run(UploadFileScript.run(file)) + except asyncio.exceptions.CancelledError: + pass