Switch linked to HomeAssistant switch

This might be something very basic, but I’m new to ESPHome, and I’m a bit lost.
I’m using the Sprinkler Controller and it’s working great. It can control a switch to turn the pump on and off, but my pump isn’t connected to this device, but it’s on Home Assistant.
I know I can call HA services (such as switch.turn_on) from ESPHome, but how can I create a switch (which is what the Sprinkler Controller expects, not a service) that is linked to one on home assistant, instead of a gpio pin?
Thanks!

Something like:

switch:
  - platform: template
    name: "Sprinkler Switch"
    id: sprinkler_switch
    turn_on_action:
      - service: switch.turn_on
        data_template:
          entity_id: 'switch.ha_sprinkler_switch'
    turn_off_action:
      - service: switch.turn_off
        data_template:
          entity_id: 'switch.ha_sprinkler_switch'

Using a template switch:

To make it more reliable, you could add a HA binary sensor that you could check in lambda (see template sensor example) that will track the state even if you change it in HA.

2 Likes

That’s awesome! Thanks a lot… I had seen the turn_on_action, but I didn’t know how to tie it all together, and the docs weren’t making it clear to me. Your example is perfect, clear and to the point. Really appreciated!

In case it is useful for someone else in the same boat, this is how my config turned out:

switch:
  - platform: template
    id: sprinkler_pump
    optimistic: true
    turn_on_action:
      - homeassistant.service:
          service: homeassistant.turn_on
          data:
            entity_id: 'switch.pump'
    turn_off_action:
      - homeassistant.service:
          service: homeassistant.turn_off
          data:
            entity_id: 'switch.pump'

The other syntax was not working for me, but it was easy to fix following the doc examples.

At first I had a problem with the pump not turning off after finishing, but it was because a value is required for that to work. I first tried going the lambda route, but it’s unnecessarily complex and in my case not needed: with optimistic: true it works perfectly, and if the state changes on HA, it’s not a problem, as turn_on and turn_off do nothing if the state is already the target.

2 Likes

very helpful. i’m working on exactly the same thing. thanks!

If suggest familiarizing yourself with the esphome documentation then. It will save you from a lot of unnecessary problems later on.