I am having an issue creating a sensor to list all sensors with a battery state lower than a number defined by an input number helper. This code works fine if I put it in the template editor in the Developer Tools section. However if I create a sensor template, the state becomes “unknown” if more than 1 low battery is detected. Works fine if only 1 low battery is detected.
{% set threshold = states('input_number.battery_warning_threshold') %} #<-- this is a string value
{% set lowbatcount = states.sensor
| selectattr('entity_id', 'search', 'battery')
| selectattr('state', 'lessthan', threshold) #<-- this is performing a string comparison
Your template is not performing a numeric comparison but a string comparison.
The threshold variable contains a string not a number. In other words, if the input_number’s value is 50 then threshold contains '50' which is a numeric string but not a number.
The following line is comparing the sensor’s state value, which is a numeric string, to the threshold value which is also a numeric string. Comparing numeric strings doesn’t behave the same way as comparing numbers.
selectattr('state', 'lessthan', threshold)
For example, when comparing the numeric string '9' to the numeric string '85' it’s not less than '85'.