|
10 | 10 | from typing import Any, Callable, TypeVar, cast |
11 | 11 | from uuid import UUID |
12 | 12 |
|
13 | | -import async_timeout |
14 | 13 | from bleak.backends.device import BLEDevice |
15 | 14 | from bleak.backends.service import BleakGATTCharacteristic, BleakGATTServiceCollection |
16 | 15 | from bleak.exc import BleakDBusError |
@@ -109,6 +108,12 @@ def _merge_data(old_data: dict[str, Any], new_data: dict[str, Any]) -> dict[str, |
109 | 108 | return merged |
110 | 109 |
|
111 | 110 |
|
| 111 | +def _handle_timeout(fut: asyncio.Future[None]) -> None: |
| 112 | + """Handle a timeout.""" |
| 113 | + if not fut.done(): |
| 114 | + fut.set_exception(asyncio.TimeoutError) |
| 115 | + |
| 116 | + |
112 | 117 | class SwitchbotBaseDevice: |
113 | 118 | """Base Representation of a Switchbot Device.""" |
114 | 119 |
|
@@ -451,16 +456,28 @@ async def _execute_command_locked(self, key: str, command: bytes) -> bytes: |
451 | 456 | assert self._client is not None |
452 | 457 | assert self._read_char is not None |
453 | 458 | assert self._write_char is not None |
454 | | - self._notify_future = asyncio.Future() |
| 459 | + self._notify_future = self.loop.create_future() |
455 | 460 | client = self._client |
456 | 461 |
|
457 | 462 | _LOGGER.debug("%s: Sending command: %s", self.name, key) |
458 | 463 | await client.write_gatt_char(self._write_char, command, False) |
459 | 464 |
|
460 | | - async with async_timeout.timeout(5): |
| 465 | + timeout = 5 |
| 466 | + timeout_handle = self.loop.call_at( |
| 467 | + self.loop.time() + timeout, _handle_timeout, self._notify_future |
| 468 | + ) |
| 469 | + timeout_expired = False |
| 470 | + try: |
461 | 471 | notify_msg = await self._notify_future |
| 472 | + except asyncio.TimeoutError: |
| 473 | + timeout_expired = True |
| 474 | + raise |
| 475 | + finally: |
| 476 | + if not timeout_expired: |
| 477 | + timeout_handle.cancel() |
| 478 | + self._notify_future = None |
| 479 | + |
462 | 480 | _LOGGER.debug("%s: Notification received: %s", self.name, notify_msg.hex()) |
463 | | - self._notify_future = None |
464 | 481 |
|
465 | 482 | if notify_msg == b"\x07": |
466 | 483 | _LOGGER.error("Password required") |
|
0 commit comments