Counting entities that are have their state as 'on'

I am trying to create a simple helper to count the number of BG sockets that have the state ‘on’. These use the Broadlink integration and so I am trying to use the function

{% set blOn = integration_entities('broadlink') 
  | select('is_state', 'on')
%}

I am testing this with the Developer Tools in the following:-

*******************************************************
Broadlink Entities
{% set blOn = integration_entities('broadlink') 
  | select('is_state', 'on')
%}

Broadlink On
{% for e2 in blOn %}
  {{ e2 }} - {{ states( e2 ) }}
{% else %}
  No Broadlink entities are currently on.
{% endfor %}

The Result shows:-

Blockquote


Broadlink Entities

Broadlink On
switch.dinning_socket_s1 - on
switch.kitchen_socket_s1 - on
switch.kitchen_socket_s2 - on
switch.porch_socket_s2 - on

Result type: string

This template listens for the following state changed events:

  • Entity: switch.dinning_socket_s1
  • Entity: switch.dinning_socket_s2
  • Entity: switch.kitchen_socket_s1
  • Entity: switch.kitchen_socket_s2
  • Entity: switch.porch_socket_s1
  • Entity: switch.porch_socket_s2
  • Entity: switch.socket_s1
  • Entity: switch.socket_s2

Blockquote

However I would like to simply return the number 4. Have I made a mistake in this definition or is that a method available to get the information from the object blOn?
I tried

{{ blOn | count }}

but that fails with

Blockquote

TypeError: object of type ‘generator’ has no len()

Blockquote

Although if I use

{{ blOn | list }}

This returns

Blockquote
[‘switch.dinning_socket_s1’, ‘switch.kitchen_socket_s1’, ‘switch.kitchen_socket_s2’, ‘switch.porch_socket_s2’]

Blockquote

Any guidance would be gratefully received.

use both.

| list | count

1 Like

Many thanks.

So am I right in thinking that this modifies the blOn object from being a collection of entities, to an array which is then counted, hence the result being a number?

Yes. You can actually add those to your set statement and blOn will be the number.

1 Like

Not exactly. A list or an array is collection. A generator is an object that can produce multiple objects. A thing that you can request the objects from one by one until they run out. It prevents lists from being duplicated all the time.

You could create a generator that produces the prime numbers in ascending order. Those would never fit in a list because there are an infinite number.

The list filter asks for them all and puts them in the list. Tbh it is a bit of a shame that the count filter cannot count them by requesting them from the generator itself. That would have saved some memory during processing and would also save time.

2 Likes