Avoid polling state machine for available state in HomeKit (#101799)

This commit is contained in:
J. Nick Koston 2023-10-13 14:23:15 -10:00 committed by GitHub
parent 371d988643
commit 8fd5d89d43
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -373,6 +373,7 @@ class HomeAccessory(Accessory): # type: ignore[misc]
"""Add battery service if available""" """Add battery service if available"""
state = self.hass.states.get(self.entity_id) state = self.hass.states.get(self.entity_id)
self._update_available_from_state(state)
assert state is not None assert state is not None
entity_attributes = state.attributes entity_attributes = state.attributes
battery_found = entity_attributes.get(ATTR_BATTERY_LEVEL) battery_found = entity_attributes.get(ATTR_BATTERY_LEVEL)
@ -415,16 +416,20 @@ class HomeAccessory(Accessory): # type: ignore[misc]
CHAR_STATUS_LOW_BATTERY, value=0 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 @property
def available(self) -> bool: def available(self) -> bool:
"""Return if accessory is available.""" """Return if accessory is available."""
state = self.hass.states.get(self.entity_id) return self._available
return state is not None and state.state != STATE_UNAVAILABLE
async def run(self) -> None: async def run(self) -> None:
"""Handle accessory driver started event.""" """Handle accessory driver started event."""
if state := self.hass.states.get(self.entity_id): if state := self.hass.states.get(self.entity_id):
self.async_update_state_callback(state) self.async_update_state_callback(state)
self._update_available_from_state(state)
self._subscriptions.append( self._subscriptions.append(
async_track_state_change_event( async_track_state_change_event(
self.hass, [self.entity_id], self.async_update_event_state_callback 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.""" """Handle state change event listener callback."""
new_state = event.data["new_state"] new_state = event.data["new_state"]
old_state = event.data["old_state"] old_state = event.data["old_state"]
self._update_available_from_state(new_state)
if ( if (
new_state new_state
and old_state and old_state