Device_class search template

I am using a template to get all my sensor from a SimpliSafe integration.
These are 2 snippets of code I am using. Both give me the same error:

UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'device_class'
{%- set search_state = 'on' %}
{%- set search_class = 'window' %}
{%- set ns = namespace(binary_sensors=[]) %}
{%- for binary_sensor in states.binary_sensor 
| selectattr('state','eq', search_state) 
| selectattr('device_class','eq', search_class) %}
    {%- set ns.binary_sensors = ns.binary_sensors + [ binary_sensor.entity_id ] %}
{%- endfor %}
{{ ns.binary_sensors| count }}

{{ expand(states.binary_sensor) 
    | selectattr('device_class', 'search', 'entry') 
    | selectattr('state', 'search', 'off') 
    | rejectattr('object_id', 'search', 'battery') 
    | list | count 

This is a sample of the sensor I am trying to get to:

So I see the device_class. This may not be available as an attribute in all binary_sensors in my setup, but is there a way to get the window entry sensors I am looking for?

I will be using the same for the doors. Which is the same setup with doors as the attributes.

You need to limit it to just entities with a defined device_class:

    {{ states.binary_sensor
    | selectattr('attributes.device_class', 'defined')
    | selectattr('attributes.device_class', 'eq', 'window') 
    | selectattr('state', 'search', 'off') 
    | rejectattr('object_id', 'search', 'battery') 
    | list | count }}
1 Like