Add entity_id to mqtt sensor templates (#17872)

This commit is contained in:
Michael Klamminger 2021-05-19 15:09:09 +02:00 committed by GitHub
parent 25180d5f50
commit 3fc73b27d0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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: