How to detect how many lights are on in an area?

I’m busys creating my own dashboard and struggling to get something done.
I like to detect in a custom:button-card how many lights are on in a specifick area
something like:

      light: |
        [[[
          if (states["light.ikea_5_lamp_tv"].state == "off")
            return `<ha-icon
              icon="mdi:lightbulb-outline"
              style="width: 15px; height: 15px;">
              </ha-icon>
              <span> uit</span>`
          else 
            return `<ha-icon
              icon="mdi:lightbulb"
              style="width: 15px; height: 15px;">
              </ha-icon>
              <span> ${states['sensor.edward_s21_volume_level_ringer'].state} aan</span>`
        ]]]

in this example → (states[“light.ikea_5_lamp_tv”].state == “off”)
must be code to detect the amount of lights on of a specific area.
I know that I do need to use the attribute.device_class
of light and then check the state.

But I don’t know how to translate this in an if test code
I like to create a result to show like:

Thanks

This sample is very cobbled together from one of my templates for door sensors and a couple of searches here, but reveals that two of the light sets in my kitchen are currently on:

{%- set ns = namespace(lightsensors=[]) -%}
{%- set ns.lightsensors = states.light
  | selectattr('entity_id', 'in', area_entities('Kitchen'))
  | selectattr('state', 'eq', 'on')
  | map (attribute='name') | list -%}
{{ ns.lightsensors | count }}    

Remove the “| count” if you want an array, which you can join if you want a string. I do this to show a list of doors/windows that are unlocked and/or open.

You can add

| selectattr('attributes.brightness', '>=', 128)

For example, to narrow the list to lights that are 50% brightness or higher (assuming like mine yours go to 255).

I would create a sensor

"{{states.light | selectattr('state', 'eq', 'on') | list | count}}"
1 Like

Thanks very much for the answers.
I’m just started 2 weeks ago to create my own dashboard
It is quit more complex then I expected :hushed:
I don’t understand where to create these sensors.
In the configuration or sensor.yaml?
and @myle is this sensor not missing the area?
If I put it in the template tester it shows indeed a figure of all my lights
and @haus it indeed shows trhe amount of lights in my “Woonkamer” if I put that as area.
I only need to know where to create these sensors

EDIT:::
YESS it is working thanks

1 Like