Improve binary sensor group when member is unknown or unavailable (#67468)

This commit is contained in:
Erik Montnemery 2022-03-02 16:53:13 +01:00 committed by GitHub
parent 5b8cf379a3
commit c5dd5e18c0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 5 deletions

View file

@ -17,6 +17,7 @@ from homeassistant.const import (
CONF_UNIQUE_ID,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import Event, HomeAssistant, callback
import homeassistant.helpers.config_validation as cv
@ -80,7 +81,6 @@ class BinarySensorGroup(GroupEntity, BinarySensorEntity):
self._attr_extra_state_attributes = {ATTR_ENTITY_ID: entity_ids}
self._attr_unique_id = unique_id
self._device_class = device_class
self._state: str | None = None
self.mode = any
if mode:
self.mode = all
@ -106,13 +106,23 @@ class BinarySensorGroup(GroupEntity, BinarySensorEntity):
def async_update_group_state(self) -> None:
"""Query all members and determine the binary sensor group state."""
all_states = [self.hass.states.get(x) for x in self._entity_ids]
# filtered_states are members currently in the state machine
filtered_states: list[str] = [x.state for x in all_states if x is not None]
# Set group as unavailable if all members are unavailable
self._attr_available = any(
state != STATE_UNAVAILABLE for state in filtered_states
)
if STATE_UNAVAILABLE in filtered_states:
valid_state = self.mode(
state not in (STATE_UNKNOWN, STATE_UNAVAILABLE) for state in filtered_states
)
if not valid_state:
# Set as unknown if any / all member is not unknown or unavailable
self._attr_is_on = None
else:
# Set as ON if any / all member is ON
states = list(map(lambda x: x == STATE_ON, filtered_states))
state = self.mode(states)
self._attr_is_on = state