Ease code before adding color and temperature to light template (#30455)

* Split async_update

* Use pytest parameters to avoid duplicate code

* Fix UnboundLocalError

* Test error rendering for template state

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>
This commit is contained in:
tetienneandPaulus Schoutsen authored and Paulus Schoutsen committed 2020-01-07 17:22:42 +01:00
1 parent e18426051b
commit 13e6479b6e
4 files changed
+129 -175

No files matched your search

+39 -31
View File
@@ -267,38 +267,10 @@ class LightTemplate(Light):
self.async_schedule_update_ha_state()
async def async_update(self):
"""Update the state from the template."""
if self._template is not None:
try:
state = self._template.async_render().lower()
except TemplateError as ex:
_LOGGER.error(ex)
self._state = None
"""Update from templates."""
self.update_state()
if state in _VALID_STATES:
self._state = state in ("true", STATE_ON)
else:
_LOGGER.error(
"Received invalid light is_on state: %s. Expected: %s",
state,
", ".join(_VALID_STATES),
)
self._state = None
if self._level_template is not None:
try:
brightness = self._level_template.async_render()
except TemplateError as ex:
_LOGGER.error(ex)
self._state = None
if 0 <= int(brightness) <= 255:
self._brightness = int(brightness)
else:
_LOGGER.error(
"Received invalid brightness : %s. Expected: 0-255", brightness
)
self._brightness = None
self.update_brightness()
for property_name, template in (
("_icon", self._icon_template),
@@ -335,3 +307,39 @@ class LightTemplate(Light):
self._name,
ex,
)
@callback
def update_brightness(self):
"""Update the brightness from the template."""
if self._level_template is not None:
try:
brightness = self._level_template.async_render()
if 0 <= int(brightness) <= 255:
self._brightness = int(brightness)
else:
_LOGGER.error(
"Received invalid brightness : %s. Expected: 0-255", brightness
)
self._brightness = None
except TemplateError as ex:
_LOGGER.error(ex)
self._state = None
@callback
def update_state(self):
"""Update the state from the template."""
if self._template is not None:
try:
state = self._template.async_render().lower()
if state in _VALID_STATES:
self._state = state in ("true", STATE_ON)
else:
_LOGGER.error(
"Received invalid light is_on state: %s. Expected: %s",
state,
", ".join(_VALID_STATES),
)
self._state = None
except TemplateError as ex:
_LOGGER.error(ex)
self._state = None