Hi guys!
I am currently struggeling to create a sensor that returns two calculated integer values as attributes.
This is a simplified example code for the sensor:
- sensor:
- name: "Leistungslimit OW"
unit_of_measurement: "W"
state: >
{{ is_state('binary_sensor.gh_ost_erreichbar', 'on') }}
attributes:
ost: >
{% set max = 200 | int %}
{% set min = 100 | int %}
{% set limit1 = max + min %}
{% set limit2 = max - min %}
{{ limit1 }}
west: >
{{ limit2 }}
I am able to access the âostâ attribute with: {{ state_attr('sensor.leistungslimit_ow', 'ost') }}
Unfortunately the âwestâ attribute doesnât return a value.
I assume that variables are only valid inside an attribute and cannot be accessed in another one? Is there any way to pass them through? I want to avoid doing the calculations in both attributes.
I think you need to include all the code in each attribute:
- sensor:
- name: "Leistungslimit OW"
unit_of_measurement: "W"
state: >
{{ is_state('binary_sensor.gh_ost_erreichbar', 'on') }}
attributes:
ost: >
{% set max = 200 | int %}
{% set min = 100 | int %}
{% set limit1 = max + min %}
{{ limit1 }}
west: >
{% set max = 200 | int %}
{% set min = 100 | int %}
{% set limit2 = max - min %}
{{ limit2 }}
I want to calculate the values every ten seconds.
Will it help if I use a trigger-based template to make sure that the values donât change during execution of the attributes?
I have just tested your suggested code (a bit simplified) in the development tools. Unfortunately it seems like the variables are not valid/defined in the attribute block:
The template editor tool does not understand YAML, so testing YAML script variables there will never work without additional Jinja set statements. The method is sound, but you must actually configure the sensor.
I wasnât aware of this limitation, good to know!
After adding the code to my configurartion.yaml it works as expected.
Thatâs exactly what I was looking for.