Template sensor - select by icon type

Hi,

I glued some Aqara contact sensors to mouse-traps in my attic so I don’t have to climb up to check on them every day - it’s worked well for there last couple of years.

I am now trying to have a nice status on my dashboard board and wrote the following template based on examples I have found online (thanks to those guys for sharing).

- name: "count of mouse traps"
  state: >
    {{ states.binary_sensor
      | selectattr('attributes.device_class', 'eq', 'door')
      | map(attribute='state')
      | select('eq', 'on')
      | list | count
    }}
  icon: >-
    {% if is_state('sensor.count_of_mouse_traps', '0') %}
      mdi:check-circle
    {% else %}
      mdi:rodent
    {% endif %}

Whilst I only have 2 traps, I like to future-proof things so I don’t have to keep modifying everything every time I add a new sensor. Right now, I only have 2 contact sensors and they are both being used for this purpose. However, I will add some sensors for doors and windows and so the template will no longer work.

I have tried to replace the device_class line as follows to separate the traps from the potential door sensors but I get the error UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'icon'

      | selectattr('attributes.icon', 'eq', 'mdi:rodent')

I am struggling to find documentation that explains properly how to write sensors that use select(), selectattr(), rejectattr(), map(). Can anyone point me in the right direction (domination wise and/or howe to do this).

thanks!

Try this for the mousetrap count

{{ states.binary_sensor
  | selectattr('attributes.icon', 'defined') # it has an icon attribute
  | selectattr('attributes.icon', 'match', 'mdi:rodent') # The icon matches mdi:rodent
  | selectattr('state', 'match', 'on') # The state is on
  | list 
  | count 
}}

And give all your mouse trap binary_sensors the icon

thanks!

It no longer throws up an error, so HA must think my sensors don’t have an icon.

…only they do:

Any ideas? I will remove and re-add them and see what happens.

edit: It works if I use friendly_name so that can always be my backup!
edit: removing and re-adding the icons made no difference.

Sorry, made a typo in my template, it says mdi:redent instead of rodent

1 Like