Got a few ITEAD Sonoff WiFi switches to automate my home. Why use the boring software, so I tried to hack the switches. This is a reference manual for me, but quite useful for anyone else if they want to use micropython, mqtt, web server and control the switches.
- Sonoff switch
- VCP: FTDI Cable
- yeah, 5x pin headers to solder on the board
- few jumper wires for debugging
Make sure the FTDI cable is set to 3V which is very important. Then connect the cable as detailed in the table.
|Programmer||Sonoff (counting from the switch to bottom)|
The easiest way to flash the firmware is to use the nodemcu-flasher available. Unfortunately available only for windows. The micropython-flash image esp8266-20170108-v1.8.7.bin can be downloaded from the website. On the config tab add the image. Sometimes it helps to first flash a blank image to the WiFi switch.
Install mosquitto, an open source MQTT broker. It is very easy to install, follow the installation instructions in the link or copy paste the following commands.
MQTT service is started and running on the machine. I will deal with the basic programming initially. May be later, MQTT will be tightened up with security like auth, base64 encoded message etc.
there are few things to know first hand. That would be, the pins for the physical objects on the switch. There is a relay, led and a button. I want to use the button in case I m not connected to internet to be able to toggle the switch. Led is concealed inside the housing, so doesn’t matter. Relay is very important which will be switching the on off the device that is connect. This pin configuration is specific to micro python firmware. In LUA it might be different.
PIN 12-----------------replay PIN 13-----------------LED PIN 0------------Button
Diving in to the code, there are only three parts that are done. One is the variable that is used around in all functions declared as global to keep the state known at all times. Then connect to mqtt and subscribe to a certain topic. Here I m controlling the switch for the TV system. The call back function will handle if the switch should be turned off or on. This means, just a if loop with toggling the pin 12 where the relay is connected and storing the current action in the global variable.