Skip to content

Commit

Permalink
Split availability and data subscriptions in homekit_controller (home…
Browse files Browse the repository at this point in the history
  • Loading branch information
Jc2k authored Jul 27, 2023
1 parent cbc8ebb commit cc47ff3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
16 changes: 12 additions & 4 deletions homeassistant/components/homekit_controller/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -811,19 +811,27 @@ 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]:
del self._subscriptions[aid_iid]

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)
Expand Down
4 changes: 3 additions & 1 deletion homeassistant/components/homekit_controller/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit cc47ff3

Please sign in to comment.