You could either use interrupts on the pin to change the state of the relais or you swith to using async programming with an async mqtt client and async button implementation:
https://github.com/peterhinch/micropython-mqtt
https://github.com/peterhinch/micropython-async
You'll definitely learn the most this way.
However, if you just want your sonoff s20 to work, you could use tasmota firmware, or if you prefer to stay in micropython and be able to expand or change its behaviour you could use my framework pysmartnode. I use it for a sonoff s20 and multiple sonoff th10:
https://github.com/kevinkk525/pysmartno ... tag/v6.0.2
Just flash the esp8266 firmware and upload a file "components.py" with content:
Code: Select all
import gc
from pysmartnode import config
from pysmartnode.components.machine.button import ToggleButton
from pysmartnode.components.switches.gpio import GPIO
gc.collect()
relais0 = GPIO(12, discover=True, friendly_name="Relais")
config.addComponent("gpio0", relais0)
gc.collect()
class reset:
@staticmethod
async def reset():
await config._log.asyncLog("info", "Button requested reset", timeout=5,
await_connection=False)
import machine
machine.reset()
button0 = ToggleButton(0, long_pressed_component=reset, long_pressed_method="reset",
released_component=relais0, suppress=True)
config.addComponent("button0", button0)
and a "config.py" with contents:
Code: Select all
# Required custom configuration
WIFI_SSID = "ssid"
WIFI_PASSPHRASE = "wifipassphrase"
MQTT_HOST = "192.168.178.10"
MQTT_PORT = 1883
MQTT_USER = "user"
MQTT_PASSWORD = "password"
# Optional configuration
MQTT_DISCOVERY_PREFIX = "homeassistant"
MQTT_RECEIVE_CONFIG = False
WIFI_LED = 13 # set a pin number to have the wifi state displayed by a blinking led. Useful for devices like sonoff
WIFI_LED_ACTIVE_HIGH = False # if led is on when output is low, change to False
WEBREPL_ACTIVE = True # If you want to have the webrepl active. Configures and starts it automatically.
WEBREPL_PASSWORD = "password" # Be aware that webrepl needs 1.5kB of RAM!
RTC_TIMEZONE_OFFSET = 1 # offset from GMT timezone as ntptime on esp8266 does not support timezones
# Does not need to be changed normally
DEBUG = False
DEBUG_STOP_AFTER_EXCEPTION = False