Different speed of counting using template sensor - count lights that are on

My goal is to display text in Dashboard how many lights are on. That is quite easy, but to make it little bit harder I want to count lights used in groups as one light :slight_smile:

My idea was to add to grouped lights new attribute - grouped: “on” and then count all the lights that are on minus all the lights that are grouped. If you have more elegant solutions, I am opened to suggestions.

I have created sensor to do that, but found out it was working, but rather slowly. It wasn’t instantly changed but it took some time to display new value (20 seconds+).

I have divided the sensor into 2:

  1. counting number of lights that are on - easy + instant change of the value
- platform: template
  sensors:
    lights_count_b:
      value_template: >-
        {% set count = states.light  
                  | selectattr('state', 'eq', 'on')
                  | map(attribute='entity_id')
                  | list
                  | count %}
        {{ count }}
  1. counting number of lights that are on, but also having attribute grouped = “on” - this takes 20 seconds + to refresh. I don’t know why.
- platform: template
  sensors:
    lights_count_a:
      value_template: >-
        {% set count = states  
                  | selectattr('domain', 'eq', 'light')
                  | selectattr('state', 'eq', 'on')
                  | selectattr('attributes.grouped', 'eq', 'on')
                  | map(attribute='entity_id')
                  | list 
                  | count %}
        {{ count }}

Can you help me figure this out? Or if you have better solution, please let me know.

See Template – rate limiting updates.

If the template accesses every state on the system, a rate limit of one update per minute is applied. If the template accesses all states under a specific domain, a rate limit of one update per second is applied. If the template only accesses specific states, receives update events for specifically referenced entities, or the homeassistant.update_entity service is used, no rate limit is applied.

I just looked at the 2nd count and I changed the code states to states.light. Now, it’s working OK.

- platform: template
  sensors:
    lights_count_a:
      value_template: >-
        {% set count = states.light
                  | selectattr('state', 'eq', 'on')
                  | selectattr('attributes.grouped', 'eq', 'on')
                  | map(attribute='entity_id')
                  | list 
                  | count %}
        {{ count }}