frojac
(Frode)
June 14, 2023, 3:58pm
1
Hello all, my first post on the forum!
I’m struggling to code my template to show a default voltage if sensor input is 0 or unavailable, the sensor is giving milliamperes value. Here’s what I have so far in my template.yaml:
- sensor:
- name: "Spenning VVB"
unique_id: 23456765434
unit_of_measurement: "V"
device_class: energy
state_class: measurement
state: >
{% set state1 = states('sensor.vvb_strom') %}
{% if (state1) == 0 %}
230
{% else %}
{{ ((state1|float * 27.2674)/1000 | float ) | round(2) }}
{% endif %}
This seems to give the else statement even when sensor is 0, however I want it to show 230 if the sensor is 0.
I would also like it to show 230 if the sensor is unavailable, however I haven’t figured a way to script it.
If anyone could point me in the right direction it would be much appreciated.
Frode.
tom_l
June 14, 2023, 4:09pm
2
- sensor:
- name: "Spenning VVB"
unique_id: 23456765434
unit_of_measurement: "V"
device_class: voltage ### changed
state_class: measurement
state: >
{% set state1 = states('sensor.vvb_strom')|float(0) %}
{% if state1 == 0 %}
230
{% else %}
{{ ( state1 * 27.2674/1000 ) | round(2) }}
{% endif %}
frojac
(Frode)
June 14, 2023, 4:14pm
3
Thanks tom_l,
I changed device class, however it still reads back “0” if sensor is 0.
frojac
(Frode)
June 14, 2023, 4:31pm
4
Figured it out for returning ‘230’ when ‘0’:
- sensor:
- name: "Spenning VVB"
unique_id: 23456765434
unit_of_measurement: "V"
device_class: voltage ### changed
state_class: measurement
state: >
{% set state1 = states('sensor.vvb_strom')|float(0) %}
{% if (state1, '0') %} ### 2nd change
230
{% else %}
{{ ( state1 * 27.2674/1000 ) | round(2) }}
{% endif %}
Now only the ‘unavaliable’ condition remains.
petro
(Petro)
June 14, 2023, 4:43pm
5
That state isn’t correct. That if statement will always pass, you’ll always get a result of 230. Tom’s template is correct, you should be using that.
frojac
(Frode)
June 14, 2023, 5:02pm
6
Yes, I tested it now, it is now always ‘230’.
My original and Tom’s was giving ‘0’ when sensor is ‘0’, and a wanted floating value based on current from sensor when sensor was >‘0’.
Do you have any suggestion to make it work?
tom_l
June 14, 2023, 5:09pm
7
I also changed the template.
frojac
(Frode)
June 14, 2023, 5:20pm
8
Ahh, thanks, yes, your solution is indeed working, my eyes was too fast.
Thanks for all help, will this also handle if the sensor becomes unavailable?
Tested, it works!
tom_l
June 15, 2023, 12:40am
9
Yes unavailable will also be reported as 0. You can change it to be unavailable if you want to by adding this availability template.
availability: "{{ states('sensor.vvb_strom')|is_number }}"