|
| 1 | +import asyncio |
| 2 | +import bleak |
| 3 | +import godice |
| 4 | + |
| 5 | + |
| 6 | +async def main(): |
| 7 | + print("Discovering GoDice devices...") |
| 8 | + discovery_res = await bleak.BleakScanner.discover(timeout=10, return_adv=True) |
| 9 | + dev_advdata_tuples = discovery_res.values() |
| 10 | + dev_advdata_tuples = filter_godice_devices(dev_advdata_tuples) |
| 11 | + |
| 12 | + print("Discovered devices...") |
| 13 | + print_device_info(dev_advdata_tuples) |
| 14 | + |
| 15 | + print("Connecting to a closest device...") |
| 16 | + dev, _adv_data = select_closest_device(dev_advdata_tuples) |
| 17 | + client = bleak.BleakClient(dev, timeout=15) |
| 18 | + |
| 19 | + async with godice.create(client, godice.DiceType.D6) as dice: |
| 20 | + print(f"Connected to {dev.name}") |
| 21 | + |
| 22 | + blue_rgb = (0, 0, 255) |
| 23 | + yellow_rgb = (255, 255, 0) |
| 24 | + off_rgb = (0, 0, 0) |
| 25 | + await dice.set_led(blue_rgb, yellow_rgb) |
| 26 | + |
| 27 | + color = await dice.get_color() |
| 28 | + battery_lvl = await dice.get_battery_level() |
| 29 | + print(f"Color: {color}") |
| 30 | + print(f"Battery: {battery_lvl}") |
| 31 | + |
| 32 | + print("Listening to position updates. Flip your dice") |
| 33 | + await dice.subscribe_number_notification(print_notification) |
| 34 | + await asyncio.sleep(30) |
| 35 | + await dice.set_led(off_rgb, off_rgb) |
| 36 | + |
| 37 | + |
| 38 | +async def print_notification(stability_descr, number): |
| 39 | + print(f"Stability descriptor: {stability_descr}, number: {number}") |
| 40 | + |
| 41 | + |
| 42 | +def filter_godice_devices(dev_advdata_tuples): |
| 43 | + return [ |
| 44 | + (dev, adv_data) |
| 45 | + for dev, adv_data in dev_advdata_tuples |
| 46 | + if dev.name.startswith("GoDice") |
| 47 | + ] |
| 48 | + |
| 49 | + |
| 50 | +def select_closest_device(dev_advdata_tuples): |
| 51 | + def _rssi_as_key(dev_advdata): |
| 52 | + _, adv_data = dev_advdata |
| 53 | + return adv_data.rssi |
| 54 | + |
| 55 | + return max(dev_advdata_tuples, key=_rssi_as_key) |
| 56 | + |
| 57 | + |
| 58 | +def print_device_info(devices): |
| 59 | + for dev, adv_data in devices: |
| 60 | + print(f"Name: {dev.name}, address: {dev.address}, rssi: {adv_data.rssi}") |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + asyncio.run(main()) |
0 commit comments