Counts the lights on

There are probably better solutions but you can create your own array of devices you want to combine. It’s however something you need to update manually all the time.

I for example use it to only the spots in my bathroom to display how many spots are on. Its a bit the reverse of what you want however as I use it to limit and not count all lights.

{% set bathroomlights = [
              states.light.achter_links,
              states.light.achter_rechts,
              states.light.midden_links,
              states.light.midden_rechts,
              states.light.voor_links,
              states.light.voor_rechts
            ] %}
            {{ bathroomlights | selectattr('state','eq','on') | list | count }}

If that is an option and useful for you, you could change the device_class and change them all to lights. I did that with some contact-sensors classed as ‘door’ while they are on a window.

homeassistant:
  customize:
    binary_sensor.contactsensor_bedroom_contact:
      device_class: "window"

There probably also just is a right code to have two device_classes counted together.

1 Like

Thank you. I have change the device_class.

1 Like

wondering if you could help me…

my browser_mod “lights” are seen as

light.2fa34179_b81a98b7

light.(random signs)

How can I set rejectattr to get rid of them ?

3 Likes

After reading this thread I created the following sensor to count how many lights I have on:

- platform: template
  sensors:
    count_lights_on:
      friendly_name: "# Lights on"
      unit_of_measurement: "on"
      value_template: "{{ states.light | selectattr('state', 'eq', 'on') | rejectattr('attributes.is_hue_group', 'eq', true) | rejectattr('attributes.entity_id', 'defined') | list | count }}"

I would like to modify it so it also count switches that have an entity id that follows the pattern switch.*fan Could someone show me how to modify the template to achieve this? Thanks!

1 Like

In case it helps someone else, this code works:


- platform: template
  sensors:
    count_lights_on:
      friendly_name: "# Lights on"
      unit_of_measurement: "on"
      value_template: >-
         {{ 
          states.switch |
            selectattr('entity_id', 'search', '_fan')  |
            selectattr('state','eq','on') | 
            list | 
            count +
            states.light | 
            selectattr('state', 'eq', 'on') | 
            rejectattr('attributes.entity_id', 'defined') | 
            list | 
            count
         }}
6 Likes

My lights group are still counted twice. I’ve checked “Hide members”. And I have the following code:

- platform: template
  sensors:
    count_lights_on:
      friendly_name: "# Lights on"
      value_template: >-
        {{ 
          states.light |
          selectattr('state', 'eq', 'on') |
          rejectattr('attributes.entity_id', 'defined') |
          list |
          count 
        }}

But apparently this counts the individual lights rather than counting each light group as one. Groups are light.tv_lampa and light.fonsterlampor.

The template you posted selects all light entities that are on and then excludes Light Group entities and reports the quantity.

If you want to count the Light Group entities (that are on) but not their members, you have to identify all the group members and then exclude them from the list of all lights.

Copy-paste the following template into the Template Editor and see if it works the way you want:

      value_template: >- 
        {% set members = states.light
          | selectattr('attributes.entity_id', 'defined')
          | expand | map(attribute='entity_id') | list %}
        {{ states.light | selectattr('state', 'eq', 'on') 
          | map(attribute='entity_id')
          | reject('in', members) | list }}

Thanks! It works great in the template editor, but when I add it in configuration.yaml it seems not to recognize the expand filter? See https://github.com/home-assistant/core/issues/34715

Invalid config for [sensor.template]: invalid template (TemplateAssertionError: No filter named 'expand'.) for dictionary value @ data['sensors']['count_lights_on']['value_template']. Got "{% set members = states.light |\n selectattr('attributes.entity_id', 'defined') |\n expand | \n map(attribute='entity_id') | \n list \n%} {{ \n states.light | \n selectattr('state', 'eq', 'on') |\n map(attribute='entity_id') |\n reject('in', members) | \n list |\n count\n}}". (See ?, line ?).

That’s odd. If the expand filter works in the Template Editor it shouldn’t cause this error when it appears in a Template Sensor: TemplateAssertionError: No filter named 'expand'.

I’ve confirmed that if expand is used as a function then it passes Check Configuration.

value_template: >- 
        {% set members = expand(states.light | selectattr('attributes.entity_id', 'defined'))
          | map(attribute='entity_id') | list %}
        {{ states.light | selectattr('state', 'eq', 'on') 
          | map(attribute='entity_id')
          | reject('in', members) | list }}

EDIT

When the Template Sensor is configured using legacy format, Check Configuration doesn’t accept expand used as a filter (only as a function). However, it the Template Sensor is configured using modern format, Check Configuration accepts expand used either as a function or filter.
Nope. Upon further investigation, expand when used a filter is rejected in either a legacy or modern format Template Sensor. The only place it works as a filter is in the Template Editor.

I’ve reported this unexpected behavior as an Issue in the GitHub Core repo.

1 Like

Thanks a lot! At least the code you provided now works great. :slight_smile:

It’s getting fixed next release, or the release after

1 Like

Is this working as of now?

The code works great in the template section in developer tools, but when I add it to the template sensors in my yaml, the sensor doesn’t show up even after reloading the template entities.

I see that it’s supposed to get fixed in the next release, but that’s already been more than a month ago and I’m wondering if the 2022.10.5 update is supposed to fix that

Thanks!

The pr keeps getting blocked my merge conflicts.

So is it going to get fixed eventually or should I look for alternative template code? Cause right now the code works great in the template section of dev tools, but if there’s no plans to make it work in the HA config.yaml then I need to search for alternative.

Thanks for your help

I have been using this with no problems… I have it in a sensors.yaml file including it in the config file.

# Total Number of Switches on
- platform: template
  sensors:
    total_switch_on:
      unique_id: total_switch
      friendly_name: "Total Switches On"
      value_template: >-
        {{ states.switch 
          | rejectattr('attributes.entity_id', 'defined') 
          | selectattr('state', 'eq', 'on')
          | list | count }}

# Total Lights On
- platform: template
  sensors:
    total_lights:
      unique_id: total_light
      friendly_name: "Total Lights On"
      value_template: >-
        {{ states.light
          |selectattr('state','eq','on')
          |rejectattr('attributes.entity_id','defined')
          |list |count }}
      attribute_templates:
        light_entities: >-
          {% set domain = 'light' %}
          {% set entities = states[domain] | selectattr('state','eq','on') | map(attribute='entity_id') | list %}
          {%- for s in entities -%}
          - {{ s }},
          {%- endfor %}

# Total Sensors On
- platform: template
  sensors:
    total_sensors:
      unique_id: total_sensor
      friendly_name: "Total Sensors On"
      value_template: >-
        {{ states.binary_sensor
          |rejectattr('attributes.entity_id', 'defined')
          |rejectattr('attributes.friendly_name','eq','Remote UI')
          |rejectattr('attributes.icon', 'defined')
          |selectattr('attributes.device_class', 'defined')
          | selectattr('state','eq','on')
          |map(attribute='name') 
          |list|count  }}

Creates sensor entities
total_lights
total_switch
total_sensor

4 Likes

Just use expand as a method instead of a filter, works perfectly fine. You don’t need the PR to use expand.

expand(…)

Instead of

… | expand

will it also be possible to count how many hours the light has been on ?

Hello to all. Thank you for this posts, I’m looking for configure my lights but maybe I’ve not understand how to do.
I’ve some lights in my open_space and other in my kitchen. I want to count thats lights on in two different sensors. I’ve try this code but have two error:

# Lights count
sensor:  
  - platform: template
    sensors:
      lightsoncountopenspace:
        friendly_name: "Luci Accese nell'open Space"
        value_template: >
          {% set reject = [ 'light.hue_go_destra', 'light.hue_go_sinistra', 'light.hue_play_gradient_lightstrip_1', 'light.piantana', 'light.plafoniera_1', 'light.plafoniera_2_2' ] %}
          {{ states.light | rejectattr('object_id', 'in', reject) | selectattr('state','equalto','on')| list | length }}
      lightsoncountcucina:
        friendly_name: "Luci Accese in Cucina"
        value_template: >
          {% set reject = [ 'light.hue_color_candle_1', 'light.light', 'light.snack_strip', 'light.tavolo' ] %}
          {{ states.light | rejectattr('object_id', 'in', reject) | selectattr('state','equalto','on')| list | length }}
     
  1. When light on an open_space light it shows the count on 2 instead of 1
  2. When light on an open_space light it shows the count on 2 also in kitchen lights.

Can anyone help me?
P.s. this is in my configuration.yaml file

use the history stats integration.

change that to entity_id