I’m struggling with a template. I want to create a binary sensor that turns on and off as the humidity level rises above and below 60%. I have something that works, and thought I accounted for a “default” situation at startup, but I still get errors
TemplateError('ValueError: Template error: float got invalid input 'unknown' when rendering template '{% if states('sensor.crawlspace_sensor_humidity')|float >= 60 %} on {% elif states('sensor.crawlspace_sensor_humidity')|float < 60 %} off {% else %} unavailable {% endif %}' but no default was specified') while processing template 'Template("{% if states('sensor.crawlspace_sensor_humidity')|float >= 60 %} on {% elif states('sensor.crawlspace_sensor_humidity')|float < 60 %} off {% else %} unavailable {% endif %}")' for attribute '_attr_native_value' in entity 'sensor.humidityhigh'
But to directly answer your question, one way to do that:
{% set state = states('sensor.crawlspace_sensor_humidity') %}
{% if state == 'unknown' %}
unavailable
{% else %}
{{ 'on' if state|float >= 60 else 'off' }}
{% endif %}
This assumes the state of the sensor (other than when the states function returns ‘unknown’) is always a valid float (or more accurately, a valid string that represents a float value.)
Thanks, did not know about threshold, I’ll have to check that out.
For now, the YAML you gave is working great and much cleaner. I beleive the sensor always returns a valid percentage or unavailable (its an Aqara temp/humidity sensor connected through zigbee2mqtt)- I’ll keep an eye on it in case it reports anything strange.
The issue is that the “if” renders the template as the first step to determine the value and if the value is unknown then the render fails and gives you the error.
if you added a default value to the float function(s) then you wouldn’t get the error since the float would default to the default value.
example:
{% if states('sensor.crawlspace_sensor_humidity')|float(0) >= 60 %}
on
{% elif states('sensor.crawlspace_sensor_humidity')|float(0) < 60 %}
off
{% else %}
unavailable
{% endif %}
but then you may get undesired results since the “if” would render to 0 and the “elif” would also render to 0 and since 0 < 60 the binary sensor would be ‘off’. If that is OK then it would work to add the defaults inline as I did above as well.
Thanks, I actually had started with one of your other examples in a different post but it was older before the requirement for the default was added to templating. I can’t find that post exactly now, but the (0) to add the default to the float function was what I was missing from that one.