Skip to content
  • MySensors
  • OpenHardware.io
  • Categories
  • Recent
  • Tags
  • Popular
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Brand Logo
  1. Home
  2. OpenHardware.io
  3. 💬 Sonoff relay using MySensors ESP8266 wifi or mqtt gateway

💬 Sonoff relay using MySensors ESP8266 wifi or mqtt gateway

Scheduled Pinned Locked Moved OpenHardware.io
mqttsonoffhome assistanesp8266
93 Posts 25 Posters 28.0k Views 20 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • danbiD Offline
    danbiD Offline
    danbi
    wrote on last edited by
    #9

    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.

    NeverDieN gohanG 2 Replies Last reply
    0
    • danbiD danbi

      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.

      NeverDieN Offline
      NeverDieN Offline
      NeverDie
      Hero Member
      wrote on last edited by NeverDie
      #10

      @danbi
      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.

      1 Reply Last reply
      0
      • J Offline
        J Offline
        Jan Gatzke
        wrote on last edited by
        #11

        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?

        EfflonE 1 Reply Last reply
        0
        • J Jan Gatzke

          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?

          EfflonE Offline
          EfflonE Offline
          Efflon
          wrote on last edited by
          #12

          @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.

          J 1 Reply Last reply
          0
          • EfflonE Efflon

            @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.

            J Offline
            J Offline
            Jan Gatzke
            wrote on last edited by
            #13

            @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.

            EfflonE 1 Reply Last reply
            0
            • J Jan Gatzke

              @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.

              EfflonE Offline
              EfflonE Offline
              Efflon
              wrote on last edited by
              #14

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

              J 1 Reply Last reply
              0
              • EfflonE Efflon

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

                J Offline
                J Offline
                Jan Gatzke
                wrote on last edited by
                #15

                @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.
                
                 *******************************
                
                   REVISION HISTORY
                   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)
                
                   DESCRIPTION
                   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.
                
                   VERA CONFIGURATION:
                   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: 192.168.178.66:5003
                
                   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)
                #define MY_GATEWAY_MAX_CLIENTS 2
                
                // 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
                //#define MY_INCLUSION_MODE_FEATURE
                
                // Enable Inclusion mode button on gateway
                // #define MY_INCLUSION_BUTTON_FEATURE
                // Set inclusion mode duration (in seconds)
                //#define MY_INCLUSION_MODE_DURATION 60
                // Digital pin used for inclusion mode button
                //#define MY_INCLUSION_MODE_BUTTON_PIN  3
                
                
                // Flash leds on rx/tx/err
                // #define MY_LEDS_BLINKING_FEATURE
                // 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>
                #else
                #include <ESP8266WiFi.h>
                #endif
                
                #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);
                
                  MDNS.begin(host);
                  httpUpdater.setup(&httpServer, "/update", update_username, update_password);
                  httpServer.begin();
                  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() {
                  httpServer.handleClient();
                  if (millis() - lastheartbeat > 30000) {
                    //sendHeartbeat();
                    sendBatteryLevel(90);
                    lastheartbeat = millis();
                  }
                
                  if (RelayToggleRequired) {
                    ToggleRelay();
                    RelayToggleRequired = false;
                  }
                
                  if (SceneSwitchRequired) {
                    SwitchScene();
                    SceneSwitchRequired = false;
                  }
                
                  if (millis() - LastChange > 600) {
                    if (digitalRead(TOUCH_1_Pin) == 0) {
                      if (SceneSwitchTriggeredByTimeout == false) {
                        SceneSwitchTriggeredByTimeout = true;
                        SwitchScene();
                      }
                    }
                  }
                
                  if (millis() - LastChange > 3000) {
                    if (digitalRead(TOUCH_1_Pin) == 0) {
                      if (SceneSwitchTriggeredByTimeout2 == false) {
                        SceneSwitchTriggeredByTimeout2 = true;
                        SwitchSceneOff();
                      }
                    }
                  }
                }
                
                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(message.sensor);
                    Serial.print(", New status: ");
                    Serial.println(message.getBool());
                  }
                }
                
                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 ");
                  Serial.println(activescene);
                  send(msg1.set(activescene));
                }
                
                void SwitchSceneOff() {
                  Serial.println("3sec Long Press");
                  send(msg1.set(7));
                }
                
                EfflonE 1 Reply Last reply
                1
                • danbiD danbi

                  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.

                  gohanG Offline
                  gohanG Offline
                  gohan
                  Mod
                  wrote on last edited by
                  #16

                  @danbi
                  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

                  1 Reply Last reply
                  0
                  • J Jan Gatzke

                    @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.
                    
                     *******************************
                    
                       REVISION HISTORY
                       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)
                    
                       DESCRIPTION
                       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.
                    
                       VERA CONFIGURATION:
                       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: 192.168.178.66:5003
                    
                       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)
                    #define MY_GATEWAY_MAX_CLIENTS 2
                    
                    // 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
                    //#define MY_INCLUSION_MODE_FEATURE
                    
                    // Enable Inclusion mode button on gateway
                    // #define MY_INCLUSION_BUTTON_FEATURE
                    // Set inclusion mode duration (in seconds)
                    //#define MY_INCLUSION_MODE_DURATION 60
                    // Digital pin used for inclusion mode button
                    //#define MY_INCLUSION_MODE_BUTTON_PIN  3
                    
                    
                    // Flash leds on rx/tx/err
                    // #define MY_LEDS_BLINKING_FEATURE
                    // 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>
                    #else
                    #include <ESP8266WiFi.h>
                    #endif
                    
                    #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);
                    
                      MDNS.begin(host);
                      httpUpdater.setup(&httpServer, "/update", update_username, update_password);
                      httpServer.begin();
                      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() {
                      httpServer.handleClient();
                      if (millis() - lastheartbeat > 30000) {
                        //sendHeartbeat();
                        sendBatteryLevel(90);
                        lastheartbeat = millis();
                      }
                    
                      if (RelayToggleRequired) {
                        ToggleRelay();
                        RelayToggleRequired = false;
                      }
                    
                      if (SceneSwitchRequired) {
                        SwitchScene();
                        SceneSwitchRequired = false;
                      }
                    
                      if (millis() - LastChange > 600) {
                        if (digitalRead(TOUCH_1_Pin) == 0) {
                          if (SceneSwitchTriggeredByTimeout == false) {
                            SceneSwitchTriggeredByTimeout = true;
                            SwitchScene();
                          }
                        }
                      }
                    
                      if (millis() - LastChange > 3000) {
                        if (digitalRead(TOUCH_1_Pin) == 0) {
                          if (SceneSwitchTriggeredByTimeout2 == false) {
                            SceneSwitchTriggeredByTimeout2 = true;
                            SwitchSceneOff();
                          }
                        }
                      }
                    }
                    
                    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(message.sensor);
                        Serial.print(", New status: ");
                        Serial.println(message.getBool());
                      }
                    }
                    
                    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 ");
                      Serial.println(activescene);
                      send(msg1.set(activescene));
                    }
                    
                    void SwitchSceneOff() {
                      Serial.println("3sec Long Press");
                      send(msg1.set(7));
                    }
                    
                    EfflonE Offline
                    EfflonE Offline
                    Efflon
                    wrote on last edited by
                    #17

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

                    J 1 Reply Last reply
                    0
                    • EfflonE Efflon

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

                      J Offline
                      J Offline
                      Jan Gatzke
                      wrote on last edited by
                      #18

                      @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.

                      EfflonE 1 Reply Last reply
                      0
                      • J Jan Gatzke

                        @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.

                        EfflonE Offline
                        EfflonE Offline
                        Efflon
                        wrote on last edited by
                        #19

                        @Jan-Gatzke Great to know!

                        1 Reply Last reply
                        0
                        • BrydenB Offline
                          BrydenB Offline
                          Bryden
                          wrote on last edited by
                          #20

                          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.

                          EfflonE 1 Reply Last reply
                          0
                          • BrydenB Bryden

                            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.

                            EfflonE Offline
                            EfflonE Offline
                            Efflon
                            wrote on last edited by
                            #21

                            @Bryden It's hidden in the code of the sketch "* Hold Sonoff button when attaching FTDI to flash."

                            1 Reply Last reply
                            0
                            • warmaniacW Offline
                              warmaniacW Offline
                              warmaniac
                              wrote on last edited by
                              #22

                              @Efflon

                              Can I ask please ? I don't know if I understand correctly principle of working Sonoff under mysensors , I uploaded sketch from here to Sonoff , Sonoff is connected to my WiFi network , now I need to make MQTT gateway connected trought LAN or WiFi to the raspberry where is running Domoticz ? I had nodeMCU will it work ? Thanks much

                              EfflonE 1 Reply Last reply
                              0
                              • gohanG Offline
                                gohanG Offline
                                gohan
                                Mod
                                wrote on last edited by
                                #23

                                You would need to use the esp8266 gateway sketch and connect it to domoticz as a new mysensors gateway. IMHO in this case it is easier to flash ESPEasy or espurna and use it as mqtt stand alone, not mysensors since you don't have a real benefit to have it running mysensors

                                1 Reply Last reply
                                0
                                • hekH Offline
                                  hekH Offline
                                  hek
                                  Admin
                                  wrote on last edited by
                                  #24

                                  @gohan,
                                  it depends on if the controller supports ESPEasy/espurna "out of the box". Not all controllers even have MQTT support.

                                  1 Reply Last reply
                                  0
                                  • warmaniacW warmaniac

                                    @Efflon

                                    Can I ask please ? I don't know if I understand correctly principle of working Sonoff under mysensors , I uploaded sketch from here to Sonoff , Sonoff is connected to my WiFi network , now I need to make MQTT gateway connected trought LAN or WiFi to the raspberry where is running Domoticz ? I had nodeMCU will it work ? Thanks much

                                    EfflonE Offline
                                    EfflonE Offline
                                    Efflon
                                    wrote on last edited by
                                    #25

                                    @warmaniac the sonoff works just like any sensor except its configured as a gateway since that is what is needed for esp8266+mysensors . Mqtt or ethernet/wifi is just a matter of taste and your setup, skip mqtt if you don't have anything else using it.

                                    warmaniacW 1 Reply Last reply
                                    1
                                    • EfflonE Efflon

                                      @warmaniac the sonoff works just like any sensor except its configured as a gateway since that is what is needed for esp8266+mysensors . Mqtt or ethernet/wifi is just a matter of taste and your setup, skip mqtt if you don't have anything else using it.

                                      warmaniacW Offline
                                      warmaniacW Offline
                                      warmaniac
                                      wrote on last edited by
                                      #26

                                      @Efflon said in 💬 Sonoff relay using MySensors ESP8266 wifi or mqtt gateway:

                                      @warmaniac the sonoff works just like any sensor except its configured as a gateway since that is what is needed for esp8266+mysensors . Mqtt or ethernet/wifi is just a matter of taste and your setup, skip mqtt if you don't have anything else using it.

                                      I want to use standalone Sonoff (one device) than I must install broker (Mosquito) on my raspberry where is Domoticz running ? And how can I add than that device or how can this setup looks like.

                                      EfflonE E 2 Replies Last reply
                                      0
                                      • warmaniacW warmaniac

                                        @Efflon said in 💬 Sonoff relay using MySensors ESP8266 wifi or mqtt gateway:

                                        @warmaniac the sonoff works just like any sensor except its configured as a gateway since that is what is needed for esp8266+mysensors . Mqtt or ethernet/wifi is just a matter of taste and your setup, skip mqtt if you don't have anything else using it.

                                        I want to use standalone Sonoff (one device) than I must install broker (Mosquito) on my raspberry where is Domoticz running ? And how can I add than that device or how can this setup looks like.

                                        EfflonE Offline
                                        EfflonE Offline
                                        Efflon
                                        wrote on last edited by
                                        #27

                                        @warmaniac You dont need mqtt/mosquitto. Just follow the guide at https://www.domoticz.com/wiki/MySensors for adding a "MySensors Gateway with LAN interface (Ethernet)" then follow the ethernet sketch here https://www.openhardware.io/view/318/Sonoff-relay-using-MySensors-ESP8266-wifi-or-mqtt-gateway

                                        warmaniacW 1 Reply Last reply
                                        0
                                        • EfflonE Efflon

                                          @warmaniac You dont need mqtt/mosquitto. Just follow the guide at https://www.domoticz.com/wiki/MySensors for adding a "MySensors Gateway with LAN interface (Ethernet)" then follow the ethernet sketch here https://www.openhardware.io/view/318/Sonoff-relay-using-MySensors-ESP8266-wifi-or-mqtt-gateway

                                          warmaniacW Offline
                                          warmaniacW Offline
                                          warmaniac
                                          wrote on last edited by warmaniac
                                          #28

                                          @Efflon

                                          Tried LAN sketch after adding new hardware in domoticz this error occurs

                                          2017-04-06 06:28:07.230 MQTT: Connecting to 192.168.2.209:5003
                                          2017-04-06 06:28:07.335 Error: MQTT: disconnected, restarting (rc=2)
                                          

                                          after that Sonoff blik twice. What may be wrong ?

                                          Edit:

                                          Understand now , it is added as classic mysensor LAN gateway , now working fine ! I tried to do it complicated way , but it was easy :D

                                          2017-04-06 06:30:29.756 MySensors: trying to connect to: 192.168.2.209:5003
                                          2017-04-06 06:30:30.757 MySensors: connected to: 192.168.2.209:5003
                                          2017-04-06 06:30:30.758 MySensors: Gateway Ready...
                                          2017-04-06 06:30:30.762 MySensors: Node: 0, Sketch Name: Sonoff ethernet
                                          2017-04-06 06:30:30.763 MySensors: Node: 0, Sketch Version: 1.0
                                          2017-04-06 06:30:30.769 (MQTT) Light/Switch (Light)
                                          2017-04-06 06:30:31.778 MySensors: Gateway Version: 2.1.1
                                          2017-04-06 06:30:31.779 MySensors: Gateway Version: 2.1.1
                                          
                                          2017-04-06 06:31:11.939 User: Admin initiated a switch command (87/Sonoff-1/On)
                                          2017-04-06 06:31:11.942 (MQTT) Light/Switch (Sonoff-1)
                                          2017-04-06 06:31:12.789 (MQTT) Light/Switch (Sonoff-1)
                                          
                                          EfflonE 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          18

                                          Online

                                          11.7k

                                          Users

                                          11.2k

                                          Topics

                                          113.0k

                                          Posts


                                          Copyright 2019 TBD   |   Forum Guidelines   |   Privacy Policy   |   Terms of Service
                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • MySensors
                                          • OpenHardware.io
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular