From cc47ff30b3dc7fb8edd46d7a903f7252f9141c73 Mon Sep 17 00:00:00 2001 From: Jc2k Date: Thu, 27 Jul 2023 15:32:53 +0100 Subject: [PATCH] Split availability and data subscriptions in homekit_controller (#97337) --- .../components/homekit_controller/connection.py | 16 ++++++++++++---- .../components/homekit_controller/entity.py | 4 +++- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/homekit_controller/connection.py b/homeassistant/components/homekit_controller/connection.py index d101517e002541..4ba22317644a67 100644 --- a/homeassistant/components/homekit_controller/connection.py +++ b/homeassistant/components/homekit_controller/connection.py @@ -142,7 +142,7 @@ def __init__( function=self.async_update, ) - self._all_subscribers: set[CALLBACK_TYPE] = set() + self._availability_callbacks: set[CALLBACK_TYPE] = set() self._subscriptions: dict[tuple[int, int], set[CALLBACK_TYPE]] = {} @property @@ -189,7 +189,7 @@ def async_set_available_state(self, available: bool) -> None: if self.available == available: return self.available = available - for callback_ in self._all_subscribers: + for callback_ in self._availability_callbacks: callback_() async def _async_populate_ble_accessory_state(self, event: Event) -> None: @@ -811,12 +811,10 @@ def async_subscribe( self, characteristics: Iterable[tuple[int, int]], callback_: CALLBACK_TYPE ) -> CALLBACK_TYPE: """Add characteristics to the watch list.""" - self._all_subscribers.add(callback_) for aid_iid in characteristics: self._subscriptions.setdefault(aid_iid, set()).add(callback_) def _unsub(): - self._all_subscribers.remove(callback_) for aid_iid in characteristics: self._subscriptions[aid_iid].remove(callback_) if not self._subscriptions[aid_iid]: @@ -824,6 +822,16 @@ def _unsub(): return _unsub + @callback + def async_subscribe_availability(self, callback_: CALLBACK_TYPE) -> CALLBACK_TYPE: + """Add characteristics to the watch list.""" + self._availability_callbacks.add(callback_) + + def _unsub(): + self._availability_callbacks.remove(callback_) + + return _unsub + async def get_characteristics(self, *args: Any, **kwargs: Any) -> dict[str, Any]: """Read latest state from homekit accessory.""" return await self.pairing.get_characteristics(*args, **kwargs) diff --git a/homeassistant/components/homekit_controller/entity.py b/homeassistant/components/homekit_controller/entity.py index f6aadfac7ac90d..046dc9f17ec294 100644 --- a/homeassistant/components/homekit_controller/entity.py +++ b/homeassistant/components/homekit_controller/entity.py @@ -58,7 +58,9 @@ async def async_added_to_hass(self) -> None: self.all_characteristics, self._async_write_ha_state ) ) - + self.async_on_remove( + self._accessory.async_subscribe_availability(self._async_write_ha_state) + ) self._accessory.add_pollable_characteristics(self.pollable_characteristics) await self._accessory.add_watchable_characteristics( self.watchable_characteristics