Skip to content

Commit

Permalink
bluez: Allow accessing Bleak from multiple individual event loops
Browse files Browse the repository at this point in the history
Previous event loop needs to be closed for this to work, as the rest
of the DBus access code doesn't support concurrent access from more than one
MessageBus instance.

However this allows creating per-test Bleak classes with pytest-asyncio that
don't overlap each other, and possibly other use cases as well.
  • Loading branch information
projectgus committed Sep 26, 2022
1 parent 18f7e9a commit 1c581c0
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions bleak/backends/bluezdbus/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
Optional,
Set,
cast,
Union,
)

from dbus_fast import BusType, Message, MessageType, Variant
Expand Down Expand Up @@ -846,12 +847,30 @@ def _run_advertisement_callbacks(
async def get_global_bluez_manager() -> BlueZManager:
"""
Gets the initialized global BlueZ manager instance.
If a BlueZ manager was previously initialized and associated with an event loop which is now closed,
then a new instance will be created to replace it.
"""

if not hasattr(get_global_bluez_manager, "instance"):
setattr(get_global_bluez_manager, "instance", BlueZManager())
loop = asyncio.get_event_loop()

instance: BlueZManager = getattr(get_global_bluez_manager, "instance")
if not hasattr(get_global_bluez_manager, "instance"):
get_global_bluez_manager.instance = BlueZManager()
get_global_bluez_manager.loop = loop

instance: BlueZManager = get_global_bluez_manager.instance
stored_loop: Union(
asyncio.SelectorEventLoop, asyncio.ProactorEventLoop, None
) = get_global_bluez_manager.loop

if loop != stored_loop:
if stored_loop.is_closed():
logger.debug("Replacing BlueZManager for new event loop")
instance = BlueZManager()
get_global_bluez_manager.instance = instance
get_global_bluez_manager.loop = loop
else:
logger.warning("Accessing BlueZ from two open event loops is not supported")

await instance.async_init()

Expand Down

0 comments on commit 1c581c0

Please sign in to comment.