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

Remove hardcoded timeout values #679

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ Contributors
* Bernie Conrad <[email protected]>
* Jonathan Soto <[email protected]>
* Kyle J. Williams <[email protected]>
* Vyacheslav Linnik <[email protected]>
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
20 changes: 15 additions & 5 deletions bleak/backends/bluezdbus/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps specify the unit as seconds; so "timeout (float): Defaults to 10.0 seconds."


Returns:
Boolean representing connection status.
Expand Down Expand Up @@ -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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps specify the unit as seconds; so "timeout (float): Defaults to 10.0 seconds."


Returns:
Boolean representing if device is disconnected.

Expand All @@ -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:
Expand All @@ -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

Expand Down Expand Up @@ -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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps specify the unit as seconds; so "timeout (float): Defaults to 10.0 seconds."


Returns:
A :py:class:`bleak.backends.service.BleakGATTServiceCollection` with this device's services tree.

Expand All @@ -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

Expand Down
11 changes: 8 additions & 3 deletions bleak/backends/corebluetooth/PeripheralDelegate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()]

Expand Down
8 changes: 6 additions & 2 deletions bleak/backends/winrt/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps specify the unit as seconds; so "timeout (float): Defaults to 10.0 seconds."


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)
Expand All @@ -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)

Expand Down