Help with a template to count all the lights on

Hello Everyone,

Thank you in advance to everyone who keeps on helping others here.

Currently, i have two types of templates:

Template-1: (This counts all the lights that are in on state in my home)

  sensors:
    lights_on_counter:
      friendly_name: Lights on counter
      value_template: >-
        {{ states.light
              |rejectattr('attributes.entity_id', 'defined')
              |selectattr('state', 'eq', 'on')
              |list
              |count
        }}
      icon_template: mdi:lightbulb-group

Template-2: (This counts only the lights inside the template)

  - sensor:
      - name: "lights on"
        unique_id: lights_on
        icon: mdi:lightbulb-on
        state: >
          {% set lights = [
              states('light.office_1'),
              states('light.office_2'),
              states('light.office_3'),
              states('light.office_4'),
              ] %}
          {{ lights | select('eq', 'on') | list | count }}

Can someone please help me create a template where I can get a number for all the lights that are ‘on’ but exclude a few light entities?

Moved. Please read the topic descriptions. This is not a community guide.

template:
  - sensor:
      - name: Lights on counter
        state: >-
          {% set exclusions = ['light.office_1', 'light.office_2', 'light.office_3'] %}
          {{ states.light
            | rejectattr('attributes.entity_id', 'defined')
            | rejectattr('entity_id', 'in', exclusions)
            | selectattr('state', 'eq', 'on') | list | count }}
        icon: mdi:lightbulb-group
2 Likes

Thank you so much, this worked perfectly

1 Like

Thanks for this, super helpful. Is there a way to use wildcards in the exclusion list e.g light.ld2410_*

{{ states.light
  | rejectattr('attributes.entity_id', 'defined')
  | rejectattr('object_id', 'search', 'ld2410_*')
  | selectattr('state', 'eq', 'on')
  | list | count }}
1 Like

Wow, that’s awesome. Thank you so much.

It seems there is a limit to the reject list? This works

{{ states.light
  | rejectattr('attributes.entity_id', 'defined')
  | rejectattr('object_id', 'search', 'ld2410_*', 'wled_notifier_*')
  | selectattr('state', 'eq', 'on')
  | list | count }}

But this does not citing `TypeError: regex_search() takes from 1 to 3 positional arguments but 4 were given`

{{ states.light
  | rejectattr('attributes.entity_id', 'defined')
  | rejectattr('object_id', 'search', 'ld2410_*', 'wled_notifier_*', 'tab8_ultra_screen')
  | selectattr('state', 'eq', 'on')
  | list | count }}

I suggest you review this section of the documentation.

You can’t simply tack on additional arguments to the search function; that’s not how it works.

It accepts one regex pattern. Regex is a powerful pattern-matching language.

rejectattr('object_id', 'search', '(ld2410_*|wled_notifier_*|tab8_ultra_screen)')
3 Likes