How to Build and Flash ESPurna Open Source Firmware to Sonoff POW Wireless Switch

ITEAD Studio Sonoff family is comprised of various inexpensive ESP8266 WiFi power switch, and the company sent me two of their latest CE certified models with Sonoff TH16 + external temperature & humidity probe, and Sonoff POW to measure power consumption. I checked the hardware is the first part of the review, and used Sonoff TH16 to control a water pump with the stock firmware and Ewelink Android app in the second part. It works reasonably well, but it relies on the cloud, so if you lose your Internet connection or the service closed, you can’t control the relay manually anymore. Luckily, the UART pins are exposed on Sonoff switches so you can solder a 4-pin header and connect a USB to TTL to flash your own firmware.

Click to Enlarge
Click to Enlarge

Please don’t connect Sonoff devices to the mains when programming them, it’s very dangerous, instead the USB to TTL board will power the system, and will allow you to program the board safely. Later you’ll be able to update the firmware, if needed, over the network.

The next step is to select the firmware you want to use, and I’ve been advised two firmware for ESP8266, namely ESPurna specifically designed for Sonoff devices, and ESPEasy with a larger community of users. The latter may be usable to control the relay, but it has yet to support HLW8012 chip used to measure power consumption in Sonoff POW, so I decided to go with ESPurna.

That’s the description of the firmware from its bitbucket page:

ESPurna (“spark” in Catalan) is a custom C firmware for ESP8266 based smart switches. It was originally developed with the ITead Sonoff in mind. Features:

  • Asynchronous WebServer for configuration and simple relay toggle with basic authentication
  • Communication between webserver and webclient via websockets with secure ticket check
  • Flashing firmware Over-The-Air (OTA)
  • Up to 3 configurable WIFI networks, connects to the strongest signal
  • MQTT support with configurable host and topic
  • Manual switch ON/OFF with button (single click the button)
  • AP mode backup (double click the button)
  • Manual reeset the board (long click the button)
  • Visual status of the connection via the LED
  • Alexa integration (Amazon Echo or Dot) by emulating a Belkin WeMo switch
  • Support for automatic over-the-air updates through the NoFUSS Library
  • Support for DHT22 sensors
  • Support for the HLW8012 power sensor present in the Sonoff POW
  • Support for current monitoring through the EmonLiteESP Library using a non-intrusive current sensor (requires some hacking)
  • Command line configuration

I could not find firmware release for ESPurna, but Xose Pérez – the developer – has provided some basic instructions to build and flash the firmware to Sonoff. Those are not really detailed however, and it took me nearly a full day to successfully build and flash the firmware to Sonoff POW, mostly because I was not quite familiar with most of the tools used. So I’ve reproduced the step I went through in Ubuntu 16.04, and hopefully this can help people getting things done more quickly.

Let’s retrieve the source code, and enter the code directory first:


You can build the project with PlatformIO or the Arduino IDE. The instructions are for PlatformIO so that’s what I used. There are two ways to build the code with the project wither using Platform IDE for Atom and the command line, or simply using the command line. With insights, I ended up using the command line, but I’ll show both methods.

Setup PlatformIO IDE for Atom to build ESPurna

First, you’ll need to download PlatformIO IDE for Atom for your operating systems, and install it. For Ubuntu 16.04, I selected “Download .deb” for Linux and installed it through through Ubuntu Software program. Alternatively, after download, you can install it from the command line:


You can now start Atom program in Ubuntu dash, select Open Project, and browse for espurna/code directory to load the project we’ve just gotten from Bitbucket.

Click to Enlarge
Click to Enlarge

The tick button on the top left corner is to build the project, and the right button just under is to upload the firmware to the target board. But if we try to build the firmware now it will fail with an error about “espressif8266_stage”. That’s because we need to install Espressif 8266 (Stage) development platform. First we need to enable Developer mode in the IDE by going to the top menu to select PlatformIO->Settings->PlatformIO IDE, and checking “Use development version of PlatformIO“.

platformio_core_enable_development_version
Click to Enlarge

Now install PlatformIO shell commands from either a system Terminal, or PlatformIO IDE terminal (PlatformIO->Terminal->New Terminal):


and finally install ESP8266 development platform:


At this point you can click on the tick icon to build the default “node-debug” environment, a build output window will show in the IDE, and quickly disappear if the build is successful.

Setup PlatformIO via Command Line to Build ESPurna

If instead we want to use the command line we can install the latest pip version, the developer version of PlatformIO, and the staging version of ESP8266 development platform:


You can check the build environment is set properly by running the following command in espurna/code directory:


It will automatically download, build and install all dependencies and build for “node-debug” firmware for NodeMCU board. If it is successful, it will end as follows:


So I find the command line option much more easy and straightforward.

Build ESPurna for Sonoff POW

However, we are not using NodeMCU board here, but Sonoff POW, and there are two environments defined just for that:

  • sonoff-pow-debug – Build firmware to flash over serial
  • sonoff-pow-debug-ota – Build OTA firmware to upgrade the firmware over the network

The parameters for each environment are all defined in platformio.ini. First we need to build sonoff-pow-debug environment:


But it failed with an error message related to hlw8012 library:


I reported the issue on Bitbucket, but the main developer could not reproduce the issue. Eventually I found out that it could be a PlatformIO bug, as the system does not recursively checking for includes outside of main.ino. So I added <hlw8012.h> in the main.ino as follows:


and the build could complete:


Since we’ve already changed the code, you may also consider changing “#define ADMIN_PASS  fibonacci” in code/src/config/general.h to use a different default password. The password can also be changed in the web interface, but this makes sure you won’t have a device somewhere with the default password common to most users.

Flashing Firmware to Sonoff POW

Now that we’ve made sure the firmware could build, it’s time to flash it to the device.

First we need to setup some udev rules to allow flashing over serial:

Now connect the USB to TTL to a USB port on your computer, press the button (connected to GPIO0) on Sonoff POW for several seconds until both LEDs are off to make sure you are in bootloader mode, and start flashing with:


Success! Great. If you have your own firmware to flash it may be useful to know the actual command used to flash the firmware was:

Building and Flashing the ESPurna filesystem

Wait! We’ve just flashed the firmware, isn’t it all? Nope, as the webserver files are stored in another partitions, and compressed in a single index.html.gz file for better performance. The exact reasons why are further explained here.

We’ll need Node.js and gulp command line client:


Now inside espurna/code folder , we can check if building the file systems works with two commands:


Here my successful gulp attempt:


Finally, we can run the following (which also runs the two commands above) to flash the file system to the board, after entering bootloader mode by pressing the button:


Now that’s done.

A Quick look at ESPurna Web Interface

ESPurna firmware and filesystem has now been flashed to Sonoff POW. But does it work?

Click to Enlarge
Click to Enlarge

I can see a new SONOFF_POW_XXXXX access point, so that does look good. I can connect using the default password “fibonacci”, then go to my web browser to access http://192.168.4.1, and login again with admin/fibonacci credentials.

Click to Enlarge
Click to Enlarge

ESPURNA 1.03 interface goes to the status menu first, and there I can turn on and off the relay remotely, and check the power consumption in watts, which remains at 0 watt since I have not connected it to the mains yet. It’s also possible to turn the relay on and off with the button, and there an option to select whether to turn on or off the relay at boot time, which is great since I need it on at all times.

The web interface also allows you to change general parameters including the hostname and password, as well as enable or disable the HTTP API (disabled by default). The WiFi section is used to connect to up to 3 wireless routers, the MQTT section lets you configure an MQTT (Mosquito) broker, and the power section is used to calibrate the power monitoring device.

If you just intend to check the current power consumption and turn on and off the switch with your phone, you don’t have to do anything else. But I’d like to find some ways to draw daily, weekly, monthly charts of my office power consumption using either MQTT or the HTTP API. I’ll have to study how to do that, and that will hopefully be the topic of my next post about Sonoff POW.

Sonoff POW can be purchased on ITEAD Studio for $10.50 plus shipping, but is currently out of stock with the company manufacturing a third batch soon.

Share this:

Support CNX Software! Donate via cryptocurrencies, become a Patron on Patreon, or purchase goods on Amazon or Aliexpress

ROCK 5 ITX Rockchip RK3588 mini-ITX motherboard
Subscribe
Notify of
guest
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.
43 Comments
oldest
newest
tkaiser
tkaiser
8 years ago

Thank you for the great report. Though I would suggest to change $ADMIN_PASS and $upload_flags (defaults to “fibonacci”) in

code/src/config/general.h
code/platformio.custom.ini
code/platformio.ini

as first step just to minimize the risk to expose another device with default logon credentials to the ‘Internet of shitty things’ 😉

So once you’ve successfully built the firmware it’s basically just connecting the various Sonoff devices to the host computer, enter flash mode and executing two commands to flash firmware and fs, right?

Paul Allsopp
6 years ago

New devices should never be exposed to the internet until fully set up. Changes to the source code will result in them being overwritten next time you do a pull from master.

tkaiser
tkaiser
8 years ago

@Jean-Luc Aufranc (CNXSoft) Regarding the password I thought it would be used in more than one location (see comment above)? Anyway: this should change it directly after checking out Xose’s repo: MYPASSWD=something_secret find espurna -type f -exec sed -i "s/fibonacci/${MYPASSWD}/" {} + 12 MYPASSWD=something_secretfind espurna -type f -exec sed -i "s/fibonacci/${MYPASSWD}/" {} + The risk that an Espurna device gets compromised that way is rather low (since an attacker has to be pretty close to the device — almost physical access) but IMO it’s ‘good style’ to try to prevent any of these attacks and well known default logon credentials… Read more »

Paul Allsopp
6 years ago

Awesome. ENV vars are so the way to go

Mario
Mario
8 years ago

Any form to flash without downloading all? And a binary :3

Xose Pérez
8 years ago

Hi I’m the developer. Thank you all for the great article and all your suggestions. Several things to note: 1) Using the staging version shouldn’t be necessary. The only reason it was was that the default environment had support for the fauxmoESP library, which requires the latest version of the Arduino Core for ESP8266. I have removed that requirement from the default environment. 2) I still cannot reproduce the issue you have with the HLW8018 header. It’s weird the same does not apply to other headers included from included files (like NtpClientLib, for instance). Even thou your fix did it… Read more »

tkaiser
tkaiser
8 years ago

@Xose Pérez
Thank you for your great work on a better firmware for those devices. I think forcing a password change on first visit is ok even if it leaves the device potentially vulnerable in between (AP with known SSID and logon credentials). But that’s simply the user’s responsiblity to provide some level of physical access protection prior to password change and could be addressed with a simple sentence (in big red letters 😉 ) on download/project page.

Looking forward to play with ESPurna in 2017 🙂

rebeL
rebeL
8 years ago

Does ESPurna works without the www-internet-connection, I don´t understand where the “ESPurna Web Interface” is “hosted”?
Is it correct: I don´t need a Hardware – Arduinoboard?
And Yes, a personal Password would be better.

Xose Pérez
8 years ago

@rebeL
The web interface is hosted in the device itself. It has a small webserver embedded. If by “www-internet-connection” you mean a “cloud”, yes, it works without internet connection. Just connect it to your local network to benefit from using it from your laptop or smartphone, MQTT, Alexa,…
I don’t know what you mean by if you need a hardware. ESPurna was coded with the Itead Sonoffs in mind but it will work with most of the ESP8266-based smarts switches out there.

rebeL
rebeL
8 years ago

@Xose Pérez
Thanks for reply. I will try it as soon as I have a USB_to_TTL adapter.

Harley
Harley
8 years ago

Anyone got experience of ESPurna with Domoticz?

Currently using Domoticz home automation software.

Xose Pérez
8 years ago


The MQTT message format for Domoticz is specific. Right now your best option is to “rewrite” messages back and forth from Node-RED or any other way. That’s also the approach that they suggest in that wiki page. So for instance, you will need to subscribe to “domoticz/out”, capture the messages like “{“command”: “switchscene”, “idx”: 24, “switchcmd”: “On” }” and republish to “/whatever_your_sonoff_topic>/relay/0” as either 0 or 1.

Chuxxsss
Chuxxsss
8 years ago

Will this work with Peter Scargill all-in-one script? It’s a raspberry pi script to install a MQTT server plus node-red? What are the directions to install this on a standard sonoff please?

Gianluca Barbaro
Gianluca Barbaro
8 years ago

It was my first attempt and, although I used to be a programmer, I had never used this environment before.
I did the whole procedure without a problem on a basic Sonoff.

Now I’m going to try and integrate the switch with some control software via MQTT.

Thank you!

Gianluca

roel
roel
7 years ago

Just to let you know the code builds without errors on arch linux. Platformio installed from AUR. Only one package that should be installed and is not in the dependency lis is python-setuptools from the extra-repositories.

A last thing I would ask. on the espurna bitbucket site Xose says it should be flashed with a 3,3v usb to ttl. My usb to ttl is the one a use for my dev boards (cubie, odroid). Can I use this one then before I start flashing or do I need another one?

roel
roel
7 years ago

I flashed it with succes. To be sure I took 3,3V from my OPI-one.
One thing I had to find out was when you push the button when powering the board, you are imediately in the flashing mode. You don’t see blinking leds. If you see blinking leds, you are to late.
So you should power the board while pushing the button, release it and start flashing. The leds will not go on.

What I miss on the espurna firmware is setting switching schedules. Maybe You can do it throug the command line?

Roel
Roel
7 years ago

I think I will try ESP Easy, where you can set rules. Don’t know if they already support the power measurement though.

Gaetano
Gaetano
7 years ago

@Roel
please tell us if your tryings with ESP Easy will bring some success.

Athar
Athar
7 years ago

Will cnx do a comparison between ESPurna and the Arendst versions, esp re: integration?

Supposedly ESPurna has more features including Alexa emulation, and Arendst is more targeted to Sonoff ?

(Scroll down to Jan 2 comments):

http://tech.scargill.net/more-from-sonoff/

Adrian Andrei
Adrian Andrei
7 years ago

Hi,

Does it work with ifttt ?
I have seen that it is emulating Belkin WeMo switch, but I am curios if someone is able to link it to ifttt?

Thank you!

Harleken
Harleken
7 years ago

Hi,

i build a binary from the code and flashed it to the Sonoff, that works.

I connected the WIFI Network”sonoff_xxxxx) from PC and Phone.
I got a got IP like 192.168.4.2

but after enter the “authentication challenge” admin/fibonacci i see a blank Website.

Any Idea`?

Thanks

Ruben Tavares
Ruben Tavares
7 years ago

Binary files would be awesome :/
Using windows, and all the tutorials I find seam to use linux :/

Stephen Lofgren
Stephen Lofgren
7 years ago

Great post! I had followed it before and it worked great but when I went through it after a clean OS install I ran into a snag. The links from /usr/local/bin were broken. I didn’t have a penv folder and couldn’t figure out why. In the end the solution was simple.

I selected Install Shell Commands from the PlatformIO menu in Atom. That showed me that platformio and pio were in another location
~/.platformio/penv/bin/platformio
~/.platformio/penv/bin/pio

Khurram
Khurram
7 years ago

Hi,

I’ve no experience with electronics but I really want my Sonoff to work with Alexa Echo, how I’ll update the firmware of my Sonoff as a novice ? can I use Arduino UNO or Raspberry PI by using Arduino IDE to update firmware?

Please also suggest the best firmware and detail guide to update firmware.

Thank you

Umer
Umer
7 years ago

Hie,

can anyone tell me where to find and use gpio 14 on POW please? i am trying to hack a DHT22 into it to additionally get temp and humidity also. Using espurna firmware which should just pick it up from gpio14. (i tested that on sonoff basic)

Umer
Umer
7 years ago

@Khurram
Khurram, btw, i used a cheap FTDI like this one (http://www.ebay.co.uk/itm/Hobby-Components-UK-USB-to-serial-port-adapter-FTDI-with-3-3V-and-5V-outputs/130923180691?hash=item1e7ba13293:g:A~oAAOxyi-ZTXiu2)

you can use Arduino IDE to flash ESPURNA like i did and that has Alexa integration. just search for espurna.

Jon Lidgard
Jon Lidgard
6 years ago

@Harleken
What browser are you using? The webpage doesn’t load on Safari, Firefox works.

Boardcon Rockchip RK3588S SBC with 8K, WiFI 6, 4G LTE, NVME SSD, HDMI 2.1...