Hi folks,
Having spent 3 evenings unsuccessfully trying to debug this config issue, I’m hoping you can help.
I have a whole raft of power monitoring switches and have sensors set up for each attribute on each switch, all configured long hand and working correctly. I’ve not been trying to make a template that I can use for each so that I can massively reduce the size of the yaml file.
The sample below is a work in progress towards a being able to fully template, but it’s as far as I’ve got with a working config as a test sensor:
sensor:
- platform: template
sensors:
atest_current:
friendly_name_template: >-
aTest Current
value_template: >-
{% set dev_name = 'switch.sonoff_pow1' %}
{% set dev_attr = 'Current'%}
{%- if state_attr(dev_name, dev_attr) != None %}
{{ state_attr('switch.sonoff_pow1', dev_attr) }}
{% else %}
{{ 99 | float }}
{%- endif %}
unit_of_measurement: 'Amps'
The sample above works and sets the sensor state correctly. The final step I need to complete is to substitute the final string value on the {{ state_attr('switch.sonoff_pow1', dev_attr) }}
call, replacing it with the dev_name
parameter as on the preceding {%- if state_attr(dev_name, dev_attr) != None %}
statement.
The config with that change in place is shown below, however the change appears to cause the {% if } statement to start return false as the sensor starts picking up the dummy ‘99’ value.
sensor:
- platform: template
sensors:
atest_current:
friendly_name_template: >-
aTest Current
value_template: >-
{% set dev_name = 'switch.sonoff_pow1' %}
{% set dev_attr = 'Current'%}
{%- if state_attr(dev_name, dev_attr) != None %}
{{ state_attr(dev_name, dev_attr) }}
{% else %}
{{ 99 | float }}
{%- endif %}
unit_of_measurement: 'Amps'
I’m baffled why it’s not working as it’s based on the official example below:
Can you see what’s wrong?
EDIT: I should have stated originally that the last (broken) version of the config actually works in the Developers Tools Template editor.