How to do a Sonoff memory upgrade

Jonathan Oxer, over at SuperHouseTV, has been running a series of video episodes on the Sonoff product line recently and I really recommend his latest.  The theme of the video is Sonoff-specific hints and hint #1 is how to upgrade the memory chip in a Sonoff.  Jonathan does a great job of demonstrating how to remove the chip with nothing more than “a big, old, clunky soldering iron” and a screwdriver.  A picture is worth a thousand words, so you need to multiply that by whatever the frame rate of a YouTube video is.  Watch it!  It’s worth it.

Another Sonoff Family Member…

…and another Open Source package to run it.

I only recently noticed that ITEAD Studios have added a light switch to their Sonoff line-up.  Sonoff Touch from ITEADThe switch comes in either EU or US single-gang switch-plate sizes and has a glass front panel with a capacitive touch switch.  Inside there’s an ESP8285 module providing remote services via ITEAD’s EweLink cloud application.

There aren’t too many hardware details available on the Sonoff Touch at the moment (what sort of PSU is utilized, or even whether it’s a relay or a triac based device), but people have already started hacking it (no doubt spurred on by a statement in the comments section of the product page that this device “can’t be reprogrammed”).  David Pye seems to be first out of the gate with his (PubSubClient) MQTT implementation; not just identifying GPIO0 as the pin connected to the touch-switch, but also providing short write-ups (with photos) on how to prepare the device for programming, configuration and usage, but also providing bonus “long-touch” and “short-touch” modes in his firmware.

Note that, unsurprisingly, the Sonoff Touch requires that a neutral lead be available in the existing switch box, as well as the switched live lead.  This is something you need to check‡ before ordering a bunch of these (it’s very common for only the live lead to be available).

David’s additional switch handling looks like it might open up quite a few possibilities:-

  • Add an on-time limit for specific lights.
  • Control actual on/off based on time of day.
  • Control on/off by ambient light level (assuming you have MQTT capable sensors).
  • Put unit into OTA mode (ie:- limit reprogramming to those with physical access).
  • Use “long-press” to signal MQTT to switch all controllable lights in room on/off.
  • Additional ten-second press mode for all controllable lights in house on/off.

Seems like you could have tons of fun with this.  Nice one, David!

 

Hint – Don’t check a bathroom or toilet light switch and assume that all of the other switches in your house will be the same!

Tinkering with the Sonoff TH (by Tinkerman)

Xose Pérez has a great blog (Tinkerman.cat) with lots of hardware projects (as you’d expect from the title).  He’s also heavily into the ESP8266, so it comes as no surprise that he’s already got his hands on the latest offerings from ITead Studio, the Sonoff TH10 and TH16 high power switches.

Annotated board (bottom)Of course, it would be no fun at all if Xose just reviewed the units, but we can trust him to go a lot further than that.  In a recent article, he shows us round the interior of the units (highlighting the differences and the improvements between these new versions and the smaller original) and then demonstrates how to add i2c functionality to the existing sensor socket.  With his small modification, the Sonoff TH goes from being able to interface with either a DS18B20 (One-wire temperature sensor) or AMD2301 (DHT22 style humidity sensor) to being able to handle the whole gamut of i2c enabled input and output devices.

While we’re looking at Xose’s ESP8266 stuff, you might also like to check out his BitBucket repository.  You’ll find an alternative firmware version for the Sonoff series (named “Espurna”), which is probably where the code for the i2c mod will end up, as well as a WiFi manager library (named “JustWifi”), which features automatic AP connection based on signal strength.  There’s a ton of other, interesting stuff in there; some ESP-based and some not.  Definitely a treasure trove.

 

 

Weekend Reads [2016/5/28]

Another eclectic electric collection for your delectation.

One of Theo’s more recent updates is to add a couple of photos to the README.md for the Sonoff-MQTT-OTA-Arduino project (scroll down to the bottom of the page) of a (broken) Kaku 433Mhz mains switch which he has gutted and replaced with an ESP8266 to make a Sonoff look-alike.  I can’t find any further details of the project, but from what we can see from the photograph (click to enlarge) and what we already know of the Sonoff, it should be relatively easy to duplicate this if you have any of these older Kaku units gathering dust.

Using “TASMOTA” [Part – 2, MQTT]

[Apologies for those of you have been checking back in regularly for this second article on using Theo Arends’ Sonoff-MQTT-OTA-Arduino package.  Not only has Real Life™ been getting in the way, but I’ve purposely been delaying hitting the big, red “publish” button until I could sort out a nagging little problem I’ve been having (more on that later).  Anyway, here we go with part two…]

In the previous article, we looked at how to access some of the features of TASMOTA (Theo Arends’ Sonoff-MQTT-OTA-Arduino package) using the button/LED and serial-console interfaces.  In this article we’ll take a look at controlling the unit using MQTT.

[…and if you don’t really know what MQTT is, or what it does, Elliot Williams has recently published a clear, easy to read and easy to understand article on Hackaday which is worth looking at…]

The main selling point (other than the extraordinarily low price) of the Sonoff is the fact that it is controllable across the ‘net.  Unfortunately, ITEAD Studios have tied control of the device to their own cloud service which, while it may be great for most people, doesn’t work for those of us who are still using “dumb” phones and who don’t have the option of using a service such as Oogleg’s “voice” to get around that limitation.  Theo’s firmware implements MQTT on the Sonoff which, while it doesn’t help my “dumb” phone, does mean that I can use existing devices on my own network to control it.  I already have a couple of MQTT servers on the local network providing time services to various battery-powered, ESP8266 enabled sensors and collecting data (temperature, humidity, barometric pressure, battery voltage) from them.  It would be a trivial matter to have the internal MQTT servers push that data to one of the free data aggregation services out on the ‘net and only a little more work to make the MQTT interface available through the firewall for external access when we’re away from home (Okay, a lot more work to do it properly 🙂 ).  In my case, the need for MQTT is purely pragmatic; it’s a neat device, but I need MQTT to get it to work without a smart-phone.  For others, there may be a reluctance to entrust data access and control to a cloud service which might disappear at some time in the future.  Whichever it happens to be, Theo’s package “hits the spot” and broadens the possible usage window for the Sonoff (which, long term, is good for ITEAD’s sales, too).

In the previous article we already saw how to set up the “topic” keyword to give your Sonoff devices individual addresses, as well as using “grouptopic” to set a group address to which all devices will listen.  Before you can use MQTT though, you need to configure the MQTT broker (server) details for your network, too.  The recommended way of doing this (unless you have a gazillion MQTT servers on multiple networks) is to simply compile-in the hostname/IP and port number when you initially build the package.  If you’re using Theo’s original package, edit the user configurable details at the top of the sonoff.ino file and change these lines:-

// MQTT
#define MQTT_HOST "sidnas2"
#define MQTT_PORT 1883

…to point to your own MQTT server address and port (if you’re using the version which I put up on GitHub with the function defines added, these settings broken out into user_config.h instead).

You can still change this setting (along with most others) from the serial console, or from MQTT, later on.  Using the serial console (as per the previous examples), you can see that the Sonoff unit automatically reboots after the change:-

host
HOST = blind.nthld.org

host hazeltonrig.nthld.org
HOST = hazeltonrig.nthld.org

ets Jan 8 2013,rst cause:1, boot mode:(3,7)
chksum 0x42

Project sonoff (Topic 2F-toilet-gas-sensor, Fallback DVES_0CB0CB, GroupTopic calling-all-units) Version 1.0.6 (Boot 4, SDK 1.5.1(e67da894))

First we used the “host” command without arguments to interrogate the unit for the current setting. Secondly, we used the “host hazeltonrig…” command to change the compiled-in default. TASMOTA then automatically saves the new value to non-volatile memory and restarts the ESP8266 using the newly updated parameters.

Mosquitto notes

Before we start using MQTT let’s just take a brief look at Mosquitto and the utilities which come bundled with it, mosquitto_sub and mosquitto_pub.  If you’re not using Mosquitto as your MQTT server, feel free to skip this section.

As you’d expect from the names, mosquitto_sub is a command-line utility which allows you to subscribe to a topic, while mosquitto_pub allows you to publish.  They are invaluable tools when setting-up and debugging MQTT installations, allowing you to send arbitrary data and commands and to monitor the output.

You can also install the Mosquitto package on a desktop or laptop machine to make these applications available when you just want to connect to a remote MQTT server on some other machine (both utilities accept a “-h” option with an argument specifying the hostname to connect to and a “-p” option with a numeric argument to specify the port number).  However, typing in the full command names, plus options and arguments can get tedious very quickly, so I’d suggest adding aliases for both commands.  These can be added to your .bashrc (assuming you’re using the common, Bourne Again SHell) to make your life a little easier. Here’s an example (you need to customize it for your specific installation):-


##
## Aliases for Mosquitto utilities.
##
## Simple alias for server on this machine.
alias mp=/usr/bin/mosquitto_pub;
alias ms=/usr/bin/mosquitto_sub;
##
## Aliases for server on remote machine.
## (You can comment-out this whole section if you
## only use the server running on this machine).
MQTT_SRV="hazeltonrig.nthld.org";
MQTT_PRT=1883;
alias rmp="mp -h ${MQTT_SRV} -p ${MQTT_PRT}";
alias rms="ms -h ${MQTT_SRV} -p ${MQTT_PRT}";
unset MQTT_SRV MQTT_PRT; ## Prevent pollution.
##
## End of Mosquitto aliases.
##

In the .bashrc excerpt above, we are first setting “mp” to be an alias for the full pathname of the mosquitto_pub command and then doing the same for “ms” and mosquitto_sub command.

You only need the second part (from the line “## Aliases for server on remote machine.”) if you are running the MQTT server on a different machine to the one where you’ll be running the mosquitto_pub and  mosquitto_sub commands.  If you do want to use it, you’ll need to change “hazeltonrig.nthld.org” (and possibly the 1883 port number) to point to the MQTT server on your network.  The aliases here build on the “mp” and “ms” aliases which we’ve already defined to provide “rmp” (“r”emote “mp”) and “rms” to access our remote server with minimal typing.

The “unset” command simply deletes the MQTT_SRV and MQTT_PRT variables to prevent any unwanted clashes if those names are used by you later.

At the end of that, you can now simplify and shorten your commands.

From:- /usr/bin/mosquitto_sub -h hazeltonrig.nthld.org -p 1883 -t stat/#

    To:-    rms -t stat/#

 

Using the Mosquitto utilities

Now that we have our server defined and some aliases set up, let’s go ahead and dive into using MQTT with the Sonoff and TASMOTA.  I’m going to assume at this point that, if you already have an MQTT broker (server) set up, you basically know how the publish/subscribe model works.  Let’s also assume that our MQTT server (the machine running Mosquitto) is called “hazeltonrig” (as we saw above) and that we’re actually using a laptop to type in these examples and display the output.

Because our laptop is not the MQTT server, we need to use the remote aliases which we set up above to channel all of our publish and subscribe requests through “hazeltonrig”, because for the most part, we are actually interested in interacting with a third machine, the Sonoff module.  So, just the same as with the serial console, let’s start off by getting the status from the device.  The easiest way to do this is to use an MQTT wildcard and listen in on all status broadcasts from all devices on the network:-

rms -t "stat/#"

Going back to our aliases, we can see that this actually expands to the command:-

/usr/bin/mosquitto_sub -h hazeltonrig.northld.org -p 1883 -t "stat/#"

The word “stat” is the top-level topic used by TASMOTA clients to publish their status data.  The “#” is a wildcard, meaning match-anything-from-here onwards.

What happens when you type in this command?  Well, unless your Sonoff happens to be transmitting some status information at the time you hit <CR>, absolutely nothing.  You won’t get a prompt and you won’t see any text on the screen after the command itself.  Not very exciting, but you have just started a subscriber process which will sit there quite happily and spit out any data that comes along with the “stat/” topic header.

If you power-cycle your Sonoff at this point, you  will see a couple of power-up status messages displayed on your screen; something like:-

Sonoff switch
1.0.6
DVES_0CB0CB

You’ll also notice that, if you still have the serial monitor connected via the USB<->TTL converter, you will start seeing status messages appearing on your screen when you type in virtually any command.  So, if you type “power 1” into the serial monitor, you’ll get output on the serial monitor itself and you’ll also see the word “on” appear in the window where your subscribe command is running (actually, even if you don’t type in commands, the subscribe window will still show messages at power-up, restart or power-down events; for instance, pulling the plug on the Sonoff will produce an “offline” message approximately 10 seconds after the unit is switched off).

You could type a <CTRL>z to put the command into background and carry on typing MQTT commands into the same window where you’ve just started your subscriber process, but that would begin to get a little confusing once that process started to return data, so at this point I’d recommend opening a new window to be able to enter further commands.

Now we need to command the Sonoff to send out some status, so that we can read it with our patiently listening subscriber process.  For this we use our remote publish alias, “rmp”:-

rmp  -t  "cmnd/2f-toilet-gas-sensor/status"  -m  ""

This expands to:-

/usr/bin/mosquitto_pub  -h  hazeltonrig.nthld.org  -p  1883  -t  "cmnd/2f-toilet-gas-sensor/status"  -m  ""

…which means, publish the command “status” (request status) to the device currently known as “2f-toilet-gas-sensor”.  The -m “” part of the command is simply a null argument to keep mosquitto_pub happy, otherwise it will print a usage summary to try and persuade you that you need to use a message (-m) as an argument to any topic (-t).

The output you’ll see in your subscriber window from the status command with a null (-m “”) option will be something like:-

1.0.6, 2f-toilet-gas-sensor, POWER, 0, 9

This is telling you that the Sonoff is running firmware version 1.0.6, has a topic (addressable name) of “2f-toilet-gas-sensor”, that the last sub-command was “POWER” and the status of the relay is off (“0”). The last “9” indicates the timezone which is currently configured (in this case GMT+9 for Tokyo).

Up Next…

This article has been languishing in the deeper recesses of the WordPress draft cloud for far too long, and has a lot of information for the reader to digest, so I’m going to save some of the other MQTT commands for yet another article and push the big, red “publish” button to get this one out into the wild.

In the next part, we’ll use some of the more useful commands which Theo has provided and look at the difference between normal and group commands.

 

Using Theo Arends’ Sonoff/MQTT Package [“TASMOTA”]

This is a continuation to the previous post on updating your Sonoff to use Theo Arends’ Sonoff-MQTT-OTA-Arduino package.  Theo’s package has so many features that it takes a little time to get familiar with it.  I’ve always found that a couple of examples are worth more than a scad of explanation (would that the Unix manual pages had made an “EXAMPLES” section mandatory), so rather than leave everyone floundering around on their own, I thought I’d note down some of the examples which I’ve found to work so far.

Before we start, you should realize that there are three main ways to interact with the device:-  the button/LED pair,  the serial interface (which we used to upload the firmware in the previous post) and MQTT.  All of these interfaces interact with each  other to some extent.  So, for instance, pressing the button to toggle the state of the relay will flash the LED to indicate a successful update and automatically generate output to the serial port as well as an MQTT message.  Sending the unit an MQTT command to toggle the relay will also generate a state-change message to the serial port and flash the LED.  Using the serial port to toggle the state of the relay will automatically generate an MQTT state-change message and flash the LED.  So we effectively have three input/output channels with the input from any one of them producing status output to all three.

The simplest of the input methods is the button.  A change in the number of sequential button presses, or in the duration of the press, will produce a limited number of state changes.

  • Pressing the button one will toggle the relay state.
  • Pressing the button twice in a row will toggle the relay state twice.  🙂
  • Pressing the button thrice in a row will initiate Smart-Config mode for 100-seconds (to allow for more complex configuration changes to be made from an Android device).
  • Pressing the button four times in a row will initiate  an over-the-air (OTA) update from a previously configured source.
  • Finally, pressing the button and holding it down for more than 4-seconds will reset the Sonoff configuration to the compiled-in defaults and initiate a restart of the device.

The most versatile input method is actually the serial console, but to activate the console you need to disconnect the device from the mains and take off the covers to gain access to the serial header (programming) pins.  Obviously this is most useful with a new device when doing the initial configuration;  it’s not really practicable once the device has been reassembled and is in use.  Having said that, this is the method I’d recommend  for doing your own initial exploration of the Sonoff-MQTT-OTA-Arduino firmware.  Once you’ve completed the initial installation of the firmware, take a few minutes while the USB<->TTL converter is still connected and use the Arduino-IDE “Serial Monitor” (under the “Tools” pull-down menu) to interact with your Sonoff.  Make sure that the serial monitor window has focus and that the cursor is flashing in the input sub-window at the top.

I’m going to emphasize here once again that there shouldn’t be anything at all, other than the serial connector leads from the USB<->TTL converter, plugged into your Sonoff at this point.

When your Sonoff first boots into Theo Arends’ Sonoff-MQTT-OTA-Arduino firmware (hereafter referred to as “TASMOTA”) you’ll see a very brief status message something like this:-

NAME = Sonoff switch
VERSION = 1.0.6
FALLBACKTOPIC = DVES_0CB0CB

Where the version number is the version of TASMOTA and the fallback-topic is the “if-everything-else-fails” way of addressing this specific module from MQTT.  We’ll touch on that latter function again briefly, later on.

You should now be able to type in commands in the serial monitor window and see the results displayed there directly.  A simple carriage return will produce a “usage” message with all of the possible commands listed (in l single line which, unfortunately, will scroll off the side of the serial monitor window):-

SYNTAX = Status, Upgrade, Otaurl, Restart, Reset, Smartconfig, SSId, Password, Host, GroupTopic, Topic, Timezone, Light, Power

Theo has a couple of nice tables in the README of his GitHub repository which explain each of these, so I’m going to limit myself to a couple of the more useful ones here.

Status

This command does what you would expect, giving you some information about the current state of your Sonoff module.  This command takes options though, so you get different results depending upon whether you run the command without any options at all, or with the different options “1” or “2”.

status
STATUS = 1.0.6, sonoff, POWER, 0, 9


status 1
STATUS = sonoffs, DVES_0CB0CB, http://Your-OTA-Server.And.Domain:80/api/arduino/sonoff.ino.bin, Your-SSID, Your-Passwd, Your-MQTT-Server.And.Domain, 1, 11

status 2
STATUS = Version 1.0.6, Boot 4, SDK 1.5.1(e67da894)

As you can see, “status” without any options is succinct.  It shows the TASMOTA version, the current addressable topic name (for this module when using MQTT) which defaults to “sonoff”, the sub-topic name (in this case “POWER”), the relay status (0 = off) and the current timezone (9 = JST/Tokyo).

Status with the “1” option gives us verbose output on the current configuration of the unit.  It shows the current addressable group-topic (“sonoffs”).  The group-topic is used to address all Sonoffs on the local network to send an MQTT command or request which all of the active devices will execute (again, more on this later).  Next comes the fall-back module name for MQTT addressing, next the full URL for the OTA server, the SSID for your access point, the password for your access point, the hostname for the MQTT server.  The last two numbers on the end are the heartbeat count and the configuration save count.

Status with the “2”  option is somewhat less verbose and provides revision information for TASMOTA itself (1.0.6),  the ESP8266 boot version (4) and the ESP8266 SDK version (1.5.1).

Light & Power

The “light” and “power” commands are synonymous and do exactly the same thing – control the relay.  The commands can be used with or without options.  Used without an option they will display the current status of the relay:-

power
POWER = Off

Used with an option of “0” they will switch the relay off:-

light 0
LIGHT = Off

Used with an option of “1” they will switch the relay on:-

power 1
POWER = On

…and with an option of “2”they will toggle the state of the relay :-

light 2
LIGHT = Off

Topic

The use of “topic” as a command name is a slight misnomer, as this command only shows or changes the part of the MQTT topic which is used too address individual Sonoff units.  For instance, when using the “power” command from MQTT, your command line might look something like this:-

cmnd/sonoff/power 2              -- Toggle the state of the relay.

The “cmnd” specifies that the topic is a command.  The “power” specifies that the command is specific to relay control.  The “sonoff” part of the topic string specifies the actual address of the Sonoff unit (and Theo uses “sonoff” as the default, compiled in,  address).  You can also think of this as being the name assigned to each individual unit.

The useful part of this is that the address can be changed, using the “topic” command, so all of your Sonoff units can be addressed individually (it wouldn’t be too useful if they couldn’t be).  So, going back to our serial console and the command line, we can display the current addressable name using:-

topic
TOPIC = sonoff

…and to assign a new addressable name to this specific unit, use the topic command with an argument:-

topic 2F-toilet-gas-sensor
TOPIC = 2F-toilet-gas-sensor

ets Jan 8 2013,rst cause:1, boot mode:(3,7)
chksum 0x42

Project sonoff (Topic 2F-toilet-gas-sensor, Fallback DVES_0CB0CB, GroupTopic sonoffs) Version 1.0.6 (Boot 4, SDK 1.5.1(e67da894))
NAME = Sonoff switch
VERSION = 1.0.6
FALLBACKTOPIC = DVES_0CB0CB

Note that the unit has not only accepted the new addressable name, but it has also automatically rebooted and the reboot header information shows the new name, the fall-back name and also the group name. Now this Sonoff unit will only respond to commands and requests which include the addressable name “2F-toilet-gas-sensor” in the topic string.  It will always respond to the “fallback” name of “DVES_0CB0CB” (derived from the unit’s MAC address) and will also respond to the current group addressable name of “sonoffs” (along with all of the other Sonoffs on the local network which have the same GroupTopic setting).

GroupTopic

As just noted, the “GroupTopic” is a special, common addressible name to which all Sonoffs with the same GroupTopic setting will respond.  The GroupTopic can be displayed and set in exactly the same way as the Topic:-

grouptopic
GROUPTOPIC = sonoffs

grouptopic calling-all-units
GROUPTOPIC = calling-all-units

ets Jan 8 2013,rst cause:1, boot mode:(3,7)
chksum 0x42

Project sonoff (Topic 2F-toilet-gas-sensor, Fallback DVES_0CB0CB, GroupTopic calling-all-units) Version 1.0.6 (Boot 4, SDK 1.5.1(e67da894))
NAME = Sonoff switch
VERSION = 1.0.6
FALLBACKTOPIC = DVES_0CB0CB

Again, calling grouptopic with no argument will display the current setting, while calling it with an argument will set the new group addressable name and automatically reboot the unit.  In the scenario shown above our unit will now respond to the unique address of “2F-toilet-gas-sensor” and also to the common group address of “calling-all-units”.

Next …in the next article we’ll delve into the MQTT command structure for TASMOTA.

 

No-Phone Sonoff stuff…

Sonoff with 3v3 USB programming adapter attachedI’m still quite enamoured of the Sonoff, from ITEAD Studios, despite the fact that I can’t get their eWelink to work with a tablet (the app refuses to register you unless you have a phone number — which my tablet doesn’t have, of course — and the excellent suggestion from Jon Chandler in the support forum, “use Oogleg Voice” may well work, but only for ‘merkins living in merika).  Sniffle.  I really shouldn’t be surprised, though; previous experience has shown that anything connected to female sheep usually leaves me with a cold, wet arm or a body to bury (or both).

Anyway, playing around with the unmodified device showed it as coming up on an IP address of 10.10.7.1 and happily assigning my laptop 10.10.7.2, but that’s as far as I got. All attempts to connect to it from the laptop failed miserably and I was also unable to get the Android “Smartconfig” app to do anything with it (if you’ve had success with any other method of getting the Sonoff to work with an Android tablet, please do leave a note in the comments section below).

So, I disconnected the wee beastie, ripped it apart and set about adding some pins to the existing programming header. A couple of warnings are in order here before I go any further, though:-

  • Your warranty is null and void if you start screwing around with your hardware (but you knew that already, right!?!)
  • You need to switch the unit off, unplug it from the mains and remove any cables connected to it before you start work (hopefully you knew that, too …if you didn’t, give yourself a sharp rap across the knuckles with wooden ruler and stop reading this right now!).
  • You should let the unit stand for half an hour or so to let the capacitors on the mains side of the PSU discharge before taking the top off.
  • DO NOT under any circumstances, touch any part of the PCB or component with a finger, soldering iron or USB-to-TTL adapter until all of the above instructions have been complied with.

ITEAD Studios have designed the board of the Sonoff with a socket for a programming header.

ITEAD Studios' Sonoff, with no clothes onAs it ships on the current version that header is unpopulated (this is ITEAD Studios telling you and me not to mess with their board …which is very sound advice).

The available schematic and the board itself don’t quite match up.  The schematic shows this as a five-pin header, but the PCB very obviously only has four holes.  What are we going to be connecting?  Well, we need pins for ground, receive data, transmit data and +3v3.  We need the latter simply because we do not want to attempt connecting another device (PC/Laptop/UFO-anti-gravity-generator, or whatever) to something which is already connected to the mains (do NOT do that!   I mean it!).  At any rate, four pins is all we need and four pins is what we’ve got.  We also need something that I’d been missing for a while …a 3v3 compatible USB<->TTL adapter (I finally gave in and ordered a couple a while back).

Adding the pins is fairly straightforward, but you should note that the ground pin is the one closest to the camera in the shot above, not the one with the squared-off hole.  The squared-off hole is the 3v3 connection.  Close-up shot of the unpopulated programming headerIf in doubt, get your meter out and test.  Before you put the pin header in place it’s also fairly easy to see the “star” connections from the ground connector to the ground plane around it.  The pin on the opposite end of the connector (next to the “J1” label and the big switch) is the 3v3 connector.

The long row of holes across the bottom of the picture is the connector for the 433MHz remote control board which is fitted to the Sonoff “RF” models, but missing on the base model.

With the pin headers in place, it’s not very easy to see either the silk-screen around pin 1 or the “J1” label, so it might be a good idea to label the ground pin using something like an indelible marker Programming socket populated with pinspen so that you’ll know which way round to connect the USB<->TTL converter leads the next time you take the top off.

Now that we have the header pins in place, we need some firmware to burn to the ESP8266 on the board.  I’d like to point you towards Theo Arends’ Sonoff-MQTT-OTA-Arduino package on GitHub.  It’s a drop in replacement which has a very versatile interface, allowing control of the relay, as well as status reporting and some configuration, from both MQTT and from the Arduino-IDE serial console window.  In addition, the button on the Sonoff will also provide manual control of the relay, start SmartConfig mode, start OTA update mode and force a reset to defaults, depending upon how many presses or how long you hold it down.  Changes to the relay state triggered by the button also automatically generate an MQTT state-change message, so your application should always be able to track state of external switch events.  Neat!  Theo also maintains a non-Arduino version if any of you masochists out there prefer fiddling with the SDK.

To update your Sonoff, make sure that no mains cables are attached, plug your 3v3 USB<->TTL converter cables onto the newly installed header pins (+3v3 to the pin next to the switch, ground to the pin next to the row of holes for the 433MHz module) and then hold down the switch button while plugging the USB connector into your computer.  Burn Theo’s firmware to the board using whichever method you are familiar with.

Note that the USB converters don’t usually supply enough current to run the ESP8266 when it fires up the radio (and it definitely won’t supply enough current to power the relay coil), so don’t be surprised if you see a couple of start-up messages followed by a crash or watchdog reset; just disconnect your USB cable and put the unit back together again (including all of the covers), before applying mains power.  Once it’s all back in one piece and powered on, you can check basic functionality by pressing the button.  A single press should produce an audible click from the Sonoff as the relay toggles state, followed by two brief flashes of the LED.  If you have “mosquitto_sub” available (or one of the Android MQTT monitor apps), you can fire it up and monitor the topic “stat/#” to see output from your newly updated Sonoff (assuming that you set up your own MQTT server details in the firmware defaults).  The mosquitto_sub command would be:-

mosquitto_sub -h Your.MQTT.Server -t sub/#

Use mosquitto_pub to publish an MQTT message to the cmnd/sonoff topic to have your Sonoff toggle the state of the relay:-

mosquitto_pub -h Your.MQTT.Server -t cmnd/sonoff/power -m "toggle"

Hopefully you’re now in business and your Sonoff is happily clicking away as you play with MQTT.

Update –  If you’re having trouble compiling Theo’s package (CFG_Default not defined, etc), I’ve put together a very slightly modified package with the function prototypes broken out into separate header files which should compile cleanly for most people.  It also has a minor pre-processor tweak which will reset the MQTT_MAX_PACKET_SIZE and MQTT_KEEPALIVE values to Theo’s recommended settings of 1024 and 120, without the need to modify the original PubSub library file.

Next …the next article in this series is a tutorial on using Theo’s new firmware.