Count lights on but with a specific brightness

I have a simple template sensor to check all lights on and display it. But how do I also get it to display the ones that have a specific current brightness, for example 1% ?

Current code for the sensor below:

  - platform: template
        friendly_name: "Lights on:"
        icon_template: mdi:light      
        value_template: >
          {{ states.light |selectattr('state', 'eq', 'on') 
            |list |count }}

You can add another selectattr filter to filter by brightness like this:

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

I don’t have brightness_pct for my lights, so I can’t test if you can replace brightness with brightness_pct

Thanks, that’s one of the variations I actually tried but I get this error (in Template editor):

UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'brightness'

Weird, because it works with me, in developer tools, to test, I have:

{{ states.light | selectattr('state', 'eq', 'on') | list | count }}
{{ states.light | selectattr('state', 'eq', 'on') | selectattr('attributes.brightness', '>=', 50) | list | count }}

And the result, when I turn one light at the minimum brightness is


Yeah, weird. Copied your exact code and still same error. I thought that it could perhaps be because I have some switches made into lights, so I tried to reject those with:

|reject('search', 'switch.tellus_plug|switch.wall| ....

But the error remains:

Shouldn’t you put the reject regex before trying to read attributes?

No, I’d assume not. If I just remove the “new” line below, I get the correct number of lights on.

| selectattr('attributes.brightness', '>=', 50

EDIT: I incorrectly wrote switch instead of light on those entities. But still, same error.

If you remove the count and look at the list here, you’ll probably see some entries that doesn’t have a brightness attribute.

These are the one you have to exclude before trying to read the brightness attribute. Or try to put a default to assume their brightness.

Or select the one with a brightness attribute

{{ states.light | selectattr('state', 'eq', 'on') | selectattr('attributes.brightness', 'defined') | selectattr('attributes.brightness', '>=', 50) | list | count }}

Not sure about that one, trying to help

Yes! That one (also) works! Marking that as the solution.

I did it like this before seeing your answer, which also works but feels more messy.

{{ states.light | selectattr('state', 'eq', 'on') 
|reject('search', 'light.switches_that_were_made_into_lights....')
| selectattr('attributes.brightness', 'eq', 1)
| list | count }}

Thanks for all the help!

1 Like