Display number of lights turned on i a group

Hi,

Anyone now how to display how many lights in a group that are turned on?
Either a template sensor or preferably embedded in a custom:button-card under label or custom_varible.

- type: custom:button-card
  template: device_button
  entity: group.livingroom_lights
  name: Lampor
  label: >
       [[[ *code for displaying number of lights turned on* ]]]

Here, 2nd example.
It’s Jinja so you have at least 2 options - create a template sensor and use wherever you need it or rewrite it in JS.
Hope it helps.

1 Like

Thank you for your awnser but that example gives me a list of the lights. I just want to know how many. 1,2,3 and so on.
Also the example list all lights, i just want to count the lights that are in a group.

I am really bad at these codes so all help is much appreciated.

Presumably adding " | count " or " | length " will get you quantity rather than a list, per https://jinja.palletsprojects.com/en/2.11.x/templates/#list-of-builtin-filters

1 Like

You’re lazy :wink:
First of all, read some docs.
And here I can see exactly the answer: “This template counts all entities that have a specific state. e.g. count all lights that are on.”

{% set domain = 'light' %}
{% set state = 'on' %}
{% set count = states[domain] | selectattr('state','eq', state) | map(attribute='entity_id') | list | count %}

Call me whatever you want, I still need help.

That code gives me nothing, unknown.

This on the other hand gives me total lights that are turned on. But I can not figure out how to change it to only count the lights in a specific entity group.

{{ states.light|selectattr("state", "equalto", "on")|list|length }}

Sorry about that.
Try this

{% set ns = namespace(res=0) %}
{% for light in state_attr('group.livingroom_lights', 'entity_id') if is_state(light, 'on') %}
  {% set ns.res = ns.res + 1 %}
{%endfor%}
{{ ns.res }}
1 Like

No worries. :slight_smile:

Thank you for the code, that worked like a charm, well after i changed ‘o’ to ‘on’. :wink:

1 Like

yeah, was switching between on and off while testing :wink:
here’s the source

1 Like
  • type: ‘custom:button-card’
    template: device_button
    entity: group.seminterrato
    name: Seminterrato
    label: > [[[{% set ns = namespace(res=0) %}
    {% for light in state_attr(‘group.seminterrato’, ‘entity_id’) if is_state(light, ‘on’) %}
    {% set ns.res = ns.res + 1 %}
    {%endfor%}
    {{ ns.res }}]]]

Is OK?