Template Switch

Hi
I am new to HA .I am trying to create a template switch . With the below code, I am able to get the switch in UI but when I toggle it to ON , it turns on the soundbar and toggle icon just goes back to its previous state (off) . The soundbar doesn’t turn off though .

Any help is appreciated .

   - platform: template
    switches:
      bose:
        value_template: "{% if is_state('media_player.bose', 'on') %}on{% else %}off{% endif %}"
        turn_on:
          service: media_player.turn_on
          data:
            entity_id: media_player.bose
        turn_off:
          service: media_player.turn_off
          data:
            entity_id: media_player.bose
1 Like

I believe you need to enclose the on and off in the value_template in single quotes as they also have other special meanings. That should be in the Templating documentation. Also media_players tend to have states other than on and off like pause, stop, idle ,etc. I’m not sure about the Bose media_player but you should check the documentation.

Appreciate the response . I just tried this removing the on and off in value_template and I have the same issue again .I have bose soundtouch 300 . I don’t see any specifics to turning on/off the soundtouch in integration page .As you can see from the screen shot, the switch shows as off but the sound bar is actually turned on . As soon as I turn on the switch ,it turns on the soundbar but the switch goes back to OFF .

 - platform: template
    switches:
      bose:
        value_template: "{{ is_state('media_player.bose', 'on') }}"
        turn_on:
          service: media_player.turn_on
          data:
            entity_id: media_player.bose
        turn_off:
          service: media_player.turn_off
          data:
            entity_id: media_player.bose

Go into the Developer Tools/States and locate the media_player.bose. What does the State column report? It probably isn’t ‘on’. Media players can report a State of ‘on’, ‘off’, ‘pause’, ‘idle’, etc. Likely your bose is in ‘idle’ state which isn’t ‘on’ hence the switch turns off. You will probably want to say

"{{ states('media_player.bose') != 'off' }}"

Or something like that.

2 Likes

I don’t think a media_player ever has a state value called on. It will be something like playing or perhaps paused but not on.

Change the template to this:

        value_template: "{{ not is_state('media_player.bose', 'off') }}"

EDIT

Ninja’d by micque!

1 Like

Thank you @micque @123 . That solved my issue :slight_smile:

Glad to hear it works.

Thank you for tagging my post with the Solution tag. However, I believe you should tag micque’s post as the Solution because it was offered first and also fixes the problem you reported.

Nice to see such great community !

1 Like