ESPHome Switch not respecting state

Hi all,

I have just connected up a ESP32 board to an AliExpress 4-relay board which requires a UART communication to turn the relays on and off. What I have so far is this:

uart:
  tx_pin: GPIO5
  baud_rate: 115200

switch:
  - platform: template
    name: "Relay-1"
    turn_on_action:
      - uart.write: [0xA0, 0x01, 0x01, 0xA2]
    turn_off_action:
      - uart.write: [0xA0, 0x01, 0x00, 0xA1]
  - platform: template
    name: "Relay-2"
    turn_on_action:
      - uart.write: [0xA0, 0x02, 0x01, 0xA3]
    turn_off_action:
      - uart.write: [0xA0, 0x02, 0x00, 0xA2]
  - platform: template
    name: "Relay-3"
    turn_on_action:
      - uart.write: [0xA0, 0x03, 0x01, 0xA4]
    turn_off_action:
      - uart.write: [0xA0, 0x03, 0x00, 0xA3]
  - platform: template
    name: "Relay-4"
    turn_on_action:
      - uart.write: [0xA0, 0x03, 0x01, 0xA5]
    turn_off_action:
      - uart.write: [0xA0, 0x03, 0x00, 0xA4]

This actually works reasonably well, clicking the entity switch in Home Assistant turns the relay on. The issue is that after a couple of seconds, Home Assistant sets the switch state to ‘Off’ for no apparent reason? The relay is left open, so now the states mismatch the hardware.
Any ideas what’s wrong with the code?

Thanks!

You have no lambda for state feedback for each switch, so esphome does not know what state the switch is in. As you have no way to obtain this state just add this to each switch:

optimistic: true

Esphome will then assume all your on/off commands work and will change the sate using only whichever command (on/off) is issued.

1 Like

Thank you for the very clear and informative response, that makes a lot of sense. I’ll give it a go, cheers!