Please help from automation esp and relay

I am not a programmer and I hardly understand how to set it up correctly. Help a newbie.
The scheme is simple.
chemes
But in the examples, the button is used as a switch.
And I have a switch with a fixed position.
How to set up automatic switching off the relay with the help of such a switch? And at the same time to be able to control the relay using the home assistant?
I need to understand the main logic. I really want to understand.
switch
I tried these lines. But it causes multiple relay switches.

switch: 
  • platform: gpio
    pin: 4
    name: “rel”
    id: rel

binary_sensor:

  • platform: gpio
    pin: 5
    id: sw
    on_state:
    then:
    switch.toggle: rel

If you are experiencing constant toggling of the binary sensor, I suspect that you need to either use pull up or pull down for your binary sensor. If you see only momentary toggling only when the button is pressed or released, you can consider debouncing. My money is on the former. See below for how to do both.

I’ve found using the debug console with the esp unit directly connected to a machine to be helpful in these situations. You see the behavior immediately without lag.

Adding a pull-up resistor partially solved the problem. Thank!

What do you mean “partially”?

When added a physical resistor on the GPIO connected to the switch.
The relay has ceased to constantly switch state.
But still clicked once every 20 seconds.
Then added filtering and software PULLUP. Now everything is stable.
Maybe it will help someone.

mode: WAKEUP_PULLUP
id: sw
name: “sw”
filters:
- delayed_off: 5ms

why did you use “wakeup_pullup” as the mode? normally you would use “input_pullup” instead. From everything I just read “wakeup_pullup” is only used for devices that are used in a deep sleep scenario.

I did not find the information in what the fundamental difference between these modes. Can you tell me?
But I needed so that when the power was turned on, the relay was always in the off state.

Not really. There isn’t much information aside from what I mentioned above. That is likely because almost no one ever uses the wakeup_pullup mode and just uses the input_pullup. I had never even heard of it until you mentioned it above.

But if it’s working the way you want then I wouldn’t change it.