How to count media players in two different states?

Hi all,
I currently use the code below to count how many media players are currently in use.

            {% set media_players = [
              states.media_player.1,
              states.media_player.2,
              states.media_player.3,
              states.media_player.pc,
              ] %}
            {% set playing_number = (media_players | selectattr('state','eq','playing') | list | count)%}
            {% if playing_number!= 0 %}
            xyz
            {% elif playing_number== 0 %}
            abc
            {% endif %}This text will be hidden

However, one of my media players which is just old tv reports only two types of state - ON or OFF.
How can i modify my code to count different states - ‘playing’ and ‘on’ ?

Looking forward to your replies.
Cheers

If it’s a media_player, I would expect the states to be in lower-case on or off as opposed to upper-case ON or OFF. However if they are actually in upper-case, just adjust the following template accordingly.

 {% set playing_number = media_players | selectattr('state', 'in', ['playing', 'on']) | list | count %}

If you’re interested, you can reduce the entire template to this:

{% set playing = expand('media_player.1', 'media_player.2', 'media_player.3', 'media_player.pc')
  | selectattr('state', 'in', ['playing', 'on']) | list | count %}
{{ 'xyz' if playing > 0 else 'abc' }}

Yes, you are tottaly right. I was inconsistent.

Code is of course correct. Thanks!

1 Like