Flash espeasy
Image can be found here.
To boot the sonoff into flash mode, press and hold the button while connecting it to power.
./esptool.py --port /dev/ttyUSB0 write_flash 0x000 ESPEasy_R120_1024.bin -fs 8m
Connect to wifi and configure
Connect to ESP_0 with password configesp and set up the wifi connection.
After connecting to wifi open the webinterface http://ip.of.sonoff/config and configure the name and unit number. The name of my sonoff is sonoff-s20.
Configure Hardware and Devices.
Enable rules: Tools – Advanced – Rules: Checked
Now there is a new menu entry named Rules
On Button#State=1 do
if [Relay#State]=0
gpio,12,1
else
gpio,12,0
endif
endon
Now you can toggle the relay with the button.
MQTT usage
I use the protocol OpenHAB MQTT. So I can subscribe these events:
# mosquitto_sub -h my.mqtt.server -t "#" -v
/sonoff-s20/Relay/State 1
/sonoff-s20/Relay/State 0
To switch on and off you can publish these messages:
# mosquitto_pub -h 192.168.1.99 -t "/sonoff-s20/gpio/12" -m "1"
# mosquitto_pub -h 192.168.1.99 -t "/sonoff-s20/gpio/12" -m "0"
It is also possible to change „Relay“ to „gpio“ and „State“ to „12“. In this case, the subscribed and published strings are the same, but the rules also have to be modified.
192.168.1.99 is the IP-Address of the MQTT-Server (for example, mosquitto).
openHAB configuration
After configuration of the mqtt-binding in openhab.cfg I created a new item-file
items/sonoff.items:
Switch sonoff01 "Sonoff Socket" {mqtt=">[mosquitto:/sonoff-s20/gpio/12:command:ON:1],>[mosquitto:/sonoff-s20/gpio/12:command:OFF:0],<[mosquitto:/sonoff-s20/Relay/State:state:MAP(mqtt.map)]", autoupdate="false"}
I also created the file transforms/mqtt.map
0=OFF
1=ON