From 3fc73b27d02bbcbc2b7eb738c612ea05dd35c328 Mon Sep 17 00:00:00 2001 From: Michael Klamminger <6277211+m1ch@users.noreply.github.com> Date: Wed, 19 May 2021 15:09:09 +0200 Subject: [PATCH] Add entity_id to mqtt sensor templates (#17872) --- source/_integrations/sensor.mqtt.markdown | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/source/_integrations/sensor.mqtt.markdown b/source/_integrations/sensor.mqtt.markdown index b2eaeda5e75..c1de8e28308 100644 --- a/source/_integrations/sensor.mqtt.markdown +++ b/source/_integrations/sensor.mqtt.markdown @@ -147,7 +147,7 @@ unit_of_measurement: required: false type: string value_template: - description: "Defines a [template](/docs/configuration/templating/#processing-incoming-data) to extract the value." + description: "Defines a [template](/docs/configuration/templating/#processing-incoming-data) to extract the value. Available variables: `entity_id`. The `entity_id` can be used to reference the entity's attributes." required: false type: template {% endconfiguration %} @@ -206,6 +206,26 @@ sensor: The state and the attributes of the sensor by design do not update in a synchronous manner if they share the same MQTT topic. Temporal mismatches between the state and the attribute data may occur if both the state and the attributes are changed simultaneously by the same MQTT message. An automation that triggers on any state change of the sensor will also trigger both on the change of the state or a change of the attributes. Such automations will be triggered twice if both the state and the attributes change. Please use a [MQTT trigger](/docs/automation/trigger/#mqtt-trigger) and process the JSON in the automation directly via the {% raw %}`{{ trigger.payload_json }}`{% endraw %} [trigger data](/docs/automation/templating/#mqtt) for automations that must synchronously handle multiple JSON values within the same MQTT message. +### Usage of `entity_id` in the template + +The example below shows how a simple filter, that calculates the value by adding 90% of the new value and 10% of the previous value, can be implemented in a template. + +{% raw %} +```yaml +# Example configuration.yaml entry +sensor: + - platform: mqtt + name: "Temp 1" + state_topic: "sensor/temperature" + value_template: |- + {% if states(entity_id) == None %} + {{ value | round(2) }} + {% else %} + {{ value | round(2) * 0.9 + states(entity_id) * 0.1 }} + {% endif %} +``` +{% endraw %} + ### Owntracks battery level sensor If you are using the [OwnTracks](/integrations/owntracks) and enable the reporting of the battery level then you can use an MQTT sensor to keep track of your battery. A regular MQTT message from OwnTracks looks like this: