Switch template that check the state first

Hello,

I’ve configured a switch template to turn on and off my tv sending an IR signal. The problem is that that signal is the same for turning it on and off, so I want to make sure that it is not send if already in that state.

I use the switch template to integrate it with Google Assistant so the order can be launched in any moment/state.

This is the configuration:

- platform: template
  switches:
    tv_salon_switch:
      friendly_name: "Tele"
      entity_id: media_player.chromecast_salon
      value_template: "{{ not is_state('media_player.chromecast_salon', 'unavailable') }}"
      turn_on:
        service: remote.send_command
        data:
          entity_id: remote.xiaomi_miio_salon
          command:
            - tv_standby
      turn_off:
        service: remote.send_command
        data:
          entity_id: remote.xiaomi_miio_salon
          command:
            - tv_standby

It works properly in HA, i mean, state is correctly detected and I can switch it on/off correctly. But when used with Google Assistant I can send the switch off order several times and it is always run no matter the current state of switch.

I want to send the switch off order from Google Assistant (or any other source) and that the order don’t run if the switch is already in that state.

Is it possible?

I think it could be possible replacing direct “remote.send_command” by a script that check the state first. But maybe is there any other and more direct/elegant way to do it.

Thanks in advance.

Best regards,
Lukeid

That’s the way I do it for operating my old non-smart garage door using a z wave switch. I have Alexa run a script that checks the position of the door and then operates the switch if the state matches the command requirements.