From 8fd5d89d4372b44c44d954c1d5f6417435adb6ce Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 13 Oct 2023 14:23:15 -1000 Subject: [PATCH] Avoid polling state machine for available state in HomeKit (#101799) --- homeassistant/components/homekit/accessories.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/homekit/accessories.py b/homeassistant/components/homekit/accessories.py index 2e0d1e6c052..a14e0add488 100644 --- a/homeassistant/components/homekit/accessories.py +++ b/homeassistant/components/homekit/accessories.py @@ -373,6 +373,7 @@ class HomeAccessory(Accessory): # type: ignore[misc] """Add battery service if available""" state = self.hass.states.get(self.entity_id) + self._update_available_from_state(state) assert state is not None entity_attributes = state.attributes battery_found = entity_attributes.get(ATTR_BATTERY_LEVEL) @@ -415,16 +416,20 @@ class HomeAccessory(Accessory): # type: ignore[misc] CHAR_STATUS_LOW_BATTERY, value=0 ) + def _update_available_from_state(self, new_state: State | None) -> None: + """Update the available property based on the state.""" + self._available = new_state is not None and new_state.state != STATE_UNAVAILABLE + @property def available(self) -> bool: """Return if accessory is available.""" - state = self.hass.states.get(self.entity_id) - return state is not None and state.state != STATE_UNAVAILABLE + return self._available async def run(self) -> None: """Handle accessory driver started event.""" if state := self.hass.states.get(self.entity_id): self.async_update_state_callback(state) + self._update_available_from_state(state) self._subscriptions.append( async_track_state_change_event( self.hass, [self.entity_id], self.async_update_event_state_callback @@ -474,6 +479,7 @@ class HomeAccessory(Accessory): # type: ignore[misc] """Handle state change event listener callback.""" new_state = event.data["new_state"] old_state = event.data["old_state"] + self._update_available_from_state(new_state) if ( new_state and old_state