Loop over list of contact sensor states

I used to have a notification working that would tell me if I left anything open when my house alarm was ‘arming’. It hasn’t been working for a long time, but at one point a long time ago, it did work. I’d like to get it working again. Can anyone provide feedback on how I can loop over a list of entities and only return the ones with an ‘open’ state?

My old automation was this (I think it used to work because I used to be able to grab ALL entities with an ‘open’ state, but I really would like to be able to specify a select list of entities to get the states from):

- alias: alarm_arming_actions
  initial_state: True
  - platform: state
    entity_id: alarm_control_panel.house
    to: 'arming'
  - service: notify.all_general
      message: >
        House alarm activating, ensure all doors and windows are closed.
        {% for state in states -%}
          {% if state.state == 'open'%}
            {{ state.name }} is open!
          {%- endif -%}
        {% endfor %}

For reference, in another automation, I found that I can trigger on a list of entities by placing them in their own .yaml file and calling it like this:

    - platform: state
      entity_id: !include ../groups_by_file/alarm_trigger_sensor.yaml
      to: 'on'

Is it possible to call that same .yaml file as a list to get the entity states from?

Binary sensors are either ‘on’ or ‘off’… specifying certain device classes will lead to them having specialized UI representations like ‘open’ or ‘closed’, but the actual state is still ‘on’ or ‘off’.

Instead of using your yaml file hack, just use a group. The current preferred method for binary sensors like doors and windows is using the UI, but you can also do it in yaml.

There are probably 30+ threads on this topic on this forum that can be found with a quick search. You can see a few template variations that other users have asked for here.

1 Like

Wow, that’s amazing. I had no idea half of those functions existed in templates. That expand function looks to be especially useful, thank you so much for the help!

For the record, the top search on these forums for my question was actually my post from 4 years ago where I figured out I could use the code I posted above (which no longer works). A lot has changed in that time. I’m not saying there aren’t related posts, but none of them had quite what I was looking for is the problem, or I’m just terrible at knowing the right search terms. Either way, your solution is honestly the most elegant I have seen over the years. So I really appreciate you sharing!

Using the file with a list of entities was the easiest way for me to keep track of what entities I wanted in the group, but you’re right there are far better grouping options nowadays. I will definitely update this to use a group.