💬 Sonoff relay using MySensors ESP8266 wifi or mqtt gateway

  • Admin

    Great! Added to the main site now.

  • Sorry, but what's the use case here?
    With Sonoff it's either hard or impossible to add a radio or rs485 transport, so I don't see it as a real gateway.
    If one wants to use it as a pure client and control it with MQTT - there is a great working solution available already: https://github.com/arendst/Sonoff-MQTT-OTA-Arduino

  • Admin

    The use case is that you can use the sonoff with all controllers that support mysensors.

  • With all my respect to the project and people behind it I believe that MQTT is more widely used than MySensors. So for me it would be more logical to add another MQTT client to the network rather than introduce any additional gateway. Just my 2¢.

  • @AndrewZ

    This is not really a gateway. You can use the esp8266 gateway sketch, disable the nrf24 / rfm69 and directly attach sensors. So basically it's an relay actuator which is configured as a mysensors gateway.

  • Hero Member

    I think what's throwing everybody off is applying the word "gateway" to this sonoff device. Wouldn't it make more sense to have it remain a relay actuator (i.e. just a node) and to have the mysensors gateway be something else (of which there are many examples on this website)? i.e. it makes more sense to have it be a mysensors node (or MQTT node if that's your architecture) than to have it be a mysensors gateway. Wouldn't it?

  • This is not listed as a gateway but under sensors & actuators but maybe a "s/and/relay using" would be a fix of the headline. I selected the mqtt gateway example just because I have a few other NodeMCU's working as just MYS sensors with no radio but it's trivial to just re-use code for any of the other gateways, as you all know. I choose the mqtt addition just for fun and know there are other mqtt examples but nothing working out of the box with my HASS + MYS + mqtt setup. Regarding the gateway naming, at least I don't know any other way of using MYS and ESP8266 than using the gateway sketches with a disabled radio. What should they be called, just node? At the same time, adding a radio to the Sonoff and it's a gateway...

  • Maybe a good solution to the node/gateway dilemma is adding WiFi transport for nodes to MySensors? Then defining one or more WiFi gateways to connect sensors to. You could then use WiFi enabled devices, such as ESP8266 as sensor nodes. You could use these as radio interfaces to Arduino nodes, with their original serial-to-WiFi firmware and treat it much like the RS485 transport.

  • Hero Member

    Yup. It's either that or do the MQTT thing (which, personally, I favor, though right now it's a minority opinion) like AndrewZ said.

  • I don't see the problem here. An direct ip connection between the controller and the node is perfect for critical nodes as less components mean less things that can fail. I have flashed a Sonoff Touch switch with the esp8266 gateway sketch and it is running just fine. Or am I missing something?

  • @Jan-Gatzke What code modifications have you done to get the touch buttons to work or do they work like "normal" buttons? I really like the built-in form factor and was thinking about ordering a few.

  • @Efflon

    All the touch stuff is handheld by an ic. You can use it like an normal button, active low. It is connected to pin 0. I have made a two way switch of it. With a long press I cycle through multiple scenes which control the color of my tv's led light. With a even longer press I can switch the tv light off. I can share the code when I found the time to clean it up.

    I like the OTA update function of the esp very much. It's much simpler than the rf24/ Arduino solution. My sketch provides a browser based update function with just 5 lines of code. This was important to me because I don't want to get my switches out off the wall for every update. For the eu version of the sonoff this is mandatory because the programming header does not fit when the device is mounted.

  • @Jan-Gatzke Excelletn info, thanks! Yes, please share your code , the state doesn't matter for me at least :D

  • @Efflon

    Ok, I just wiped out (hopefully) all my passwords and IP information. :D

       The MySensors Arduino library handles the wireless radio link and protocol
       between your home built sensors/actuators and HA controller of choice.
       The sensors forms a self healing radio network with optional repeaters. Each
       repeater and gateway builds a routing tables in EEPROM which keeps track of the
       network topology allowing messages to be routed to nodes.
       Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
       Copyright (C) 2013-2015 Sensnology AB
       Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
       Documentation: http://www.mysensors.org
       Support Forum: http://forum.mysensors.org
       This program is free software; you can redistribute it and/or
       modify it under the terms of the GNU General Public License
       version 2 as published by the Free Software Foundation.
       Version 1.0 - Henrik EKblad
       Contribution by a-lurker and Anticimex,
       Contribution by Norbert Truchsess <norbert.truchsess@t-online.de>
       Contribution by Ivo Pullens (ESP8266 support)
       The EthernetGateway sends data received from sensors to the WiFi link.
       The gateway also accepts input on ethernet interface, which is then sent out to the radio network.
       Enter "ip-number:port" in the ip-field of the Arduino GW device. This will temporarily override any serial configuration for the Vera plugin.
       E.g. If you want to use the defualt values in this sketch enter:
       LED purposes:
       - To use the feature, uncomment WITH_LEDS_BLINKING in MyConfig.h
       - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved
       - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly
       - ERR (red) - fast blink on error during transmission error or recieve crc error
       See http://www.mysensors.org/build/esp8266_gateway for wiring instructions.
       nRF24L01+  ESP8266
       VCC        VCC
       CE         GPIO4
       CSN/CS     GPIO15
       SCK        GPIO14
       MISO       GPIO12
       MOSI       GPIO13
       GND        GND
       Not all ESP8266 modules have all pins available on their external interface.
       This code has been tested on an ESP-12 module.
       The ESP8266 requires a certain pin configuration to download code, and another one to run code:
       - Connect REST (reset) via 10K pullup resistor to VCC, and via switch to GND ('reset switch')
       - Connect GPIO15 via 10K pulldown resistor to GND
       - Connect CH_PD via 10K resistor to VCC
       - Connect GPIO2 via 10K resistor to VCC
       - Connect GPIO0 via 10K resistor to VCC, and via switch to GND ('bootload switch')
        Inclusion mode button:
       - Connect GPIO5 via switch to GND ('inclusion switch')
       Hardware SHA204 signing is currently not supported!
       Make sure to fill in your ssid and WiFi password below for ssid & pass.
    #include <SPI.h>
    // Enable debug prints to serial monitor
    #define MY_DEBUG
    // Use a bit lower baudrate for serial prints on ESP8266 than default in MyConfig.h
    #define MY_BAUD_RATE 9600
    // Enables and select radio type (if attached)
    //#define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    #define MY_GATEWAY_ESP8266
    #define MY_ESP8266_SSID "MySSID"
    #define MY_ESP8266_PASSWORD "MyPSK"
    // Enable UDP communication
    //#define MY_USE_UDP
    // Set the hostname for the WiFi Client. This is the hostname
    // it will pass to the DHCP server if not static.
    // #define MY_ESP8266_HOSTNAME "sensor-gateway"
    // Enable MY_IP_ADDRESS here if you want a static ip address (no DHCP)
    #define MY_IP_ADDRESS 192,168,1,200
    // If using static ip you need to define Gateway and Subnet address as well
    #define MY_IP_GATEWAY_ADDRESS 192,168,1,254
    #define MY_IP_SUBNET_ADDRESS 255,255,255,0
    // The port to keep open on node server mode
    #define MY_PORT 5003
    // How many clients should be able to connect to this gateway (default 1)
    // Controller ip address. Enables client mode (default is "server" mode).
    // Also enable this if MY_USE_UDP is used and you want sensor data sent somewhere.
    //#define MY_CONTROLLER_IP_ADDRESS 192, 168, 178, 68
    // Enable inclusion mode
    // Enable Inclusion mode button on gateway
    // Set inclusion mode duration (in seconds)
    // Digital pin used for inclusion mode button
    // Flash leds on rx/tx/err
    // Set blinking period
    // #define MY_DEFAULT_LED_BLINK_PERIOD 300
    // Led pins used if blinking feature is enabled above
    //#define MY_DEFAULT_ERR_LED_PIN 16  // Error led pin
    //#define MY_DEFAULT_RX_LED_PIN  16  // Receive led pin
    //#define MY_DEFAULT_TX_LED_PIN  16  // the PCB, on board LED
    #if defined(MY_USE_UDP)
    #include <WiFiUDP.h>
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>
    #include <ESP8266HTTPUpdateServer.h>
    #include <MySensors.h>
    #define RELAY_1_Pin  12
    #define LED_1_Pin 13
    #define TOUCH_1_Pin 0
    #define RELAY_1  1
    #define TOUCH_1 3
    #define TOUCH_2 4
    boolean relayon = false;
    int activescene = 1;
    volatile unsigned long LastChange = 0;
    volatile boolean RelayToggleRequired = false;
    volatile boolean SceneSwitchRequired = false;
    volatile boolean SceneSwitchTriggeredByTimeout = false;
    volatile boolean SceneSwitchTriggeredByTimeout2 = false;
    MyMessage msg(RELAY_1, V_LIGHT);
    MyMessage msg1(TOUCH_1, V_SCENE_ON);
    MyMessage msg2(TOUCH_2, V_LIGHT);
    ESP8266WebServer httpServer(80);
    ESP8266HTTPUpdateServer httpUpdater;
    const char* host = "sonofftouch1";
    const char* location = "Couch";
    char* update_username = "admin";        //Benutzername zum login für die OTA-Programmierung
    char* update_password = "MyPassword";      //Passwort
    String webPage = "";
    unsigned long lastheartbeat = 0;
    void buttonChangeCallback() {
      if (digitalRead(TOUCH_1_Pin) == 1) {
        //LED off for feedback
        digitalWrite(LED_1_Pin, 1);
        //Button has been released, trigger one of the two possible options.
        if (millis() - LastChange > 500) {
          //Long Press
          if (!SceneSwitchTriggeredByTimeout) {
            SceneSwitchRequired = true;
        else if (millis() - LastChange > 50) {
          //Short press at least 50 ms for debounce
          RelayToggleRequired = true;
        else {
          //Too short to register as a press
      else {
        //LED on for feedback
        digitalWrite(LED_1_Pin, 0);
        //Just been pressed - do nothing until released.
      LastChange = millis();
      SceneSwitchTriggeredByTimeout = false;
      SceneSwitchTriggeredByTimeout2 = false;
    void setup() {
      webPage += "<h1>ESP8266 Web Server</h1>";
      webPage += "<br><h1>";
      webPage += host;
      webPage += "</h1>";
      webPage += "<br><h1>";
      webPage += location;
      webPage += "</h1>";
      webPage += "<br><a href=/update>Click here to update</a>";
      pinMode(TOUCH_1_Pin, INPUT_PULLUP);      // sets the digital pin as output
      pinMode(RELAY_1_Pin, OUTPUT);
      pinMode(LED_1_Pin, OUTPUT);
      //LED off
      digitalWrite(LED_1_Pin, 1);
      httpUpdater.setup(&httpServer, "/update", update_username, update_password);
      MDNS.addService("http", "tcp", 80);
      httpServer.on("/", []() {
        httpServer.send(200, "text/html", webPage);
      Serial.println("Enabling touch switch interrupt");
      attachInterrupt(digitalPinToInterrupt(TOUCH_1_Pin), buttonChangeCallback, CHANGE);
    void presentation() {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("Sonoff Touch Mysensors", "1.0");
      present(RELAY_1, S_LIGHT, "single click/onboard relay");
      present(TOUCH_1, S_SCENE_CONTROLLER, "double click/scene controller");
      present(TOUCH_2, S_LIGHT, "long press virtuel switch");
    void loop() {
      if (millis() - lastheartbeat > 30000) {
        lastheartbeat = millis();
      if (RelayToggleRequired) {
        RelayToggleRequired = false;
      if (SceneSwitchRequired) {
        SceneSwitchRequired = false;
      if (millis() - LastChange > 600) {
        if (digitalRead(TOUCH_1_Pin) == 0) {
          if (SceneSwitchTriggeredByTimeout == false) {
            SceneSwitchTriggeredByTimeout = true;
      if (millis() - LastChange > 3000) {
        if (digitalRead(TOUCH_1_Pin) == 0) {
          if (SceneSwitchTriggeredByTimeout2 == false) {
            SceneSwitchTriggeredByTimeout2 = true;
    void receive(const MyMessage &message) {
      // We only expect one type of message from controller. But we better check anyway.
      if (message.type == V_LIGHT) {
        // Change relay state
        if (message.sensor == RELAY_1) {
          digitalWrite(RELAY_1_Pin, message.getBool() ? 1 : 0);
          relayon = message.getBool() ? 1 : 0;
        // Write some debug info
        Serial.print("Incoming change for sensor:");
        Serial.print(", New status: ");
    void ToggleRelay() {
      Serial.println("Single Click");
      if (relayon) {
        digitalWrite(RELAY_1_Pin, 0);
        relayon = false;
      else {
        digitalWrite(RELAY_1_Pin, 1);
        relayon = true;
      send(msg.set(relayon ? 1 : 0));
    void SwitchScene() {
      //Domoticz does not like 1 as scene. So we start with scene 2.
      Serial.println("Long press");
      activescene += 1;
      if (activescene > 6) {
        activescene = 2;
      Serial.print("Activating Scene ");
    void SwitchSceneOff() {
      Serial.println("3sec Long Press");

  • Mod

    Configuring it as a gateway allows you to directly add it to the controller even it is isn't routing anything else than it's local I/O, making it very straightforward

  • @Jan-Gatzke Thanks! A Interesting and inspiring code example. Did you think about using the arduinoOTA option instead of the httpUpdater?

  • @Efflon

    Yes, I thought about that. But during my tests the web updater was just most reliable and easiest to use. Arduino ota needs extensions to the IDE and sometimes the node was not found. Web updater works out of the box and never made any problems.

  • @Jan-Gatzke Great to know!

  • This sketch is awesome, First MySensors sketch I have used that worked straight off the bat.

    The details page does need a few extra bits of info....

    3.3v FTDI tool needed

    Hold down the button on the Sonoff when you power it up to enter flash mode.

Log in to reply

Looks like your connection to MySensors Forum was lost, please wait while we try to reconnect.