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)