Template to count covers partially open

Hi all,

I’d like to count which are the covers partially open at my home and to do so, I created a template like this:

        friendly_name: 'Covers partial'
        icon_template: 'mdi:window-shutter'
        value_template: "{{ expand('cover.home_covers') | selectattr('state', 'as_number') | select('gt', '0') | select('lt', '100') | list | count }}"

where “cover.home_covers” is a group that includes all the covers.

Then I restarted home assistant but the sensor is unavailable.
Is there something wrong in the syntax template?

Try the template out in Developer Tools / Template a bit at a time. Your first filter fails for me. I think you want:

{{ expand('cover.home_covers') 
   |list|count }}

Then when it’s working, transfer it to a template sensor. I’d recommend either writing it in modern configuration (yours is legacy) or creating a template sensor Helper via the UI using the above template in the State Template box:

You can then set the icon via the UI settings.

1 Like

Right. I always forget this home assistant functionality.

It’s the thing I use most :slight_smile:

Unfortunately it doesn’t work.
Anyway I tried to write down a jinja code like this:

{% set entities = expand('cover.tapparelle_casa') %}
{% set count = 0 %}
{% for entity in entities %}
  {% set pos = state_attr(entity.entity_id, 'current_position') %}
  {{ pos }}
    {% if 0 < pos < 100  %}
     {% set count = count + 1 %}
     {{ count }}
    {% endif %}  
{% endfor %}
{{ count }}

and what I get as output is the following:







I don’t understand why count doesn’t increment (it should be equal to 2) and mostly why if I print outside the for cycle it remains equal to 0.

Try this version (it assumes all of your cover entities have a current_position attribute).

{{ expand('cover.home_covers') 
   | map(attribute='attributes.current_position')
   | select('>', 0) | select('<', 100)
   | list | count }}
1 Like

It works.
I didn’t understand that I could use “map(attribute=‘attributes.current_position’)” to select the current_position of my covers.
Thank you.

PS: now starting from this I will have to do other similar templates, I hope I had enough to use it as starting point.

Is there any chance to store all current position in a list or array? And then to be able to select them?
I need to check if the covers are at specific positions percentage that i decide to be an ideal position for me.

What for? are you trying to list the names of the open covers?

{% set attr = 'attributes.current_position' %}
{{ expand('cover.home_covers') 
    | selectattr(attr, 'defined')
    | rejectattr(attr, 'none')
    | selectattr(attr, '>', 0) 
    | selectattr(attr, '<', 100)
    | map(attribute='name')
    | list }}

No no, I need to check and count if the covers are partially open (as above) but except when one is at 32%, second one is at 18% and the third one at 22%.