How can HA know state of switches - open/close

I’m sure there’s a simple way to do this, but I’m puzzled. I have two relays, one to open a valve and one to close the valve. I don’t want an automation to turn on a relay when it is already in the desired state). What’s the best way to have HA know what the current state is?

switch:
  - platform: gpio
    # SN74HC595 Pin #0
    name: "Switch 1"
    pin:
      sn74hc595: sn74hc595_hub
      # Use pin number 0
      number: 0
      inverted: false
      id: relay1

  - platform: gpio
    # SN74HC595 Pin #1
    name: "Switch 2"
    pin:
      sn74hc595: sn74hc595_hub
      # Use pin number 1
      number: 1
      inverted: false
      id: relay2

Hi Dan, I think (only started with ESPHome recently) you have to create a (binary) sensor in your ESP config which will be exposed to HA to be used as a state.

I think you want to momentary activate the relay to open or close it?

If so, I would make the two switches you have now fully internal. And add a template switch. Or better, a template valve.

switch:
  - platform: gpio
    # SN74HC595 Pin #0
    name: "Switch open"
    id: valve_open
    internal: true
    pin:
      sn74hc595: sn74hc595_hub
      # Use pin number 0
      number: 0
      inverted: false
      id: relay1
  
  - platform: gpio
    # SN74HC595 Pin #1
    name: "Switch Close"
    id: valve_close
    internal: true
    pin:
      sn74hc595: sn74hc595_hub
      # Use pin number 1
      number: 1
      inverted: false
      id: relay2

valve:
  - platform: template
    name: "Valve"
    id: my_valve
    optimistic: true
    restore_mode: RESTORE
    open_action: 
      - switch.turn_on: valve_open
      - delay: 1s
      - switch.turn_off: valve_open
    close_action: 
      - switch.turn_on: valve_close
      - delay: 1s
      - switch.turn_off: valve_close
1 Like

Thank you very much. This solution works perfectly!

Good you got it solved!

Please take the time to mark the post that helped you solving your issue as the solution so anyone who’s searching for this can benefit from it like you did.
You do that by selecting the three dots under the post:

image

Then select the check box:

image

Also, by doing so this prevents that someone else steps in to try to help.