How do I run script A or B by using a condition in automation?

Hi

I have two scripts that I use to join or unjoin two Sonos-speakers. Both scripts work fine, but I want to toggle between the two.

I have set up a binary sensor that is connected to a GPIO header. So… when I press the physical switch, I want to toggle between grouped/ungrouped speakers.

My scripts:

sonos_group_players:
    sequence:
  - service: media_player.sonos_join
    data:
      master: media_player.stue
    entity_id:
      - media_player.stue
      - media_player.kkken

sonos_ungroup_players:
sequence:
- service: media_player.sonos_unjoin
entity_id:
- media_player.stue
- media_player.kkken

My automation (for now it doesn’t toggle anything, it just fires the group-script):

  - alias: Sonos Group/Ungroup
    trigger:
      platform: state
      entity_id: binary_sensor.sonos_toggle_rooms
      from: "off"
      to: "on"
    action: 
      - service: script.sonos_group_players

What I would have hoped worked, was an automation like this:

  - alias: Sonos Group/Ungroup
trigger:
  platform: state
  entity_id: binary_sensor.sonos_toggle_rooms
  from: "off"
  to: "on"
action: 
  - service:
    {% if is_state('media_player.stue.is_coordinator', 'true') %}
    script.sonos_ungroup_players
    {% else %}
    script.sonos_group_players
    {% endif %}

Please let me know how I would go about solving this :slight_smile:

You’ll want to clean up your YAML posting so that we can read it. Use three tics (`) or use the < / > preformatted text tool.

But - what I think you’re looking for is service_template (rather than “service”).

Thanks - i did click the </> button before I pasted the code, so not sure what else to do.

Can I call scripts with a service_template?
Something like:

service_template: >
  {% if is_state('media_player.stue.is_coordinator', 'true') %}
script.sonos_group_players
  {% else %}
script.sonos_ungroup_players
  {% endif %}

Yes. But in the example you give, you’ve got some indentation issues. Can’t tell if that’s because of cut/paste errors or otherwise.

Use the template dev tool to debug.

Here’s an example from my config.

- alias: Movie Lights
  trigger:
    platform: state
    entity_id: input_boolean.movie_lights
  action:
    - service_template: >
        {% if trigger.to_state.state == 'on' %}
          shell_command.turn_on_movielights
        {% else %}
          shell_command.turn_off_movielights
        {% endif %}
2 Likes

Sorry about the messy code-formatting, but I can’t seem to fix it. Indention in all my code is valid YAML and works fine when edited in Visual Studio Code.

I ended up using this automation:

- alias: Sonos Group/Ungroup
  trigger:
    platform: state
    entity_id: binary_sensor.sonos_toggle_rooms
    from: "off"
    to: "on"
  action:
    - service_template: "{% if is_state_attr('media_player.kkken','is_coordinator', false) %} script.sonos_ungroup_players {% else %} script.sonos_group_players {% endif %}"
1 Like