Convert template lock to use async_track_template_result (#38946)
This commit is contained in:
1 parent
1381b279f0
commit
d7f54ce98f
4 files changed
+68
-120
No files matched your search
@@ -10,7 +10,7 @@ from homeassistant.exceptions import TemplateError
|
||||
from homeassistant.helpers.config_validation import match_all
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.helpers.event import Event, async_track_template_result
|
||||
from homeassistant.helpers.template import Template
|
||||
from homeassistant.helpers.template import Template, result_as_boolean
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -127,6 +127,11 @@ class TemplateEntity(Entity):
|
||||
"""Template Entity."""
|
||||
self._template_attrs = []
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""No polling needed."""
|
||||
return False
|
||||
|
||||
def add_template_attribute(
|
||||
self,
|
||||
attribute: str,
|
||||
@@ -177,3 +182,42 @@ class TemplateEntity(Entity):
|
||||
for attribute in self._template_attrs:
|
||||
if attribute.async_update:
|
||||
attribute.async_update()
|
||||
|
||||
|
||||
class TemplateEntityWithAvailability(TemplateEntity):
|
||||
"""Entity that uses templates to calculate attributes with an availability template."""
|
||||
|
||||
def __init__(self, availability_template):
|
||||
"""Template Entity."""
|
||||
self._availability_template = availability_template
|
||||
self._available = True
|
||||
super().__init__()
|
||||
|
||||
@callback
|
||||
def _update_available(self, result):
|
||||
if isinstance(result, TemplateError):
|
||||
self._available = True
|
||||
return
|
||||
|
||||
self._available = result_as_boolean(result)
|
||||
|
||||
@callback
|
||||
def _update_state(self, result):
|
||||
if self._availability_template:
|
||||
return
|
||||
|
||||
self._available = not isinstance(result, TemplateError)
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
"""Return if the device is available."""
|
||||
return self._available
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Register callbacks."""
|
||||
if self._availability_template is not None:
|
||||
self.add_template_attribute(
|
||||
"_available", self._availability_template, None, self._update_available
|
||||
)
|
||||
|
||||
await super().async_added_to_hass()
|
||||
Reference in new issue
Block a user