Sunday, 9 July 2017

Syncing two Sonoff’s for 2-way light switching

For as long as I've been playing with home automation, I've wanted a straight forward low-cost solution for replacing standard light switches. Although I have several Z-wave dimmers and Aeon Labs touch panels, these work out to be $180 NZD each! At least in NZ, the common 2-way and 3-way light circuits have the mains coming in on one switch and the load connected to another. The two switches are connected together as shown below.
3-way_switches

While the excellent Fibaro dimmers allow for 2-way circuits, @ $139 NZD ea., that's not a cost effective long-term solution either. If you see this blog post, the author of Espurna firmware for Sonoff has written a post on how he achieved it using devices with two SPDT relays like the Electrodragon.

My solution is even simpler (?) and leverage's the rules capability built into ESPEasy along with another very cool feature. There are several ways to do this and the first is using UDP as the ESPEasy devices can know about and talk to each other without the need for a home automation controller!

To enable this, you need to define three things;
  1. Turn on rules in the advanced menu.
  2. Enable UDP and define a port (I used 65432).
  3. Ensure your device has a unit number between 1-32.
After that, reboot your device and on the main page at the bottom you should see that the devices have discovered one another. Cool! To leverage UDP, you would use the SendToUDP command from the command reference guide here https://www.letscontrolit.com/wiki/index.php/ESPEasy_Command_Reference however I found UDP to be decidedly intermittent so I'm recommending a more reliable method below by publishing MQTT commands to a broker.

In my early testing, both units come on and off at the same time which is great. Controlling either unit with MQTT turns on the other at the same time. To my mind, this is even better than a standard 2-way circuit as both status LED's for the chosen light switch/LED combo are on when the light is on.

As the Sonoff's have a spare GPIO on pin 14, I'll bring this out externally to control a LED built-in to the stainless steel push button I'll be using or maybe I'll just leave the LED around the button on all the time (dimly).

## Sonoff1 ##
on button#state do
   if [relay#state] = 0
     GPIO,12,1
   else
     GPIO,12,0
   endif
endon

on relay#state do
if [relay#state] = 1
gpio,13,0
Publish /sonoff2/gpio/12,1
else
gpio,13,1
Publish /sonoff2/gpio/12,0
endif
endon

## Sonoff2 ##
on button#state do
   if [relay#state] = 0
     GPIO,12,1
   else
     GPIO,12,0
   endif
endon

on relay#state do
if [relay#state] = 1
gpio,13,0
Publish /sonoff1/gpio/12,1
else
gpio,13,1
Publish /sonoff1/gpio/12,0
endif
endon


My video on this working using MQTT below:


Great video on how to use ESPEasy rules here: