Convert template fan to use async_track_template_result (#38983)
* Convert template lock to use async_track_template_result * Convert template switch to use async_track_template_result * Convert template fan to use async_track_template_result
This commit is contained in:
parent
264e340b9e
commit
f3d077c1e1
3 changed files with 91 additions and 140 deletions
|
@ -23,8 +23,6 @@ from homeassistant.const import (
|
||||||
CONF_FRIENDLY_NAME,
|
CONF_FRIENDLY_NAME,
|
||||||
CONF_UNIQUE_ID,
|
CONF_UNIQUE_ID,
|
||||||
CONF_VALUE_TEMPLATE,
|
CONF_VALUE_TEMPLATE,
|
||||||
EVENT_HOMEASSISTANT_START,
|
|
||||||
MATCH_ALL,
|
|
||||||
STATE_OFF,
|
STATE_OFF,
|
||||||
STATE_ON,
|
STATE_ON,
|
||||||
STATE_UNAVAILABLE,
|
STATE_UNAVAILABLE,
|
||||||
|
@ -36,8 +34,8 @@ import homeassistant.helpers.config_validation as cv
|
||||||
from homeassistant.helpers.entity import async_generate_entity_id
|
from homeassistant.helpers.entity import async_generate_entity_id
|
||||||
from homeassistant.helpers.script import Script
|
from homeassistant.helpers.script import Script
|
||||||
|
|
||||||
from . import extract_entities, initialise_templates
|
|
||||||
from .const import CONF_AVAILABILITY_TEMPLATE
|
from .const import CONF_AVAILABILITY_TEMPLATE
|
||||||
|
from .template_entity import TemplateEntityWithAvailability
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
@ -104,17 +102,6 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
|
||||||
speed_list = device_config[CONF_SPEED_LIST]
|
speed_list = device_config[CONF_SPEED_LIST]
|
||||||
unique_id = device_config.get(CONF_UNIQUE_ID)
|
unique_id = device_config.get(CONF_UNIQUE_ID)
|
||||||
|
|
||||||
templates = {
|
|
||||||
CONF_VALUE_TEMPLATE: state_template,
|
|
||||||
CONF_SPEED_TEMPLATE: speed_template,
|
|
||||||
CONF_OSCILLATING_TEMPLATE: oscillating_template,
|
|
||||||
CONF_DIRECTION_TEMPLATE: direction_template,
|
|
||||||
CONF_AVAILABILITY_TEMPLATE: availability_template,
|
|
||||||
}
|
|
||||||
|
|
||||||
initialise_templates(hass, templates)
|
|
||||||
entity_ids = extract_entities(device, "fan", None, templates)
|
|
||||||
|
|
||||||
fans.append(
|
fans.append(
|
||||||
TemplateFan(
|
TemplateFan(
|
||||||
hass,
|
hass,
|
||||||
|
@ -131,7 +118,6 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
|
||||||
set_oscillating_action,
|
set_oscillating_action,
|
||||||
set_direction_action,
|
set_direction_action,
|
||||||
speed_list,
|
speed_list,
|
||||||
entity_ids,
|
|
||||||
unique_id,
|
unique_id,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
@ -139,7 +125,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
|
||||||
async_add_entities(fans)
|
async_add_entities(fans)
|
||||||
|
|
||||||
|
|
||||||
class TemplateFan(FanEntity):
|
class TemplateFan(TemplateEntityWithAvailability, FanEntity):
|
||||||
"""A template fan component."""
|
"""A template fan component."""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
|
@ -158,10 +144,10 @@ class TemplateFan(FanEntity):
|
||||||
set_oscillating_action,
|
set_oscillating_action,
|
||||||
set_direction_action,
|
set_direction_action,
|
||||||
speed_list,
|
speed_list,
|
||||||
entity_ids,
|
|
||||||
unique_id,
|
unique_id,
|
||||||
):
|
):
|
||||||
"""Initialize the fan."""
|
"""Initialize the fan."""
|
||||||
|
super().__init__(availability_template)
|
||||||
self.hass = hass
|
self.hass = hass
|
||||||
self.entity_id = async_generate_entity_id(
|
self.entity_id = async_generate_entity_id(
|
||||||
ENTITY_ID_FORMAT, device_id, hass=hass
|
ENTITY_ID_FORMAT, device_id, hass=hass
|
||||||
|
@ -172,8 +158,6 @@ class TemplateFan(FanEntity):
|
||||||
self._speed_template = speed_template
|
self._speed_template = speed_template
|
||||||
self._oscillating_template = oscillating_template
|
self._oscillating_template = oscillating_template
|
||||||
self._direction_template = direction_template
|
self._direction_template = direction_template
|
||||||
self._availability_template = availability_template
|
|
||||||
self._available = True
|
|
||||||
self._supported_features = 0
|
self._supported_features = 0
|
||||||
|
|
||||||
domain = __name__.split(".")[-2]
|
domain = __name__.split(".")[-2]
|
||||||
|
@ -211,7 +195,6 @@ class TemplateFan(FanEntity):
|
||||||
if self._direction_template:
|
if self._direction_template:
|
||||||
self._supported_features |= SUPPORT_DIRECTION
|
self._supported_features |= SUPPORT_DIRECTION
|
||||||
|
|
||||||
self._entities = entity_ids
|
|
||||||
self._unique_id = unique_id
|
self._unique_id = unique_id
|
||||||
|
|
||||||
# List of valid speeds
|
# List of valid speeds
|
||||||
|
@ -257,16 +240,6 @@ class TemplateFan(FanEntity):
|
||||||
"""Return the oscillation state."""
|
"""Return the oscillation state."""
|
||||||
return self._direction
|
return self._direction
|
||||||
|
|
||||||
@property
|
|
||||||
def should_poll(self):
|
|
||||||
"""Return the polling state."""
|
|
||||||
return False
|
|
||||||
|
|
||||||
@property
|
|
||||||
def available(self):
|
|
||||||
"""Return availability of Device."""
|
|
||||||
return self._available
|
|
||||||
|
|
||||||
# pylint: disable=arguments-differ
|
# pylint: disable=arguments-differ
|
||||||
async def async_turn_on(self, speed: str = None) -> None:
|
async def async_turn_on(self, speed: str = None) -> None:
|
||||||
"""Turn on the fan."""
|
"""Turn on the fan."""
|
||||||
|
@ -331,59 +304,57 @@ class TemplateFan(FanEntity):
|
||||||
", ".join(_VALID_DIRECTIONS),
|
", ".join(_VALID_DIRECTIONS),
|
||||||
)
|
)
|
||||||
|
|
||||||
async def async_added_to_hass(self):
|
|
||||||
"""Register callbacks."""
|
|
||||||
|
|
||||||
@callback
|
@callback
|
||||||
def template_fan_state_listener(event):
|
def _update_state(self, result):
|
||||||
"""Handle target device state changes."""
|
super()._update_state(result)
|
||||||
self.async_schedule_update_ha_state(True)
|
if isinstance(result, TemplateError):
|
||||||
|
|
||||||
@callback
|
|
||||||
def template_fan_startup(event):
|
|
||||||
"""Update template on startup."""
|
|
||||||
if self._entities != MATCH_ALL:
|
|
||||||
# Track state change only for valid templates
|
|
||||||
self.hass.helpers.event.async_track_state_change_event(
|
|
||||||
self._entities, template_fan_state_listener
|
|
||||||
)
|
|
||||||
|
|
||||||
self.async_schedule_update_ha_state(True)
|
|
||||||
|
|
||||||
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, template_fan_startup)
|
|
||||||
|
|
||||||
async def async_update(self):
|
|
||||||
"""Update the state from the template."""
|
|
||||||
# Update state
|
|
||||||
try:
|
|
||||||
state = self._template.async_render()
|
|
||||||
except TemplateError as ex:
|
|
||||||
_LOGGER.error(ex)
|
|
||||||
state = None
|
|
||||||
self._state = None
|
self._state = None
|
||||||
|
return
|
||||||
|
|
||||||
# Validate state
|
# Validate state
|
||||||
if state in _VALID_STATES:
|
if result in _VALID_STATES:
|
||||||
self._state = state
|
self._state = result
|
||||||
elif state in [STATE_UNAVAILABLE, STATE_UNKNOWN]:
|
elif result in [STATE_UNAVAILABLE, STATE_UNKNOWN]:
|
||||||
self._state = None
|
self._state = None
|
||||||
else:
|
else:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Received invalid fan is_on state: %s. Expected: %s",
|
"Received invalid fan is_on state: %s. Expected: %s",
|
||||||
state,
|
result,
|
||||||
", ".join(_VALID_STATES),
|
", ".join(_VALID_STATES),
|
||||||
)
|
)
|
||||||
self._state = None
|
self._state = None
|
||||||
|
|
||||||
# Update speed if 'speed_template' is configured
|
async def async_added_to_hass(self):
|
||||||
|
"""Register callbacks."""
|
||||||
|
self.add_template_attribute("_state", self._template, None, self._update_state)
|
||||||
if self._speed_template is not None:
|
if self._speed_template is not None:
|
||||||
try:
|
self.add_template_attribute(
|
||||||
speed = self._speed_template.async_render()
|
"_speed",
|
||||||
except TemplateError as ex:
|
self._speed_template,
|
||||||
_LOGGER.error(ex)
|
None,
|
||||||
speed = None
|
self._update_speed,
|
||||||
self._state = None
|
none_on_template_error=True,
|
||||||
|
)
|
||||||
|
if self._oscillating_template is not None:
|
||||||
|
self.add_template_attribute(
|
||||||
|
"_oscillating",
|
||||||
|
self._oscillating_template,
|
||||||
|
None,
|
||||||
|
self._update_oscillating,
|
||||||
|
none_on_template_error=True,
|
||||||
|
)
|
||||||
|
if self._direction_template is not None:
|
||||||
|
self.add_template_attribute(
|
||||||
|
"_direction",
|
||||||
|
self._direction_template,
|
||||||
|
None,
|
||||||
|
self._update_direction,
|
||||||
|
none_on_template_error=True,
|
||||||
|
)
|
||||||
|
await super().async_added_to_hass()
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _update_speed(self, speed):
|
||||||
# Validate speed
|
# Validate speed
|
||||||
if speed in self._speed_list:
|
if speed in self._speed_list:
|
||||||
self._speed = speed
|
self._speed = speed
|
||||||
|
@ -395,15 +366,8 @@ class TemplateFan(FanEntity):
|
||||||
)
|
)
|
||||||
self._speed = None
|
self._speed = None
|
||||||
|
|
||||||
# Update oscillating if 'oscillating_template' is configured
|
@callback
|
||||||
if self._oscillating_template is not None:
|
def _update_oscillating(self, oscillating):
|
||||||
try:
|
|
||||||
oscillating = self._oscillating_template.async_render()
|
|
||||||
except TemplateError as ex:
|
|
||||||
_LOGGER.error(ex)
|
|
||||||
oscillating = None
|
|
||||||
self._state = None
|
|
||||||
|
|
||||||
# Validate osc
|
# Validate osc
|
||||||
if oscillating == "True" or oscillating is True:
|
if oscillating == "True" or oscillating is True:
|
||||||
self._oscillating = True
|
self._oscillating = True
|
||||||
|
@ -413,21 +377,13 @@ class TemplateFan(FanEntity):
|
||||||
self._oscillating = None
|
self._oscillating = None
|
||||||
else:
|
else:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
"Received invalid oscillating: %s. Expected: True/False",
|
"Received invalid oscillating: %s. Expected: True/False", oscillating,
|
||||||
oscillating,
|
|
||||||
)
|
)
|
||||||
self._oscillating = None
|
self._oscillating = None
|
||||||
|
|
||||||
# Update direction if 'direction_template' is configured
|
@callback
|
||||||
if self._direction_template is not None:
|
def _update_direction(self, direction):
|
||||||
try:
|
# Validate direction
|
||||||
direction = self._direction_template.async_render()
|
|
||||||
except TemplateError as ex:
|
|
||||||
_LOGGER.error(ex)
|
|
||||||
direction = None
|
|
||||||
self._state = None
|
|
||||||
|
|
||||||
# Validate speed
|
|
||||||
if direction in _VALID_DIRECTIONS:
|
if direction in _VALID_DIRECTIONS:
|
||||||
self._direction = direction
|
self._direction = direction
|
||||||
elif direction in [STATE_UNAVAILABLE, STATE_UNKNOWN]:
|
elif direction in [STATE_UNAVAILABLE, STATE_UNKNOWN]:
|
||||||
|
@ -439,17 +395,3 @@ class TemplateFan(FanEntity):
|
||||||
", ".join(_VALID_DIRECTIONS),
|
", ".join(_VALID_DIRECTIONS),
|
||||||
)
|
)
|
||||||
self._direction = None
|
self._direction = None
|
||||||
|
|
||||||
# Update Availability if 'availability_template' is defined
|
|
||||||
if self._availability_template is not None:
|
|
||||||
try:
|
|
||||||
self._available = (
|
|
||||||
self._availability_template.async_render().lower() == "true"
|
|
||||||
)
|
|
||||||
except (TemplateError, ValueError) as ex:
|
|
||||||
_LOGGER.error(
|
|
||||||
"Could not render %s template %s: %s",
|
|
||||||
CONF_AVAILABILITY_TEMPLATE,
|
|
||||||
self._name,
|
|
||||||
ex,
|
|
||||||
)
|
|
||||||
|
|
|
@ -26,6 +26,7 @@ class _TemplateAttribute:
|
||||||
template: Template,
|
template: Template,
|
||||||
validator: Callable[[Any], Any] = match_all,
|
validator: Callable[[Any], Any] = match_all,
|
||||||
on_update: Optional[Callable[[Any], None]] = None,
|
on_update: Optional[Callable[[Any], None]] = None,
|
||||||
|
none_on_template_error: Optional[bool] = False,
|
||||||
):
|
):
|
||||||
"""Template attribute."""
|
"""Template attribute."""
|
||||||
self._entity = entity
|
self._entity = entity
|
||||||
|
@ -35,6 +36,7 @@ class _TemplateAttribute:
|
||||||
self.on_update = on_update
|
self.on_update = on_update
|
||||||
self.async_update = None
|
self.async_update = None
|
||||||
self.add_complete = False
|
self.add_complete = False
|
||||||
|
self.none_on_template_error = none_on_template_error
|
||||||
|
|
||||||
@callback
|
@callback
|
||||||
def async_setup(self):
|
def async_setup(self):
|
||||||
|
@ -75,6 +77,9 @@ class _TemplateAttribute:
|
||||||
self._attribute,
|
self._attribute,
|
||||||
self._entity.entity_id,
|
self._entity.entity_id,
|
||||||
)
|
)
|
||||||
|
if self.none_on_template_error:
|
||||||
|
self._default_update(result)
|
||||||
|
else:
|
||||||
self.on_update(result)
|
self.on_update(result)
|
||||||
self._write_update_if_added()
|
self._write_update_if_added()
|
||||||
|
|
||||||
|
@ -139,6 +144,7 @@ class TemplateEntity(Entity):
|
||||||
template: Template,
|
template: Template,
|
||||||
validator: Callable[[Any], Any] = match_all,
|
validator: Callable[[Any], Any] = match_all,
|
||||||
on_update: Optional[Callable[[Any], None]] = None,
|
on_update: Optional[Callable[[Any], None]] = None,
|
||||||
|
none_on_template_error: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Call in the constructor to add a template linked to a attribute.
|
Call in the constructor to add a template linked to a attribute.
|
||||||
|
@ -158,7 +164,9 @@ class TemplateEntity(Entity):
|
||||||
if the template or validator resulted in an error.
|
if the template or validator resulted in an error.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
attribute = _TemplateAttribute(self, attribute, template, validator, on_update)
|
attribute = _TemplateAttribute(
|
||||||
|
self, attribute, template, validator, on_update, none_on_template_error
|
||||||
|
)
|
||||||
attribute.async_setup()
|
attribute.async_setup()
|
||||||
self._template_attrs.append(attribute)
|
self._template_attrs.append(attribute)
|
||||||
|
|
||||||
|
|
|
@ -414,8 +414,9 @@ async def test_invalid_availability_template_keeps_component_available(hass, cap
|
||||||
await hass.async_block_till_done()
|
await hass.async_block_till_done()
|
||||||
|
|
||||||
assert hass.states.get("fan.test_fan").state != STATE_UNAVAILABLE
|
assert hass.states.get("fan.test_fan").state != STATE_UNAVAILABLE
|
||||||
assert ("Could not render availability_template template") in caplog.text
|
|
||||||
assert ("UndefinedError: 'x' is undefined") in caplog.text
|
assert "TemplateError" in caplog.text
|
||||||
|
assert "x" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
# End of template tests #
|
# End of template tests #
|
||||||
|
|
Loading…
Add table
Reference in a new issue