Refactor bluetooth message handling to extract on_bluetooth_message (#772)

This commit is contained in:
J. Nick Koston 2023-11-28 08:23:19 -06:00 committed by GitHub
parent 5e0b6c1b07
commit 5ba404df48
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 23 deletions

View File

@ -77,6 +77,7 @@ from .client_callbacks import (
on_bluetooth_device_connection_response,
on_bluetooth_gatt_notify_data_response,
on_bluetooth_le_advertising_response,
on_bluetooth_message,
on_home_assistant_service_response,
on_state_msg,
on_subscribe_home_assistant_state_response,
@ -442,28 +443,6 @@ class APIClient:
(HomeassistantServiceResponse,),
)
def _filter_bluetooth_message(
self,
address: int,
handle: int,
msg: message.Message,
) -> bool:
"""Handle a Bluetooth message."""
if TYPE_CHECKING:
assert isinstance(
msg,
(
BluetoothGATTErrorResponse,
BluetoothGATTNotifyResponse,
BluetoothGATTReadResponse,
BluetoothGATTWriteResponse,
BluetoothDeviceConnectionResponse,
),
)
if type(msg) is BluetoothDeviceConnectionResponse:
return bool(msg.address == address)
return bool(msg.address == address and msg.handle == handle)
async def _send_bluetooth_message_await_response(
self,
address: int,
@ -476,7 +455,7 @@ class APIClient:
),
timeout: float = 10.0,
) -> message.Message:
message_filter = partial(self._filter_bluetooth_message, address, handle)
message_filter = partial(on_bluetooth_message, address, handle)
msg_types = (response_type, BluetoothGATTErrorResponse)
[resp] = await self._get_connection().send_messages_await_response_complex(
(request,),

View File

@ -8,3 +8,5 @@ cdef object CameraImageResponse, CameraState
cdef object HomeassistantServiceCall
cdef object BluetoothLEAdvertisement
cdef object BluetoothDeviceConnectionResponse

View File

@ -1,3 +1,4 @@
# pylint: disable=unidiomatic-typecheck
from __future__ import annotations
from asyncio import Future
@ -8,7 +9,11 @@ from google.protobuf import message
from .api_pb2 import ( # type: ignore
BluetoothConnectionsFreeResponse,
BluetoothDeviceConnectionResponse,
BluetoothGATTErrorResponse,
BluetoothGATTNotifyDataResponse,
BluetoothGATTNotifyResponse,
BluetoothGATTReadResponse,
BluetoothGATTWriteResponse,
BluetoothLEAdvertisementResponse,
BluetoothLERawAdvertisement,
BluetoothLERawAdvertisementsResponse,
@ -111,3 +116,18 @@ def on_bluetooth_device_connection_response(
# or we get an error.
if not connect_future.done():
connect_future.set_result(None)
def on_bluetooth_message(
address: int,
handle: int,
msg: BluetoothGATTErrorResponse
| BluetoothGATTNotifyResponse
| BluetoothGATTReadResponse
| BluetoothGATTWriteResponse
| BluetoothDeviceConnectionResponse,
) -> bool:
"""Handle a Bluetooth message."""
if type(msg) is BluetoothDeviceConnectionResponse:
return bool(msg.address == address)
return bool(msg.address == address and msg.handle == handle)