| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import contextlib |
| 5 |
import logging |
| 6 |
|
| 7 |
from .const import DBUS_CONNECT_TIMEOUT, IS_LINUX |
| 8 |
from .util import asyncio_timeout |
| 9 |
|
| 10 |
_LOGGER = logging.getLogger(__name__) |
| 11 |
|
| 12 |
_global_instances: dict[asyncio.AbstractEventLoop, BlueZManager] | None = None |
| 13 |
if IS_LINUX: |
| 14 |
with contextlib.suppress(ImportError): # pragma: no cover |
| 15 |
from bleak.backends.bluezdbus.manager import ( # pragma: no cover |
| 16 |
BlueZManager, |
| 17 |
get_global_bluez_manager, |
| 18 |
) |
| 19 |
|
| 20 |
with contextlib.suppress(ImportError): # pragma: no cover |
| 21 |
from bleak.backends.bluezdbus.manager import ( # type: ignore[no-redef] # pragma: no cover |
| 22 |
_global_instances, |
| 23 |
) |
| 24 |
|
| 25 |
|
| 26 |
def get_global_bluez_manager_sync() -> BlueZManager | None: |
| 27 |
"""Return the BlueZ manager bleak built for the running loop, if any.""" |
| 28 |
if not _global_instances: |
| 29 |
return None |
| 30 |
try: |
| 31 |
loop = asyncio.get_running_loop() |
| 32 |
except RuntimeError: |
| 33 |
_LOGGER.debug("get_global_bluez_manager_sync called off the event loop") |
| 34 |
return None |
| 35 |
return _global_instances.get(loop) |
| 36 |
|
| 37 |
|
| 38 |
async def get_global_bluez_manager_with_timeout() -> BlueZManager | None: |
| 39 |
"""Get the properties.""" |
| 40 |
if not IS_LINUX: |
| 41 |
return None |
| 42 |
|
| 43 |
if manager := get_global_bluez_manager_sync(): |
| 44 |
return manager |
| 45 |
|
| 46 |
if ( |
| 47 |
getattr(get_global_bluez_manager_with_timeout, "_has_dbus_socket", None) |
| 48 |
is False |
| 49 |
): |
| 50 |
# We are not running on a system with DBus do don't |
| 51 |
# keep trying to call get_global_bluez_manager as it |
| 52 |
# waits for a bit trying to connect to DBus. |
| 53 |
return None |
| 54 |
|
| 55 |
try: |
| 56 |
async with asyncio_timeout(DBUS_CONNECT_TIMEOUT): |
| 57 |
return await get_global_bluez_manager() |
| 58 |
except FileNotFoundError as ex: |
| 59 |
setattr(get_global_bluez_manager_with_timeout, "_has_dbus_socket", False) |
| 60 |
_LOGGER.debug( |
| 61 |
"Dbus socket at %s not found, will not try again until next restart: %s", |
| 62 |
ex.filename, |
| 63 |
ex, |
| 64 |
) |
| 65 |
except asyncio.TimeoutError: |
| 66 |
setattr(get_global_bluez_manager_with_timeout, "_has_dbus_socket", False) |
| 67 |
_LOGGER.debug( |
| 68 |
"Timed out trying to connect to DBus; will not try again until next restart" |
| 69 |
) |
| 70 |
except Exception as ex: # pylint: disable=broad-except |
| 71 |
_LOGGER.debug( |
| 72 |
"get_global_bluez_manager_with_timeout failed: %s", ex, exc_info=True |
| 73 |
) |
| 74 |
|
| 75 |
return None |
| 76 |
|
| 77 |
|
| 78 |
def _reset_dbus_socket_cache() -> None: |
| 79 |
"""Reset the dbus socket cache.""" |
| 80 |
setattr(get_global_bluez_manager_with_timeout, "_has_dbus_socket", None) |