Having trouble filtering by attribute

Ok so I already have long-working template sensors filtering battery zigbee devices, which has not sent any new information by last_seen attribute. I will not send the whole sensor here, because it’s not the point, but this is the short part I am having trouble with now:

{% set variable = namespace(value = {}) %}
{% for entity in states.sensor if state_attr(entity.entity_id, 'last_seen')
  and is_state_attr(entity.entity_id, 'device_class', 'battery') %}
{{ entity.name }}
{% endfor %}

The code above is part of perfectly working zigbee sensor code, showing me all battery zigbee sensors 1 by 1

Now I am trying to do the same with bluetooth SwitchBot sensors. They don’t have last_seen parameter, but all switchbot devices in HA have last_run_success attribute, and even if it’s null, because it surves no purpose for sensors, only for the actianoble devices, this is a perfect option to filter only SwitchBot sensors from any other entities in HA, because last_run_success is exclusive to their integration.

My idea was to just use last_updated on all their sensors, and get not perfect timing of the last time device sent something, but at least a pretty good estimate. But here’s the problem- filtering by using this code (only last_run_success changed instead of last_seen) i get an empty list, as of no sensors in HA has this attribute.

{% set variable = namespace(value = {}) %}
{% for entity in states.sensor if state_attr(entity.entity_id, 'last_run_success')
  and is_state_attr(entity.entity_id, 'device_class', 'battery') %}
{{ entity.name }}
{% endfor %}

What am I doing wrong here? Thanks in advance!

{{ states.sensor
  | selectattr('attributes.last_run_success', 'defined')
  | selectattr('attributes.device_class', 'defined')
  | selectattr('attributes.device_class', 'eq', 'battery')
  | map(attribute='name') | list | join('\n') }}
1 Like