diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bee8a64 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__ diff --git a/droid.py b/droid.py index dc2d3fb..246e88e 100644 --- a/droid.py +++ b/droid.py @@ -1,7 +1,7 @@ import asyncio from time import sleep -from bleak import BleakScanner, BleakClient -import pickle +from bleak import BleakScanner, BleakClient, BleakError + class Droid(): def __init__(self, profile): print("Initializing") @@ -114,13 +114,38 @@ def findDroid(candidate, data): else: return False +async def discoverDroid(retry=False): + myDroid = None + + while retry and myDroid is None: + try: + myDroid = await BleakScanner.find_device_by_filter(findDroid) + if myDroid is None: + if not retry: + print("Droid discovery timed out.") + return + else: + print("Droid discovery timed out. Retrying...") + continue + except BleakError as err: + print("Droid discovery failed. Retrying...") + continue + + + print (f"Astromech successfully discovered: [ {myDroid} ]") + + d = Droid(myDroid) + return d + + + async def main(): - myDroid = await BleakScanner.find_device_by_filter(findDroid) - print (myDroid) - arms = Droid(myDroid) - await arms.connect() - sleep (3) + + d = await discoverDroid(retry=True) + try: + await d.connect() + sleep (3) # await arms.run_routine("05") # sleep (5) # await arms.set_soundbank("05") @@ -131,16 +156,22 @@ async def main(): # sleep(5) # await arms.play_sound("00", "00") # sleep(8) - await arms.led_disable_sound("01") - await arms.play_sound("00", "00") + await d.led_disable_sound("01") + await d.play_sound("00", "00") sleep(10) - await arms.led_on("1f") + await d.led_on("1f") sleep(10) - await arms.led_off("1f") - await arms.play_sound("00", "00") + await d.led_off("1f") + await d.play_sound("00", "00") sleep(10) + except OSError as err: + print(f"Discovery failed due to operating system: {err}") + except BleakError as err: + print(f"Discovery failed due to Bleak: {err}") finally: - await arms.disconnect() -asyncio.run(main()) \ No newline at end of file + await d.disconnect() + +if __name__ == "__main__": + asyncio.run(main())