1
mirror of https://github.com/home-assistant/core synced 2024-09-06 10:29:55 +02:00

Make variable entity_id available to value_template for MQTT binary sensor (#19195)

* MQTT binary_sensor: Make variable `entity_id` available to value_template

* Review comments

* Add testcase
This commit is contained in:
emontnemery 2018-12-14 13:00:37 +01:00 committed by Paulus Schoutsen
parent e886576a64
commit b97f0c0261
3 changed files with 33 additions and 5 deletions

View File

@ -135,7 +135,7 @@ class MqttBinarySensor(MqttAttributes, MqttAvailability, MqttDiscoveryUpdate,
value_template = self._config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
payload = value_template.async_render_with_possible_json_value(
payload)
payload, variables={'entity_id': self.entity_id})
if payload == self._config.get(CONF_PAYLOAD_ON):
self._state = True
elif payload == self._config.get(CONF_PAYLOAD_OFF):

View File

@ -149,7 +149,8 @@ class Template:
error_value).result()
def async_render_with_possible_json_value(self, value,
error_value=_SENTINEL):
error_value=_SENTINEL,
variables=None):
"""Render template with value exposed.
If valid JSON will expose value_json too.
@ -159,9 +160,9 @@ class Template:
if self._compiled is None:
self._ensure_compiled()
variables = {
'value': value
}
variables = dict(variables or {})
variables['value'] = value
try:
variables['value_json'] = json.loads(value)
except ValueError:

View File

@ -58,6 +58,33 @@ class TestSensorMQTT(unittest.TestCase):
state = self.hass.states.get('binary_sensor.test')
assert STATE_OFF == state.state
def test_setting_sensor_value_via_mqtt_message_and_template(self):
"""Test the setting of the value via MQTT."""
assert setup_component(self.hass, binary_sensor.DOMAIN, {
binary_sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test-topic',
'payload_on': 'ON',
'payload_off': 'OFF',
'value_template': '{%if is_state(entity_id,\"on\")-%}OFF'
'{%-else-%}ON{%-endif%}'
}
})
state = self.hass.states.get('binary_sensor.test')
assert STATE_OFF == state.state
fire_mqtt_message(self.hass, 'test-topic', '')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert STATE_ON == state.state
fire_mqtt_message(self.hass, 'test-topic', '')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert STATE_OFF == state.state
def test_valid_device_class(self):
"""Test the setting of a valid sensor class."""
assert setup_component(self.hass, binary_sensor.DOMAIN, {