Updated disconnect_callback.py to show proper event loop shutdown handling
If there is a KeyboardInterupt during this program, the device will not disconnect unless we ensure all pending tasks are allowed to finish.
@@ -9,6 +9,7 @@ Updated on 2019-09-07 by hbldh <henrik.blidh@gmail.com>
"""
import asyncio
+import sys
from bleak import BleakClient, discover
@@ -31,10 +32,23 @@ async def show_disconnect_handling():
print("Sleeping until device disconnects...")
await disconnected_event.wait()
print("Connected: {0}".format(await client.is_connected()))
- await asyncio.sleep(
- 0.5
- ) # Sleep a bit longer to allow _cleanup to remove all BlueZ notifications nicely...
-loop = asyncio.get_event_loop()
+if sys.version_info >= (3, 7):
+ asyncio.run(show_disconnect_handling())
+else:
+ loop = asyncio.new_event_loop()
+ try:
+ asyncio.set_event_loop(loop)
loop.run_until_complete(show_disconnect_handling())
+ finally:
+ try:
+ tasks = asyncio.all_tasks(loop)
+ if tasks:
+ for t in tasks:
+ t.cancel()
+ loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
+ loop.run_until_complete(loop.shutdown_asyncgens())
+ finally:
+ asyncio.set_event_loop(None)
+ loop.close()
