it’s not possible using select_attr because it doesn’t have a test to check parts of a string. selectattr is all or nothing. Well… I lied, there is a way to do it for the front of a string only. It’s painful…
That would check to see if the first part of your entity_id starts with foo. But that many generators would be a hog. Better off just using a for loop.
{% set ns = namespace(battery=[]) %}
{% for s in states.sensor if 'battery_level' in s.entity_id %}
{% set ns.battery = ns.battery + [ s ] %}
{% endfor %}
{{ ns.battery | map(attribute='name') | join(', ') }}
If you wish to use that to create a “battery alert” sensor, that indicates how many devices currently have low battery levels, there’s a recent thread about that very same subject here (same as Troon’s link).
For example, this will report how many sensors (whose entity name contains ‘battery_level’) have levels below 50. The names of the corresponding sensors are contained in an attribute called battery_low.
sensor:
- platform: template
sensors:
battery_alert:
entity_id: sensor.date
value_template: >
{% set ns = namespace(below=[]) %}
{% for s in states.sensor
if 'battery_level' in s.entity_id and s.state != 'unknown' and s.state|int < 50 %}
{% set ns.below = ns.below + [ s ] %}
{% endfor %}
{{ ns.below | count }}
attribute_templates:
battery_low: >
{% set ns = namespace(below=[]) %}
{% for s in states.sensor
if 'battery_level' in s.entity_id and s.state != 'unknown' and s.state|int < 50 %}
{% set ns.below = ns.below + [ s.name ~ ' (' ~ s.state ~ '%)'] %}
{% endfor %}
{{ ns.below | join(', ') }}
Was searching like crazy (initially for checking the end of a string (friendly_name or entity_id) with string$ which never worked, while using *string$ gave an error - using .*string$ finally works - seems like * needs . as kind of an escape character)
That’s an interesting interpretation but the period doesn’t serve as an escape character.
The match test accepts a regex pattern (REGular EXpression) so the period has special meaning. It serves as a wildcard character to indicate “match any character”. The asterisk following the period serves to “match zero or more of the preceding character”. Therefore the combination of period and asterisk means “match zero or more characters of any kind”.
hi, I would like to display all device with low battery level. The following obviously does not work because state is not numeric. Could you please show me how to make it work?
{{ states.sensor
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'battery')
| selectattr('state', 'lt', 25) <- this will not work
| map(attribute='attributes.friendly_name' )
| list }}
Go to the search bar, type “battery level template”, hit the Enter key… there are multiple ways to do this depending on exactly what you need as your output.