Toggling a template switch in esphome

I’m using a Shelly Uni and 2 momentary buttons as detached buttons to trigger an automation (such as switch from ‘day’ to ‘night’ scene). I’m struggling to get the yaml to work correctly. This is what I have:

binary_sensor:
  - platform: gpio
    pin:
      number: GPIO12
      mode:
        input: true
        pullup: true
      inverted: true
    id: button1
    on_click:
      - switch.template.publish:
          id: switch1
          state: !lambda |-
            if (id(switch1).state) {
              return false;
            } else {
              return true;
            }
    internal: true

switch:
  - platform: template
    name: Day/Night Switch
    id: switch1
    optimistic: true
    lambda: return id(switch1).state;

The soft switch shows up correctly in Home Assistant and the behavior is correct. I can turn the switch on and off (and see the correct MQTT messages flowing back and forth)

However, I can’t get the physical button to work. When pressing, I see the button state changing but the template switch state is not changing. I can’t figure out what I’m doing wrong. Any thoughts?

1 Like

Not sure but here’s some things you could try.

  1. Change on click to on press.
  2. Totally remove this / comment out.
lambda: return id(switch1).state;

Try

on_press:
      then:
        - switch.toggle: switch_1

Or if you want button 1 to turn the switch on and button 2 to turn the switch off

Button 1

on_press:
      then:
        - switch.turn_on: switch_1

Button 2

on_press:
      then:
        - switch.turn_off: switch_1

That did the trick. Thank you. The correct YAML is:

binary_sensor:
  - platform: gpio
    pin:
      number: GPIO12
      mode:
        input: true
        pullup: true
      inverted: true
    id: button1
    on_press:
      - switch.toggle: switch1
    internal: true

switch:
  - platform: template
    name: Day/Night Switch
    id: switch1
    optimistic: true
    lambda: return id(switch1).state;

@Mahko_Mahko is correct the lambda in the switch is not needed.

Oops. yes, I forgot to remove that line. Removed it and all still works as expected. txs.

1 Like