Hi all,
I currently use the below code to count the amount of lights that are on in my place:
- platform: template
sensors:
lights_on:
value_template: >
{% set lights = [
states.light.tv_light,
states.light.table_light,
states.light.kitchen_light,
states.light.bedroom_light,
states.light.wardrobe_light,
] %}
{{ lights | selectattr('state','eq','on') | list | count }}
However when I tried adapting it to count media players playing, it does not work. As I do not fully understand how to work with templating I was hoping someone could tell me how to count the currently active media players.
This is my non-working code:
- platform: template
sensors:
media_players_active:
value_template: " {{ states.media_player | selectattr('state','eq','on') | selectattr('state','eq','playing') | list | count }}"
{% set states.media_player = [
states.media_player.bed_room_display,
states.media_player.bedroom_tv,
states.media_player.kitchen_speaker,
states.media_player.living_room_speaker,
states.media_player.living_room_tv,
states.media_player.shield_tv,
] %}
Looking forward to your replies.
Cheers
tom_l
May 19, 2020, 11:20am
2
Try this:
- platform: template
sensors:
media_players_active:
value_template: >
{% set media_players = [
states.media_player.bed_room_display,
states.media_player.bedroom_tv,
states.media_player.kitchen_speaker,
states.media_player.living_room_speaker,
states.media_player.living_room_tv,
states.media_player.shield_tv,
] %}
{{ media_players | selectattr('state','eq','playing') | list | count }}
4 Likes
Thanks a lot Tom!!
That did the trick.
Out of curiosity:
{{ media_players | selectattr(‘state’,‘eq’,‘playing’) | list | count }}
The media_players part, how is this syntax defined? I now know that you have media_players and lights, does that then mean that you also have scripts, automations etc…? Whereis this value defined?
Thanks again for the help
tom_l
May 19, 2020, 1:43pm
4
The first bit is just a variable used to store the list of media players. It can be named anything, e.g.
- platform: template
sensors:
media_players_active:
value_template: >
{% set brown_trousers = [
states.media_player.bed_room_display,
states.media_player.bedroom_tv,
states.media_player.kitchen_speaker,
states.media_player.living_room_speaker,
states.media_player.living_room_tv,
states.media_player.shield_tv,
] %}
{{ brown_trousers | selectattr('state','eq','playing') | list | count }}
It makes more sense to call the variable after what it is storing though.
1 Like
I followed exactly what you said but it’s not working damn.
injectx
(Injectx)
December 27, 2022, 7:29pm
6
Anyone has a solution for this? Doesn’t seem to work, I’m guessing the formatting has changed over the years.
addrum
February 17, 2023, 6:08pm
7
This still works on latest version:
{{ states.media_player | selectattr('state','eq','playing') | list | count }}
It does grab all media_players
though so adjust the first part if you only want to include specific entities.
2 Likes