From 3064e89310ee8dde692d675c89cb20db400351f5 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 12 Jan 2024 21:09:27 -1000 Subject: [PATCH] Handle cancellation while waiting for an encrypted BLE response --- aiohomekit/controller/ble/pairing.py | 34 ++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/aiohomekit/controller/ble/pairing.py b/aiohomekit/controller/ble/pairing.py index b0b81f05..3db1117a 100644 --- a/aiohomekit/controller/ble/pairing.py +++ b/aiohomekit/controller/ble/pairing.py @@ -426,15 +426,31 @@ async def _async_request_under_lock( char.service.type, char.type, endpoint_iid ) - pdu_status, result_data = await ble_request( - self.client, - self._encryption_key, - self._decryption_key, - opcode, - endpoint, - endpoint_iid, - data, - ) + try: + pdu_status, result_data = await ble_request( + self.client, + self._encryption_key, + self._decryption_key, + opcode, + endpoint, + endpoint_iid, + data, + ) + except BaseException as ex: + # If the request fails for any reason (especially + # cancellation), we need to close the connection + # otherwise the encryption counters will be out of sync + try: + await self._close_while_locked() + except Exception as exc: + logger.debug( + "%s: Failed to close connection after exception: %s", + self.name, + exc, + ) + # Make sure we propagate the exception to the caller + # especially if it was a cancellation + raise ex if not self.client or not self.client.is_connected: logger.debug("%s: Client not connected; rssi=%s", self.name, self.rssi)