Binary Sensor Template: Add icon_template and entity_picture_template support (#12158)
* Binary Sensor Template: Add icon_template and entity_picture_template support * fix white space * Added else logging and return state
This commit is contained in:
parent
323fe87b57
commit
4f0776de13
2 changed files with 121 additions and 7 deletions
|
@ -15,6 +15,7 @@ from homeassistant.components.binary_sensor import (
|
||||||
DEVICE_CLASSES_SCHEMA)
|
DEVICE_CLASSES_SCHEMA)
|
||||||
from homeassistant.const import (
|
from homeassistant.const import (
|
||||||
ATTR_FRIENDLY_NAME, ATTR_ENTITY_ID, CONF_VALUE_TEMPLATE,
|
ATTR_FRIENDLY_NAME, ATTR_ENTITY_ID, CONF_VALUE_TEMPLATE,
|
||||||
|
CONF_ICON_TEMPLATE, CONF_ENTITY_PICTURE_TEMPLATE,
|
||||||
CONF_SENSORS, CONF_DEVICE_CLASS, EVENT_HOMEASSISTANT_START)
|
CONF_SENSORS, CONF_DEVICE_CLASS, EVENT_HOMEASSISTANT_START)
|
||||||
from homeassistant.exceptions import TemplateError
|
from homeassistant.exceptions import TemplateError
|
||||||
import homeassistant.helpers.config_validation as cv
|
import homeassistant.helpers.config_validation as cv
|
||||||
|
@ -29,6 +30,8 @@ CONF_DELAY_OFF = 'delay_off'
|
||||||
|
|
||||||
SENSOR_SCHEMA = vol.Schema({
|
SENSOR_SCHEMA = vol.Schema({
|
||||||
vol.Required(CONF_VALUE_TEMPLATE): cv.template,
|
vol.Required(CONF_VALUE_TEMPLATE): cv.template,
|
||||||
|
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
|
||||||
|
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
|
||||||
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
|
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
|
||||||
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
|
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
|
||||||
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
|
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
|
||||||
|
@ -55,6 +58,9 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
|
||||||
|
|
||||||
for device, device_config in config[CONF_SENSORS].items():
|
for device, device_config in config[CONF_SENSORS].items():
|
||||||
value_template = device_config[CONF_VALUE_TEMPLATE]
|
value_template = device_config[CONF_VALUE_TEMPLATE]
|
||||||
|
icon_template = device_config.get(CONF_ICON_TEMPLATE)
|
||||||
|
entity_picture_template = device_config.get(
|
||||||
|
CONF_ENTITY_PICTURE_TEMPLATE)
|
||||||
entity_ids = (device_config.get(ATTR_ENTITY_ID) or
|
entity_ids = (device_config.get(ATTR_ENTITY_ID) or
|
||||||
value_template.extract_entities())
|
value_template.extract_entities())
|
||||||
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
|
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
|
||||||
|
@ -65,10 +71,17 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
|
||||||
if value_template is not None:
|
if value_template is not None:
|
||||||
value_template.hass = hass
|
value_template.hass = hass
|
||||||
|
|
||||||
|
if icon_template is not None:
|
||||||
|
icon_template.hass = hass
|
||||||
|
|
||||||
|
if entity_picture_template is not None:
|
||||||
|
entity_picture_template.hass = hass
|
||||||
|
|
||||||
sensors.append(
|
sensors.append(
|
||||||
BinarySensorTemplate(
|
BinarySensorTemplate(
|
||||||
hass, device, friendly_name, device_class, value_template,
|
hass, device, friendly_name, device_class, value_template,
|
||||||
entity_ids, delay_on, delay_off)
|
icon_template, entity_picture_template, entity_ids,
|
||||||
|
delay_on, delay_off)
|
||||||
)
|
)
|
||||||
if not sensors:
|
if not sensors:
|
||||||
_LOGGER.error("No sensors added")
|
_LOGGER.error("No sensors added")
|
||||||
|
@ -82,7 +95,8 @@ class BinarySensorTemplate(BinarySensorDevice):
|
||||||
"""A virtual binary sensor that triggers from another sensor."""
|
"""A virtual binary sensor that triggers from another sensor."""
|
||||||
|
|
||||||
def __init__(self, hass, device, friendly_name, device_class,
|
def __init__(self, hass, device, friendly_name, device_class,
|
||||||
value_template, entity_ids, delay_on, delay_off):
|
value_template, icon_template, entity_picture_template,
|
||||||
|
entity_ids, delay_on, delay_off):
|
||||||
"""Initialize the Template binary sensor."""
|
"""Initialize the Template binary sensor."""
|
||||||
self.hass = hass
|
self.hass = hass
|
||||||
self.entity_id = async_generate_entity_id(
|
self.entity_id = async_generate_entity_id(
|
||||||
|
@ -91,6 +105,10 @@ class BinarySensorTemplate(BinarySensorDevice):
|
||||||
self._device_class = device_class
|
self._device_class = device_class
|
||||||
self._template = value_template
|
self._template = value_template
|
||||||
self._state = None
|
self._state = None
|
||||||
|
self._icon_template = icon_template
|
||||||
|
self._entity_picture_template = entity_picture_template
|
||||||
|
self._icon = None
|
||||||
|
self._entity_picture = None
|
||||||
self._entities = entity_ids
|
self._entities = entity_ids
|
||||||
self._delay_on = delay_on
|
self._delay_on = delay_on
|
||||||
self._delay_off = delay_off
|
self._delay_off = delay_off
|
||||||
|
@ -119,6 +137,16 @@ class BinarySensorTemplate(BinarySensorDevice):
|
||||||
"""Return the name of the sensor."""
|
"""Return the name of the sensor."""
|
||||||
return self._name
|
return self._name
|
||||||
|
|
||||||
|
@property
|
||||||
|
def icon(self):
|
||||||
|
"""Return the icon to use in the frontend, if any."""
|
||||||
|
return self._icon
|
||||||
|
|
||||||
|
@property
|
||||||
|
def entity_picture(self):
|
||||||
|
"""Return the entity_picture to use in the frontend, if any."""
|
||||||
|
return self._entity_picture
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_on(self):
|
def is_on(self):
|
||||||
"""Return true if sensor is on."""
|
"""Return true if sensor is on."""
|
||||||
|
@ -137,8 +165,9 @@ class BinarySensorTemplate(BinarySensorDevice):
|
||||||
@callback
|
@callback
|
||||||
def _async_render(self):
|
def _async_render(self):
|
||||||
"""Get the state of template."""
|
"""Get the state of template."""
|
||||||
|
state = None
|
||||||
try:
|
try:
|
||||||
return self._template.async_render().lower() == 'true'
|
state = (self._template.async_render().lower() == 'true')
|
||||||
except TemplateError as ex:
|
except TemplateError as ex:
|
||||||
if ex.args and ex.args[0].startswith(
|
if ex.args and ex.args[0].startswith(
|
||||||
"UndefinedError: 'None' has no attribute"):
|
"UndefinedError: 'None' has no attribute"):
|
||||||
|
@ -148,6 +177,29 @@ class BinarySensorTemplate(BinarySensorDevice):
|
||||||
return
|
return
|
||||||
_LOGGER.error("Could not render template %s: %s", self._name, ex)
|
_LOGGER.error("Could not render template %s: %s", self._name, ex)
|
||||||
|
|
||||||
|
for property_name, template in (
|
||||||
|
('_icon', self._icon_template),
|
||||||
|
('_entity_picture', self._entity_picture_template)):
|
||||||
|
if template is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
setattr(self, property_name, template.async_render())
|
||||||
|
except TemplateError as ex:
|
||||||
|
friendly_property_name = property_name[1:].replace('_', ' ')
|
||||||
|
if ex.args and ex.args[0].startswith(
|
||||||
|
"UndefinedError: 'None' has no attribute"):
|
||||||
|
# Common during HA startup - so just a warning
|
||||||
|
_LOGGER.warning('Could not render %s template %s,'
|
||||||
|
' the state is unknown.',
|
||||||
|
friendly_property_name, self._name)
|
||||||
|
else:
|
||||||
|
_LOGGER.error('Could not render %s template %s: %s',
|
||||||
|
friendly_property_name, self._name, ex)
|
||||||
|
return state
|
||||||
|
|
||||||
|
return state
|
||||||
|
|
||||||
@callback
|
@callback
|
||||||
def async_check_state(self):
|
def async_check_state(self):
|
||||||
"""Update the state from the template."""
|
"""Update the state from the template."""
|
||||||
|
|
|
@ -98,13 +98,75 @@ class TestBinarySensorTemplate(unittest.TestCase):
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
def test_icon_template(self):
|
||||||
|
"""Test icon template."""
|
||||||
|
with assert_setup_component(1):
|
||||||
|
assert setup.setup_component(self.hass, 'binary_sensor', {
|
||||||
|
'binary_sensor': {
|
||||||
|
'platform': 'template',
|
||||||
|
'sensors': {
|
||||||
|
'test_template_sensor': {
|
||||||
|
'value_template': "State",
|
||||||
|
'icon_template':
|
||||||
|
"{% if "
|
||||||
|
"states.binary_sensor.test_state.state == "
|
||||||
|
"'Works' %}"
|
||||||
|
"mdi:check"
|
||||||
|
"{% endif %}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
self.hass.start()
|
||||||
|
self.hass.block_till_done()
|
||||||
|
|
||||||
|
state = self.hass.states.get('binary_sensor.test_template_sensor')
|
||||||
|
assert state.attributes.get('icon') == ''
|
||||||
|
|
||||||
|
self.hass.states.set('binary_sensor.test_state', 'Works')
|
||||||
|
self.hass.block_till_done()
|
||||||
|
state = self.hass.states.get('binary_sensor.test_template_sensor')
|
||||||
|
assert state.attributes['icon'] == 'mdi:check'
|
||||||
|
|
||||||
|
def test_entity_picture_template(self):
|
||||||
|
"""Test entity_picture template."""
|
||||||
|
with assert_setup_component(1):
|
||||||
|
assert setup.setup_component(self.hass, 'binary_sensor', {
|
||||||
|
'binary_sensor': {
|
||||||
|
'platform': 'template',
|
||||||
|
'sensors': {
|
||||||
|
'test_template_sensor': {
|
||||||
|
'value_template': "State",
|
||||||
|
'entity_picture_template':
|
||||||
|
"{% if "
|
||||||
|
"states.binary_sensor.test_state.state == "
|
||||||
|
"'Works' %}"
|
||||||
|
"/local/sensor.png"
|
||||||
|
"{% endif %}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
self.hass.start()
|
||||||
|
self.hass.block_till_done()
|
||||||
|
|
||||||
|
state = self.hass.states.get('binary_sensor.test_template_sensor')
|
||||||
|
assert state.attributes.get('entity_picture') == ''
|
||||||
|
|
||||||
|
self.hass.states.set('binary_sensor.test_state', 'Works')
|
||||||
|
self.hass.block_till_done()
|
||||||
|
state = self.hass.states.get('binary_sensor.test_template_sensor')
|
||||||
|
assert state.attributes['entity_picture'] == '/local/sensor.png'
|
||||||
|
|
||||||
def test_attributes(self):
|
def test_attributes(self):
|
||||||
""""Test the attributes."""
|
""""Test the attributes."""
|
||||||
vs = run_callback_threadsafe(
|
vs = run_callback_threadsafe(
|
||||||
self.hass.loop, template.BinarySensorTemplate,
|
self.hass.loop, template.BinarySensorTemplate,
|
||||||
self.hass, 'parent', 'Parent', 'motion',
|
self.hass, 'parent', 'Parent', 'motion',
|
||||||
template_hlpr.Template('{{ 1 > 1 }}', self.hass), MATCH_ALL,
|
template_hlpr.Template('{{ 1 > 1 }}', self.hass),
|
||||||
None, None
|
None, None, MATCH_ALL, None, None
|
||||||
).result()
|
).result()
|
||||||
self.assertFalse(vs.should_poll)
|
self.assertFalse(vs.should_poll)
|
||||||
self.assertEqual('motion', vs.device_class)
|
self.assertEqual('motion', vs.device_class)
|
||||||
|
@ -156,8 +218,8 @@ class TestBinarySensorTemplate(unittest.TestCase):
|
||||||
vs = run_callback_threadsafe(
|
vs = run_callback_threadsafe(
|
||||||
self.hass.loop, template.BinarySensorTemplate,
|
self.hass.loop, template.BinarySensorTemplate,
|
||||||
self.hass, 'parent', 'Parent', 'motion',
|
self.hass, 'parent', 'Parent', 'motion',
|
||||||
template_hlpr.Template('{{ 1 > 1 }}', self.hass), MATCH_ALL,
|
template_hlpr.Template('{{ 1 > 1 }}', self.hass),
|
||||||
None, None
|
None, None, MATCH_ALL, None, None
|
||||||
).result()
|
).result()
|
||||||
mock_render.side_effect = TemplateError('foo')
|
mock_render.side_effect = TemplateError('foo')
|
||||||
run_callback_threadsafe(self.hass.loop, vs.async_check_state).result()
|
run_callback_threadsafe(self.hass.loop, vs.async_check_state).result()
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue