From af820a7ae27fb253158b4bea0f6bc035bec60b97 Mon Sep 17 00:00:00 2001 From: Vyacheslav Linnik Date: Tue, 26 Oct 2021 18:32:04 +0300 Subject: [PATCH] add missing timeout options --- AUTHORS.rst | 1 + CHANGELOG.rst | 1 + bleak/backends/bluezdbus/client.py | 20 ++++++++++++++----- .../corebluetooth/PeripheralDelegate.py | 11 +++++++--- bleak/backends/winrt/client.py | 8 ++++++-- 5 files changed, 31 insertions(+), 10 deletions(-) diff --git a/AUTHORS.rst b/AUTHORS.rst index c2140593..05fe4c72 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -19,3 +19,4 @@ Contributors * Bernie Conrad * Jonathan Soto * Kyle J. Williams +* Vyacheslav Linnik diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 25cf7329..18c82e09 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -16,6 +16,7 @@ Fixed of the same characteristic are used. Fixes #675. * Fixed reading a characteristic on CoreBluetooth backend also triggers notification callback. +* Removed hardcoded timeout values in all backends. `0.13.0`_ (2021-10-20) diff --git a/bleak/backends/bluezdbus/client.py b/bleak/backends/bluezdbus/client.py index 2f1c8499..2deed972 100644 --- a/bleak/backends/bluezdbus/client.py +++ b/bleak/backends/bluezdbus/client.py @@ -90,7 +90,7 @@ async def connect(self, **kwargs) -> bool: """Connect to the specified GATT server. Keyword Args: - timeout (float): Timeout for required ``BleakScanner.find_device_by_address`` call. Defaults to 10.0. + timeout (float): Defaults to 10.0. Returns: Boolean representing connection status. @@ -377,9 +377,12 @@ def _cleanup_all(self) -> None: self.services = BleakGATTServiceCollection() self._services_resolved = False - async def disconnect(self) -> bool: + async def disconnect(self, **kwargs) -> bool: """Disconnect from the specified GATT server. + Keyword Args: + timeout (float): Defaults to 10.0. + Returns: Boolean representing if device is disconnected. @@ -396,10 +399,11 @@ async def disconnect(self) -> bool: logger.debug(f"already disconnected ({self._device_path})") return True + timeout = kwargs.get("timeout", self._timeout) if self._disconnecting_event: # another call to disconnect() is already in progress logger.debug(f"already in progress ({self._device_path})") - await asyncio.wait_for(self._disconnecting_event.wait(), timeout=10) + await asyncio.wait_for(self._disconnecting_event.wait(), timeout=timeout) elif self.is_connected: self._disconnecting_event = asyncio.Event() try: @@ -413,7 +417,9 @@ async def disconnect(self) -> bool: ) ) assert_reply(reply) - await asyncio.wait_for(self._disconnecting_event.wait(), timeout=10) + await asyncio.wait_for( + self._disconnecting_event.wait(), timeout=timeout + ) finally: self._disconnecting_event = None @@ -575,6 +581,9 @@ def mtu_size(self) -> int: async def get_services(self, **kwargs) -> BleakGATTServiceCollection: """Get all services registered for this GATT server. + Keyword Args: + timeout (float): Defaults to 10.0. + Returns: A :py:class:`bleak.backends.service.BleakGATTServiceCollection` with this device's services tree. @@ -585,11 +594,12 @@ async def get_services(self, **kwargs) -> BleakGATTServiceCollection: if self._services_resolved: return self.services + timeout = kwargs.get("timeout", self._timeout) if not self._properties["ServicesResolved"]: logger.debug(f"Waiting for ServicesResolved ({self._device_path})") self._services_resolved_event = asyncio.Event() try: - await asyncio.wait_for(self._services_resolved_event.wait(), 5) + await asyncio.wait_for(self._services_resolved_event.wait(), timeout) finally: self._services_resolved_event = None diff --git a/bleak/backends/corebluetooth/PeripheralDelegate.py b/bleak/backends/corebluetooth/PeripheralDelegate.py index 74353883..9f1c22fc 100644 --- a/bleak/backends/corebluetooth/PeripheralDelegate.py +++ b/bleak/backends/corebluetooth/PeripheralDelegate.py @@ -9,7 +9,7 @@ import asyncio import itertools import logging -from typing import Callable, Any, Dict, Iterable, NewType, Optional +from typing import Callable, Any, Dict, Iterable, NewType, Optional, Union import objc from Foundation import NSNumber, NSObject, NSArray, NSData, NSError, NSUUID, NSString @@ -125,17 +125,22 @@ async def discover_descriptors(self, characteristic: CBCharacteristic) -> NSArra @objc.python_method async def read_characteristic( - self, characteristic: CBCharacteristic, use_cached: bool = True + self, + characteristic: CBCharacteristic, + use_cached: bool = True, + timeout: Optional[Union[int, float]] = None, ) -> NSData: if characteristic.value() is not None and use_cached: return characteristic.value() + if timeout is None: + timeout = self._timeout future = self._event_loop.create_future() self._characteristic_read_futures[characteristic.handle()] = future try: self.peripheral.readValueForCharacteristic_(characteristic) - return await asyncio.wait_for(future, timeout=5) + return await asyncio.wait_for(future, timeout=timeout) finally: del self._characteristic_read_futures[characteristic.handle()] diff --git a/bleak/backends/winrt/client.py b/bleak/backends/winrt/client.py index 850dd883..8b827230 100644 --- a/bleak/backends/winrt/client.py +++ b/bleak/backends/winrt/client.py @@ -258,14 +258,18 @@ def _ConnectionStatusChanged_Handler(sender, args): return True - async def disconnect(self) -> bool: + async def disconnect(self, **kwargs) -> bool: """Disconnect from the specified GATT server. + Keyword Args: + timeout (float): Defaults to 10.0. + Returns: Boolean representing if device is disconnected. """ logger.debug("Disconnecting from BLE device...") + timeout = kwargs.get("timeout", self._timeout) # Remove notifications. for handle, event_handler_token in list(self._notification_callbacks.items()): char = self.services.get_characteristic(handle) @@ -289,7 +293,7 @@ async def disconnect(self) -> bool: self._disconnect_events.append(event) try: self._requester.close() - await asyncio.wait_for(event.wait(), timeout=10) + await asyncio.wait_for(event.wait(), timeout=timeout) finally: self._disconnect_events.remove(event)