Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bluez: Allow accessing Bleak from multiple individual event loops (not simultaneously) #1031

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
) = 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