@@ -19,6 +19,9 @@ async def main():
1919 dev , _adv_data = select_closest_device (dev_advdata_tuples )
2020 client = bleak .BleakClient (dev , timeout = 15 )
2121
22+ # Python context manager (async with) is used for convenient connection handling
23+ # Device stays connected during `async with` block execution and auto-disconnected on block finish
24+ # Otherwise, dice.connect/dice.disconnect can be used instead
2225 async with godice .create (client , godice .DiceShell .D6 ) as dice :
2326 print (f"Connected to { dev .name } " )
2427
@@ -33,16 +36,25 @@ async def main():
3336 print (f"Battery: { battery_lvl } " )
3437
3538 print ("Listening to position updates. Flip your dice" )
36- await dice .subscribe_number_notification (print_notification )
39+ await dice .subscribe_number_notification (notification_callback )
3740 await asyncio .sleep (30 )
3841 await dice .set_led (off_rgb , off_rgb )
3942
4043
41- async def print_notification (number , stability_descr ):
44+ async def notification_callback (number , stability_descr ):
45+ """
46+ GoDice number notification callback.
47+ Called each time GoDice is flipped, receiving flip event data:
48+ :param number: a rolled number
49+ :param stability_descr: an additional value clarifying device movement state, ie stable, rolling...
50+ """
4251 print (f"Number: { number } , stability descriptor: { stability_descr } " )
4352
4453
4554def filter_godice_devices (dev_advdata_tuples ):
55+ """
56+ Receives all discovered devices and returns only GoDice devices
57+ """
4658 return [
4759 (dev , adv_data )
4860 for dev , adv_data in dev_advdata_tuples
@@ -51,6 +63,9 @@ def filter_godice_devices(dev_advdata_tuples):
5163
5264
5365def select_closest_device (dev_advdata_tuples ):
66+ """
67+ Finds the closest device based on RSSI are returns it
68+ """
5469 def _rssi_as_key (dev_advdata ):
5570 _ , adv_data = dev_advdata
5671 return adv_data .rssi
@@ -59,9 +74,14 @@ def _rssi_as_key(dev_advdata):
5974
6075
6176def print_device_info (devices ):
77+ """
78+ Prints short summary of discovered devices
79+ """
6280 for dev , adv_data in devices :
6381 print (f"Name: { dev .name } , address: { dev .address } , rssi: { adv_data .rssi } " )
6482
6583
84+ # identify if the script is called directly and run if so
85+ # asyncio.run starts execution in Python async environment
6686if __name__ == "__main__" :
6787 asyncio .run (main ())
0 commit comments