Counts the lights on

Yes the output is 2, which is correct

So thank you all.

This code is working :slight_smile:

      - name: Lichten Aan Hal
        state: >-
          {{ states.light | selectattr('name', 'in', state_attr('light.hal', 'lights') | list) | selectattr('state', 'eq', 'on') | list | count }}

 {{ expand('group.all_lights')
          | selectattr('state', 'eq', 'on')
          | map(attribute='entity_id')
          | select('search', 'light.*') 
          | list 
          | count
          }}

You might find this intuitive as well. I have groups for all rooms. Works well.

1 Like

I should add a switch entity (swith.light_01) in the count of lights, how can I do?

value_template: "{{ states.light | selectattr('state', 'eq', 'on') | rejectattr('attributes.luci', 'eq', true) | rejectattr('attributes.luci', 'defined') | list | count }}"

value_template: "{{ expand(states.light, 'switch.light_01') | selectattr('state', 'eq', 'on') | rejectattr('attributes.luci', 'eq', true) | rejectattr('attributes.luci', 'defined') | list | count }}"

Trying to find something that shows the switches and lights on
Getting error (<template DomainStates('switch')>, 0) on this one
{{ states.switch, states.lights|selectattr('state','eq','on')|list|length }}

Any ideas?

I use this (in a lovelace card) - but the template code is the same - copes with removing light groups of either HA or Hue flavour, and if you want you can set the exclude list to be specific lights you want to exclude - like light.christmas_tree for example :slight_smile:

{% set exclude = ["light.not_to_be_counted","light.another_not_to_be_counted"] %}
{{ states.light
    | rejectattr('entity_id','in', exclude )
    | selectattr('attributes.is_hue_group','undefined')
    | selectattr('attributes.entity_id', 'undefined')
    | selectattr('state','eq','on')
    | list
    | count
}}

Another approach - just to throw an alternative, an SQL sensor which is updated every minute rather than jinja templates that are I think updated every second by default as they are not referencing the full state table - you can of course set the SQL sensor to not be polled and just use homeassistant.update_sensor in a script or automation just to make it zero load:

select count(s1.entity_id) as on_lights
from states s1
inner join
(
        select max(state_id) as max_id, entity_id, attributes_id from states
        where entity_id like 'light.%'
        group by entity_id
) s2 on s1.state_id = s2.max_id
inner join state_attributes on state_attributes.attributes_id = s2.attributes_id
where state = 'on' and not instr(shared_attrs, 'group') and not instr(shared_attrs, 'entity_id');

Not sure on the relative performance merits of using an SQL sensor v a template sensor?

Someone asked about light count by room earlier in the thread - this may help - you should be able to paste this directly into the developers template section and play with it (the definitions for exclude and room at the top) and see what works best in your setup:

{% set exclude = ["light.not_to_be_counted","light.another_not_to_be_counted"] %}
{% set room = [ "light.grb1", "light.grb2" ] %}
{% set room = "light.lounge" %}

{%- macro breakdown_group(group, exclude) -%}
      {%- if group is string -%}
      {%- set entities = iif(state_attr(group, 'is_hue_group'),
        state_attr(group, 'lights') | map('lower') | map('regex_replace', '^(.*)', 'light.\\1'),
        state_attr(group, 'entity_id') | map('lower'))
        | list -%}
      {%- else -%}
        {%- set entities = group | map('lower') -%}
      {%- endif -%}
      {{- iif(exclude is defined, entities | reject('in', exclude), entities) | list -}}
{%- endmacro -%}

{%- set room_lights = breakdown_group(room, exclude) -%}
{%- set light_count = states.light
    | selectattr('entity_id','in',room_lights)
    | selectattr('attributes.is_hue_group','undefined')
    | selectattr('attributes.entity_id', 'undefined')
    | selectattr('state','eq','on')
    | map(attribute='entity_id')
    | list
    | count
-%}
{{ light_count }}
1 Like

Hey,
I’m trying to make something that looks like a SWAKES Sensor counter, but I can’t figure it out by myself.
image

I want to count the number of entities within a group that I have and show also how many of them are in the ‘On’ state
For example:
I have group.cameras with 3 entities of my cameras, 2 of them are ‘On’ state and 1 is ‘Off’ state
So I want to show up in my dashboard 3/2 (3 is the total number of entities within the group, and 2 is the number of ‘On’ devices within the group).

How do I do that? I want to count my lights and some devices I have.

Thanks for helping me out!

*Note that I have tried the following method:
Dashboard card

          - type: custom:template-card
            entity: sensor.ac_counter
            name: Cameras

The sensor declaration in 'templates.yaml’

- sensor:
    - name: ac_counter
      state: >-
        {{ expand(state_attr('group.ac_counter', 'entity_id') )
          | selectattr('state', 'eq', 'on') 
          | list 
          | count
        }}

The group declaration in groups.yaml

ac_counter:
  name: Test
  entities:
    - climate.ofir_a_c
    - switch.switcher_v4_yair
    - media_player.mibox4_2
    - binary_sensor.zigbee2mqtt_running

Hi all
Can some one help me with this code

{{ expand('light.b1', 'light.b2', 
          'light.b3', 'light.k1', 
          'light.k2', 'light.l1', 'light.l2', 'light.l3', 'light.stairs_down_switch_1', 'light.stairs_down_switch_2', 'light.stairs_down_switch_3') 
   | selectattr('state', 'eq', 'on')
   | map(attribute='entity_id')
   | map('area_name')
   | select('eq', 'Kitchen')
   | list | count }}
{{ states.light | selectattr('state', 'eq', 'on')
   | selectattr('state', 'eq', 'on')
   | map(attribute='entity_id')
   | map('area_name')
   | select('eq', 'Kitchen')
   | list }}

Instead output be
"2
[‘Kitchen’, ‘Kitchen’]
"
want to be friendly name like use in Lovelace
" "2
[‘K1’, ‘K2’]
"
Thanks in advance

{% set entities = ['light.b1', 'light.b2', 
          'light.b3', 'light.k1', 
          'light.k2', 'light.l1', 'light.l2', 'light.l3', 'light.stairs_down_switch_1', 'light.stairs_down_switch_2', 'light.stairs_down_switch_3'] %}
{% set on = expand(area_entities('Kitchen'))
              | selectattr('entity_id', 'in', entities) 
              | selectattr('state','eq','on') | list %}
{{ on | count }}
{{ on | map(attribute='name') | list }}
1 Like

hi petro, mind helping me in post 188 here?
I’m really stuck and can’t figure it out by myself.

thanks a lot!

None of the above examples were perfect in my case so I share what was my solution. If I missunderstood something please correct me.

Background: I’m using IKEA tradfri bulbs and zigbee switches to switch the light, only when I want to change the brightness / color temp then I configure the bulbs. For the sake of convenience I organized the bulbs in groups.
Problem:
The common | rejectattr('attributes.entity_id', 'defined') statement is not filtering out my groups nor my bulbs. I guess because I’m using ZHA groups and in these groups there is no entity_id attribute. It neither filters out my bulbs so I ended up counting a lot more light then I wanted :slight_smile:
Example:

min_color_temp_kelvin: 2202
max_color_temp_kelvin: 4000
min_mireds: 250
max_mireds: 454
supported_color_modes:
  - color_temp
  - xy
color_mode: color_temp
brightness: 252
color_temp_kelvin: 2702
color_temp: 370
hs_color:
  - 28.391
  - 65.659
rgb_color:
  - 255
  - 166
  - 87
xy_color:
  - 0.526
  - 0.387
off_with_transition: false
off_brightness: null
friendly_name: dresden elektronik ConBee II Bulb.feriroom_bulbs_zha_group_0x0002
supported_features: 40

Solution:
I had to find an attribute which exist in the ZHA groups and in my bulbs but not in my switches:
Switch attributes:

supported_color_modes:
  - onoff
off_with_transition: false
off_brightness: null
friendly_name: Kitchen.zbmini.switch Light
supported_features: 8

Sidenote: first I wanted to use supported_color_modes and separate by the value of this attribute, but this is not a real attribute DO NOT waste your time with this :wink:

Solution:
I ended up using the min_mireds attribute to filter out the groups and bulbs because its a common attribute for bulbs and is not populated for switches.

{{ 
states.light
              | rejectattr('attributes.min_mireds', 'defined')
              | selectattr('state', 'eq', 'on')
              | list
              | count
}}

I hope this might help someone.

Got to be an easier way to show just switches and light on?

It’s states.light :slight_smile:


{{ expand(states.switch, states.light)
|selectattr('state', 'eq', 'on') |list |count }}

Hello,

I’m trying to create an entity to count the lights that are on. Based on what I’ve read above, I’ve created the following yaml in the sensors.yaml file. However, the entity does not show up. What am I doing wrong?

- platform: template
  sensors:
    current_lights_on:
      friendly_name: Lichten aan op dit moment
      unit_of_measurement: "on"
      value_template: >
        {% set lights = [
        'states.light.woonkamer',
        'states.light.slaapkamer',
        ] %}
        "{{ expand(lights) | selectattr('states','eq','on') | list | count }}"

Cheers,

Ruben

Remove the double-quotes from the last line.
Change the word states to state.
Just use the entity_ids directly.

- platform: template
  sensors:
    current_lights_on:
      friendly_name: Lichten aan op dit moment
      unit_of_measurement: "on"
      value_template: >
        {% set lights = [
        'light.woonkamer',
        'light.slaapkamer'
        ] %}
        {{ expand(lights) | selectattr('state','eq','on') | list | count }}

Thanks for your reply! I did what you said, but the entity does not show up in the entities list.

What could be the problem here?

PS: I ‘manually’ added the sensors.yaml file by going into configuration.yaml and writing:

sensor: !include sensors.yaml 

Then I proceeded by creating a new file called sensors.yaml

Was this the correct way? (I restarted HA afterwards)

Check the log for reported errors.

No errors found, but I wrote the code from scratch, restarted the system and the entity showed up in the list. Thanks for your help!

Hy everyone

I am quite confused with this behavior by counting 2 light groups.
When I am executing the following code in the jinja2 engine the sum up is correctly. But in the template sensor (code itself), it seems that home assistant is unable to parse it (not presente in my entity list).

{{  expand(state_attr('light.bureau', 'entity_id') )
| expand(state_attr('light.sejour', 'entity_id') )
| selectattr('state','eq','on') | list | count }}

I add a workaround by sumup the 2 groupe separatelly, but the first scenario would have be proper and factorized


{{  expand(state_attr('light.bureau', 'entity_id') )
| selectattr('state','eq','on') | list | count 
+  expand(state_attr('light.sejour', 'entity_id') )
| selectattr('state','eq','on') | list | count }}

If you have any reflexion to share… Thanx :wink: