I created a sensor template that calculates wind chill from my weather station. Wind chill is only calculated if the temp is below 50°. How can I add a line to the code to display “–” or “N/A” if the temp is above 50°?
{% set T = states('sensor.weather_station_temperature') | float %}
{% set W = states('sensor.weather_station_speed') | float %}
{# Formula requires mph and Fahrenheit #}
{% if T <= 50 and W > 3 %}
{{ (35.74 + (0.6215 * T) - (35.75 * (W**0.16)) + (0.4275 * T * (W**0.16))) | round(1) }}
{% else %}
{{ T | round(1) }}
{% endif %}
I’m reading about the availability option now. I’m not seeing how to add a condition to the availability code. I only want the sensor to display of the temperature is below 50°
I don’t think that is possible, the best you can do is have it say: Unavailable
To do that you would need something like this:
- sensor:
- name: "Wind Chill"
unique_id: wind_chill
device_class: temperature
unit_of_measurement: °F
state: >
{% set T = states('sensor.weather_station_temperature') | float %}
{% set W = states('sensor.weather_station_speed') | float %}
{% set WC = (35.74 + (0.6215 * T) - (35.75 * (W**0.16)) + (0.4275 * T * (W**0.16))) | round(1) %}
{% if T <= 50 and W > 3 %}
{{ WC }}
{% else %}
{{ T | round(1) }}
{% endif %}
availability: >
{% set T = states('sensor.weather_station_temperature') | float %}
{{ T < 50.0 }}
Note I added an additional “set” (for WC) since I think it reads a bit better with it.
There is also an option for variables however you can only use them with “trigger” based sensors and thats probably a can of worms not worth opening for this use case.
I do appreciate you teaching a newbie how do things the right way.
So for clarity - yes you should handle the other states properly …
However, I don’t usually worry to much about unavailable sensors:
Battery sensors tend to freeze (last value) instead of showing as unavailable.
I don’t cut power to any of my mains devices, so pretty much the rest of them are online all the time.
I know there is a small window during HA restart where they go into an unknown state, but I am not aware of any situation where not handling unknown/unavailable states has led to one of my automations doing something it shouldn’t.
Frankly the only condition along these lines I do error handle is when I haven’t received an update in some time from a battery sensor (i.e. the battery is flat).
TL;DR - I “get away” with not handling it properly all the time…
PS I did a quick check and I am not going to say it works perfectly (every time - without thought) but unavailable status tends to propagate through templates so it’s often the case that if an upstream sensor goes unavailable downstream sensors also show unavailable even without specifically handling it.