Template binary sensor to not track all state changes (#18573)
This commit is contained in:
parent
97c493448b
commit
84fd66c8a1
2 changed files with 111 additions and 30 deletions
|
@ -58,10 +58,12 @@ async def async_setup_platform(hass, config, async_add_entities,
|
|||
entity_ids = set()
|
||||
manual_entity_ids = device_config.get(ATTR_ENTITY_ID)
|
||||
|
||||
for template in (
|
||||
value_template,
|
||||
icon_template,
|
||||
entity_picture_template,
|
||||
invalid_templates = []
|
||||
|
||||
for tpl_name, template in (
|
||||
(CONF_VALUE_TEMPLATE, value_template),
|
||||
(CONF_ICON_TEMPLATE, icon_template),
|
||||
(CONF_ENTITY_PICTURE_TEMPLATE, entity_picture_template),
|
||||
):
|
||||
if template is None:
|
||||
continue
|
||||
|
@ -73,6 +75,8 @@ async def async_setup_platform(hass, config, async_add_entities,
|
|||
template_entity_ids = template.extract_entities()
|
||||
if template_entity_ids == MATCH_ALL:
|
||||
entity_ids = MATCH_ALL
|
||||
# Cut off _template from name
|
||||
invalid_templates.append(tpl_name[:-9])
|
||||
elif entity_ids != MATCH_ALL:
|
||||
entity_ids |= set(template_entity_ids)
|
||||
|
||||
|
@ -81,6 +85,14 @@ async def async_setup_platform(hass, config, async_add_entities,
|
|||
elif entity_ids != MATCH_ALL:
|
||||
entity_ids = list(entity_ids)
|
||||
|
||||
if invalid_templates:
|
||||
_LOGGER.warning(
|
||||
'Template binary sensor %s has no entity ids configured to'
|
||||
' track nor were we able to extract the entities to track'
|
||||
' from the %s template(s). This entity will only be able'
|
||||
' to be updated manually.',
|
||||
device, ', '.join(invalid_templates))
|
||||
|
||||
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
|
||||
device_class = device_config.get(CONF_DEVICE_CLASS)
|
||||
delay_on = device_config.get(CONF_DELAY_ON)
|
||||
|
@ -132,10 +144,12 @@ class BinarySensorTemplate(BinarySensorDevice):
|
|||
@callback
|
||||
def template_bsensor_startup(event):
|
||||
"""Update template on startup."""
|
||||
async_track_state_change(
|
||||
self.hass, self._entities, template_bsensor_state_listener)
|
||||
if self._entities != MATCH_ALL:
|
||||
# Track state change only for valid templates
|
||||
async_track_state_change(
|
||||
self.hass, self._entities, template_bsensor_state_listener)
|
||||
|
||||
self.hass.async_add_job(self.async_check_state)
|
||||
self.async_check_state()
|
||||
|
||||
self.hass.bus.async_listen_once(
|
||||
EVENT_HOMEASSISTANT_START, template_bsensor_startup)
|
||||
|
@ -233,3 +247,7 @@ class BinarySensorTemplate(BinarySensorDevice):
|
|||
async_track_same_state(
|
||||
self.hass, period, set_state, entity_ids=self._entities,
|
||||
async_check_same_func=lambda *args: self._async_render() == state)
|
||||
|
||||
async def async_update(self):
|
||||
"""Force update of the state from the template."""
|
||||
self.async_check_state()
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue