Automation: set Sonos volume by source

Hi,

I have an issue with my automation. I want HA to set the volume of my Sonos based on the source. I have as source, TV, TTS (empty source) or the name of a radio, media, etc. I can set the volume by TV and any other source. However, when I send a TTS command to my Sonos, the source is temporary empty or not existing. How can I check if the source is existing or not?

I have the following automation right now:

id: 0bcc19e0-7f01-457f-9fd9-2b152d1eaf1d
alias: living_room_media_speaker_set_volume_by_source
trigger:
  - platform: state
    entity_id: media_player.living_room_media_speaker
    attribute: source
condition: []
action:
  - service: script.living_room_media_speaker_set_volume
    data:
      entity_id: media_player.living_room_media_speaker
      volume_level: >- 
        {% if state_attr(trigger.entity_id, 'source') == 'TV' %} 
            0.16
        {% elif state_attr(trigger.entity_id, 'source') == '' %} 
            0.20
        {% else %} 
            0.12
        {% endif %}
mode: single

The == ‘’ does not work. I tried | length == 0, but that doesn’t work also as it can not find the source as an entity during tts output.

Edit: found the solution:

{% elif state_attr(trigger.entity_id, 'source') is none %}

Use none instead of an empty string.

        {% elif state_attr(trigger.entity_id, 'source') == none %}
            0.20

Thanks. I found it right before you posted it! :slight_smile:

FWIW, you can also write it using an inline if like this:

      volume_level: >- 
        {% set s = state_attr(trigger.entity_id, 'source') %} 
        {{ '0.20' if s == none else '0.16' if s == 'TV' else '0.12' }}

Cool! That I did now know. Thank you!

1 Like