I really need help from from experienced ‘templaters’, as I’ve simply no idea how to begin extracting the friendly names from the Sonos HA media player group attribute ? I need these friendly names in two new sensors (one master and one slave sensor), so I can display them along with other media player info using ESPhome with a display.
The group is dynamic and can consist of many entities, but always at least one. If grouped, first entity is always the master device and remaining entities are the slave devices.
Below attribute example from one of the slave devices.
sonos_group consist of three devices, where I would like to end up with these devices friendly names as:
sensor.master: Kitchen
sensor.slaves: Living room, Dining room
Any help pushing me in the right direction would really be appreciated, as my templating skills are still quite limited
source_list:
- DR P1
- DR P3
- DR P4 Fyn 96.8 (Nyheder)
- DR P5 (Pop)
- DR P6 Beat
- NOVA
- Radio 100
- Radio Soft
- The Voice
volume_level: 0.15
is_volume_muted: false
media_content_id: 'x-rincon-mp3radio://http://live-icy.gslb01.dr.dk:80/A/A07H.mp3'
media_content_type: music
media_title: DR P4 Fyn
source: DR P4 Fyn 96.8 (Nyheder)
shuffle: false
sonos_group:
- media_player.kitchen
- media_player.livingroom
- media_player.diningroom
friendly_name: Livingroom
entity_picture: >-
/api/media_player_proxy/media_player.livingroom?token=afae26a4bbe16686bc8c0e7ff78f2964bb6ee92f4cf4291e5bb34b93edbe74c0&cache=9c3cd9674956a6b5
supported_features: 64063
The following templates returns the friendly names of the entities of a group:
{% for entity_id in state_attr("group.my_group", "entity_id") -%}
{% set friendly_name = state_attr(entity_id, "friendly_name") %}
{%- if loop.last %}{{ friendly_name }}{% else %}{{ friendly_name }}, {% endif -%}
{%- endfor %}
Then if you want one master sensor and the slaves, the template would look like this:
# Master
{{ state_attr(state_attr("group.my_group", "entity_id")[0], "friendly_name") }}
# Slaves
{% for entity_id in state_attr("group.my_group", "entity_id")[1:] -%}
{% set friendly_name = state_attr(entity_id, "friendly_name") %}
{%- if loop.last %}{{ friendly_name }}{% else %}{{ friendly_name }}, {% endif -%}
{%- endfor %}
You can try this in “Developer Tools > Template” and change group.my_group for any group you have at home. If it is the last entity it does not add the comma, otherwise, it adds a comma and space.
The following would be the sensors with the templates:
I asked for help and you provide the complete solution - Thank you !!
I really have to improve my templating skills quickly, as it’s very hard to do anything advanced without templates. But I find it difficult to find some medium/advanced template examples online to learn from.
I’ll incorporate these sensors at once in my display project
I’ve just corrected one minor syntax error on the master sensor (see below).