Add entity_id to mqtt sensor templates (#50773)
* Add entity_id to mqtt sensor * update test commentpull/50863/head
parent
109b08bb57
commit
7c7432a582
|
@ -125,8 +125,11 @@ class MqttSensor(MqttEntity, SensorEntity):
|
|||
|
||||
template = self._config.get(CONF_VALUE_TEMPLATE)
|
||||
if template is not None:
|
||||
variables = {"entity_id": self.entity_id}
|
||||
payload = template.async_render_with_possible_json_value(
|
||||
payload, self._state
|
||||
payload,
|
||||
self._state,
|
||||
variables=variables,
|
||||
)
|
||||
self._state = payload
|
||||
self.async_write_ha_state()
|
||||
|
|
|
@ -640,3 +640,31 @@ async def test_entity_disabled_by_default(hass, mqtt_mock):
|
|||
await help_test_entity_disabled_by_default(
|
||||
hass, mqtt_mock, sensor.DOMAIN, DEFAULT_CONFIG
|
||||
)
|
||||
|
||||
|
||||
async def test_value_template_with_entity_id(hass, mqtt_mock):
|
||||
"""Test the access to attributes in value_template via the entity_id."""
|
||||
assert await async_setup_component(
|
||||
hass,
|
||||
sensor.DOMAIN,
|
||||
{
|
||||
sensor.DOMAIN: {
|
||||
"platform": "mqtt",
|
||||
"name": "test",
|
||||
"state_topic": "test-topic",
|
||||
"unit_of_measurement": "fav unit",
|
||||
"value_template": '\
|
||||
{% if state_attr(entity_id, "friendly_name") == "test" %} \
|
||||
{{ value | int + 1 }} \
|
||||
{% else %} \
|
||||
{{ value }} \
|
||||
{% endif %}',
|
||||
}
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
async_fire_mqtt_message(hass, "test-topic", "100")
|
||||
state = hass.states.get("sensor.test")
|
||||
|
||||
assert state.state == "101"
|
||||
|
|
Loading…
Reference in New Issue