Filtering and counting entities in state by area - Jinja templates in front end?

I believe I have a means for you to create multiple Template Binary Sensors, one per area, with the least amount of effort. It employs this.name, as mentioned in my previous post, plus the use of YAML anchors and aliases.

The following configuration creates four Template Binary Sensors. The second through fourth sensors share the same configuration as the first except they have their own unique name option. Any change you make to the first one’s options or templates are inherited by the other three sensors.

template:
  - binary_sensor:
      - name: Area Family Room
        <<: &area_info
          state: "{{ area_entities(this.name[5:-5]) | select('match', 'light') | select('is_state', 'on') | list | count > 0 }}"
          attributes:
            lights_count: "{{ area_entities(this.name[5:-5]) | select('match', 'light') | list | count }}"
            lights_on: "{{ area_entities(this.name[5:-5]) | select('match', 'light') | select('is_state', 'on') | list | count }}"
            shades_count: "{{ area_entities(this.name[5:-5]) | select('match', 'cover') | list | count }}"
            shades_open: "{{ area_entities(this.name[5:-5]) | select('match', 'cover') | select('is_state', 'open') | list | count }}"

      - name: Area Dining Room
        <<: *area_info
      - name: Area Living Room
        <<: *area_info
      - name: Area Kitchen Room
        <<: *area_info

The only remaining task is to adopt a uniform naming convention for the sensors so that it’s easy to consistently extract the sensor’s area from its name. The example above assumes the name is always three words in the format “Area TheAreaName Room” where “TheAreaName” is the actual area name. Obviously the easiest format would be to simply set the sensor’s name to the area’s name without additional words.

5 Likes