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]

Update @ 20th February 2018  –  There’s now a newer post available on using TASMOTA, which I’d recommend as a follow-up to this one.

[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:-

#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 = 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).
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

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”]

PREFACE – Theo has put a lot of hard work into TASMOTA and continues to update and improve the package at a quite incredible rate.  For instance, Theo changed the major revision number from “4” to “5” on the 25th of April, 2017.  Between then and the time of adding this note (19th of July, 2017), he has made 92 updates that warranted an entry in the release notes and 42 of those changes were additions.

This article first appeared in April of 2016, so it is fairly ancient.  The basic information here (such as the three main methods for interacting with your Sonoff) is still correct, but you need to realize that any references to menu items or MQTT commands have very probably changed since it was first written.  I just can’t keep up with Theo.  🙂

Please do have a quick look at the “_releasenotes.ino” file in the sonoff subdirectory of the Sonoff-Tasmota package to get an idea of what recent changes there are, as well as checking the package README.md for the major news (ie:- Theo has recently added Alexa support to Sonoff).

Having said that, I hope these articles will help you to become more familiar with TASMOTA and with the Sonoff devices themselves.  Please read on…


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

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.


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 = 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:-


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

light 0

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

power 1

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

light 2


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 = 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

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).


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 = 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

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.