Making Sonoff switch smarter

I’ve got a great Sonoff TX-US (2-gang) wall-light switch. It looks good, and it’s sorta smart. But can I make it smarter?

Step 1 — install Tasmota. Step 2 — use MQTT. Right?

Well, it works, but only until your home automation hub/server fails, and takes your MQTT server with it. Is there a way to bullet-proof your setup in case of an emergency?

There is, thanks to Tasmota!

First of all, let’s disassociate button presses from power switching. Why? I prefer a smarter scheme, not the default dumb toggle. E.g. in the kitchen:

  • motion sensor turns countertop lights on — but only if it’s dark (median <110 lux during the last minute)
  • motion sensor restarts countdown timer if lights are already on
  • a long press on any of the two buttons turns ceiling lights on
  • a short press on any of the two buttons turns all lights off (rarely used, everyone is used to stuff working auto-magically

Here’s the setup. First, internal Tasmota config:

Backlog ButtonTopic 0; SwitchTopic 0; SetOption1 1; SetOption11 0; SetOption13 0; SetOption32 10; PowerOnState 0

Then a rule (MQTT topic structure should be obvious):

RULE1
ON Button1#State=2 DO publish home/kitchen/button/main/1 OFF ENDON
ON Button1#State=3 DO publish home/kitchen/button/main/1 ON ENDON
ON Button2#State=2 DO publish home/kitchen/button/main/2 OFF ENDON
ON Button2#State=3 DO publish home/kitchen/button/main/2 ON ENDON

This rule redefines what a button does. Instead of toggling the power it sends an MQTT message. But what if the MQTT server fails? For that unlikely case we have another rule, it enables rule 1 only when MQTT is there.

RULE2
ON mqtt#connected DO Rule1 ON ENDON
ON mqtt#disconnected DO Rule1 OFF ENDON

And voila, we have a smart light switch, with fallback.