- Count the number of media players currently in a paused or playing state
- Have a value of true or false based on if there was at least one media player in these states
Both options are possible, but I decided to go with the count of media players as this could be a handy figure for other uses.
Home Assistant count media players playing or paused
{{ int(states.media_player|selectattr("state","equalto","playing")|list|length) + int(states.media_player|selectattr("state","equalto","paused")|list|length) }}
This Home Assistant value template calculates the total
number of media players that are either in a "playing" or
"paused" state, and returns the result as an integer.
Here's a breakdown of how the template works:
- states.media_player
retrieves a list of all media player entities in the current Home
Assistant state.
- |selectattr("state","equalto","playing")
filters this list to only include entities whose state attribute is
equal to "playing".
- |list
converts this filtered list into a standard Python list format.
- |length
returns the number of items in the resulting list as an integer.
- The
same process is repeated for the "paused" state, and the two
resulting integers are added together using the + operator.
The end result is a single integer value that represents the
total number of media players that are either playing or paused.
Adding this formula into your Home Assistant configuration file can be done with the following code.
sensor:
- platform: template
sensors:
active_media_players:
friendly_name: 'Active media players'
value_template: '{{ int(states.media_player|selectattr("state","equalto","playing")|list|length) + int(states.media_player|selectattr("state","equalto","paused")|list|length) }}'
Was this helpful?
Comments
Post a Comment