md
Flash Tasmota on a Sonoff in DIY mode in Linux
Last Revision September 15. Original Version: August 22, 2019

Itead now ships Sonoff Wi-Fi switches that have a DIY mode making it possible to turn the switch on or off locally with an HTTP request. Putting the Sonoff into DIY mode is straight forward: simply short two pins on a header with the supplied jumper. Using DIY mode is another matter as will be explained later. Consequently, it is probably the case that the vast majority of those persons that would want to use DIY mode will replace the Itead firmware with something else such as Tasmota.

Unfortunately, flashing new firmware on the Sonoff Mini is more complicated because there is no place to solder a four or five pin header as in the Sonoff Basic. Fortunately, DIY mode makes it possible to replace the firmware by wireless uploading (OTA) using the Sonoff_Devices_DIY_Tools provided by Itead. However, that utility only works in Windows 10 and it also appears that many, including myself, ran into problems using the utility.

This post shows how I replaced the Itead firmware of a Sonoff Mini with Tasmota using the OTA capability of the DIY mode and a Web browser on a Linux desktop. The technique is flexible. In all probability other operating systems including Windows 10 and older versions and macOS, could be used. Of course something other than Tasmota could be flashed. This works with Firefox and other browsers or curl could be used instead. And the technique could be used with a Sonoff Basic/RF R3 also. There is no such thing as a free lunch; the trade off is increased complexity.

  1. There must be a Web server on the local area network (LAN) that can download the replacement firmware. Many will probably have that in place if they are currently running a home automation system.
  2. A Wi-Fi access point connected to the LAN must be set up. I used MoCA network extender but I am confident that a Wi-Fi router would also work if running OpenWrt or perhaps a proprietary system. There are another two or even three possibilities that I can envision that do not require extra hardware.

Table of content

  1. What is Wrong with DIY mode
  2. Creating a Wi-Fi Access Point
    1. With a Network Extender
    2. With an OpenWrt Wi-Fi Router
    3. With a Desktop HotSpot
    4. With a Guest Network
  3. Update the Sonoff Device
  4. Upload Tasmota to the Sonoff Device
    1. Using Firefox and RESTer
    2. Using cURL
  5. Tasmota Configuration
  6. Conclusion

What is Wrong with DIY mode toc

Currently, there are only three Itead Wi-Fi switch models that can work in DIY mode: Sonoff Basic R3, Sonoff RF R3 and Sonoff Mini. The implementation of this mode is rather odd. The Sonoff devices in DIY mode can only connect to a Wi-Fi network with specific credentials:

Who will use DIY mode on a Sonoff device? Anyone that dares to do it will be creating what is, for all intents and purposes, a public Wi-Fi network in their home. In his video, Tutorial Sonoff Mini (incl. DIY Mode and how to Flash Tasmota), Andreas Spiess (The Guy with the Swiss Accent) rightly mocks this implementation.

Additionally, the DIY mode REST API is too complicated, in my opinion. HTTP requests sent to turn the Sonoff on or off must use the POST method. In my home automation system, Domoticz, an action in response to turning a virtual device on or off can be an HTML GET request, an explicit invocation of a script or an implicit invocation of a script. As far as I know the only way a Domoticz action could perform an HTTP request using the POST method as required by the API involves writing a script Arguably the POST method is marginally more secure then the GET method because the data sent, identifying the device and action to take, is not displayed in the URL of the request. But that is a bit like closing the proverbial barn door given the public nature of the wireless network.

Fortunately, DIY mode needs to be used only once to flash the Sonoff device with some other firmware such as Tasmota.

Creating a Wi-Fi Access Point toc

The first step is to create a Wi-Fi access point (AP) with the DIY mode required credentials. The Web server capable of downloading the new firmware must be on the same machine hosting the AP or on a computer on the same local network as the AP. It is even better if the LAN is also connected to the Internet because upgrading the Itead firmware and then replacing it can all be done in the same environment.

In what follows, the wireless network is named HomeNet. It is connected to the local area network on subnet 192.168.1.xxx. Machines on that network have access to the Internet through the ISP provided router. The Raspberry Pi, which is the host of the home automation system, also has a Web server, which is used for OTA updating of the Tasmota firmware of Sonoff devices in use. This pre-existing network is identified by the blue Wi-Fi icons in the figures below. The sonoffDiy Wi-Fi network is tagged with red Wi-Fi icons.

With a Network Extender toc

The following image shows the hardware I used to flash Tasmota on a Sonoff Mini. I hasten to add that it is more complex than necessary, because my initial goal was to make the Python scripts used by Sonoff_Devices_DIY_Tools work in Linux as explained by ThierryM / Lo Furòl.

The wired LAN is extended with MoCA technology which uses coaxial cabling for television. The ActionTec WCB3000 which is at the far end of the cable provides both Ethernet and Wi-Fi connections. The extender has two radios (2.4 GHz and 5 GHz) that by default are enabled. Being surplus to requirements, both were disabled. It was very easy to activate the 2.4 GHz radio creating the needed Wi-Fi access point with the specific credentials required by the Sonoff DIY mode.

It is necessary to log onto the device. Here are the instructions pulled from WCB3000N_Wireless_Settings_Guide.pdf.

Open a web browser on the computer and enter http://wecb-XXXX.local in the address bar, where XXXX stands for the last four digits of the Extender’s serial number. The serial number can be found on the label located on the back panel of the Extender.

Just a warning, that method works very well in Linux if avahi is installed and should work in Mac OS where Bonjour is Apple's implementation of Zero Configuration Networking (zeroconf). There is a good chance that it will work in Windows especially if networked printing is enabled in the system. But even when zeroconf is implemented, some web browsers, Chromium notably, will not resolve a machinename.local URL.

Once logged in to the extender's web configuration utility,

  1. Click on the Wireless Setup icon.
  2. Select Basic Setup in the Wireless Settings menu.
  3. Select the 2.4Ghz radio (the ESP8266 in the Sonoff only works at that frequency).
  4. Enable the radio.
  5. Enter sonoffDiy in the Wireless Network Name field.
  6. Enter 20170618sn in the Password Phrase field.
  7. Click on the Apply button.

That is it; after 20 seconds the wireless access point is operating.

To be fair, MoCA is not a widely used technology, but it is possible to achieve the same result with an extra Wi-Fi router. This is the setup I will be using when I receive a Sonoff Basic R3 on order from Itead.

With an OpenWrt Wi-Fi Router toc

Here I am using an old Rosewill RNX-N300RT Wi-Fi router on which I installed OpenWrt 17.01 quite some time ago. A newer version of OpenWrt exists but it cannot be installed comfortably on a system with only 4 MB of flash memory and 32 MB of RAM.

Setting up the wireless access point with the Rosewill/OpenWrt router is a two-stage operation. First the Rosewill router has to be connected to the existing home network. In the second stage, the Wi-Fi interface has to be created.

The guide to setting up connecting the router to the LAN is a page from the OpenWrt user guide: Client Device - Connecting to an existing network. I will repeat the instructions somewhat edited here:

  1. Backup the current configuration just in case the Rosewill router needs to be used as before.
    • Click on SystemBackup / Flash Firmware.
    • In the Flash Operation / Actions tab, click on Generate archive button.
    • Save the configuration archive to a reasonable directory on the desktop computer.
    This is an optional but recommended step.
  2. Click on NetworkInterfaces, then click on the Edit button of the LAN Network.
  3. In General Setup tab, in Protocol, select Static Address.
  4. In IPv4 address write the new static address of this device. I chose 192.168.1.98 which was not used by other devices. Adjust this IP address to correspond to your situation.
  5. In IPv4 Netmask set the netmask to 255.255.255.0.
  6. In IPv4 gateway set the address of the gateway: 192.168.1.98.
  7. In Custom DNS field set the address of the default gateway: 192.168.1.98.
  8. Scroll down and in DHCP Server, in General tab, select Disable DHCP for this interface, to disable automatic IP assignment on the LAN. Client devices will be connected to a network where there is a router doing DHCP server already and this will avoid conflicts with it.
  9. Click on Save & Apply button at the end of the page. This will change the network configuration of the device.

Since the router is being connected to the existing network, there must be an Ethernet cable between it and the local area network as shown in the figure above. It is important that the Ethernet cable from the LAN router be connected into one of the four yellow LAN ports of the Rosewill router and not its blue WAN port. It may be necessary to power cycle the Rosewill router but after that it will be reached at 192.168.1.98 from any computer on the LAN.

The guide to setting up the Wi-Fi access point is a page from the OpenWrt quick start guide: Enabling a Wi-Fi access point on OpenWrt. I will repeat the instructions somewhat edited here:

  1. Go to NetworkWireless. A Wi-Fi network can be created by clicking Add or if one already exists it can be modified by clicking Edit.
  2. Go to the Device Configuration and open the tab Advanced Settings: in the Country Code field, select the correct county code.
  3. In the tab General Setup, set ESSID to sonoffDiy.
  4. In the tab General Setup, uncheck all Network(s).
  5. In the tab Wireless Security, set the Encryption method to “WPA2-PSK”, recommended for home/small office networks.
  6. In the tab Wireless Security, set Key to 20170618sn
  7. Click on Save & Apply button at the end of the page. This will change the network configuration of the device.

The sonoffDiy Wi-Fi network will now be active. Any device that connects to that wireless network will have access to the Internet and to all resources on the local area network 192.168.1.xxx.

Proof that this setup will work when trying to flash a Sonoff device will have to wait until one with DIY mode capability arrives. Nevertheless, I am confident in this configuration because my desktop has been connected to this Wi-Fi access point for the last couple of hours while I have been editing this text, opening the router configuration site, connecting to the Raspberry Pi hosting my home automation system, and consulting the OpenWrt web site.

With a Desktop Hotspot toc

If you can get it to work, this approach does not require extra hardware. The idea is to create the needed access point with the Wi-Fi adapter of a desktop or portable computer as shown below.

Start by defining a hotspot connection using the NetManager connection editor.

michel@hp:~$ nm-connection-editor

The editor starts with a list of known network connections. Click on the + button at the bottom to create a new definition.

Choose Wi-Fi for the connection type.

  1. Name the connection.
  2. Enter the needed network name (SSID): sonoffDiy
  3. Set the Mode to Hotspot

  1. Click on the Wi-Fi Security tab.
  2. Select WPA & WPA2 Personal encryption protocols.
  3. Set the password to 20170618sn.
  4. Click on the Save button.

From now on, to start the access point go to Wi-Fi settings.

  1. Click on the system menu in the top right hand corner of the screen.
  2. Click on the Settings icon.

This should display the Wi-Fi settings. If not, navigate to it.

If the Wi-Fi interface is not available, activate it by clicking on the white and grey slide button on the title bar. Wi-Fi should be ON as shown below.

  1. Click on the hamburger menu icon.
  2. Click on Connect to Hidden Network... Do not click on Turn On Wi-Fi Hotspot.. because this will start an ad-hoc Wi-Fi network with a network name set to the computer hostname and with an abritrary password.

  1. Select the connection defined in the previous step, sonoffDiy_AP.
  2. Click on the Connect button.

The connection to the HomeNet Wi-Fi network will be lost because the radio is now used to operate the sonoffDiy network. However, it is possible to stay connected to the local area network using a wired (Ethernet) connection. If a Web server is running on the machine, then it would not even be necessary to be connected to the local area network with an Ethernet cable.

Be warned, this may not work. Indeed, the sonoffDiy network would not come on line on my desktop machine. A search yielded some helpful information. Running the suggested command showed that AP (access point) mode was not supported by either the Wi-Fi card or the Linux driver for that device.

michel@hp:~$ iw list Wiphy phy0 max # scan SSIDs: 1 ... Supported interface modes: * IBSS * managed ...

I then checked the situation on an older portable running Mint 19 and found * AP among its supported modes. It was possible to create the desired Wi-Fi hotpoint and to log into it with an Android tablet. When the laptop was connected to the LAN with an Ethernet cable, it was possible to open a web page on the Raspberry Pi from the Android tablet. I take that to mean that this is a viable configuration to install Tasmota on a Sonoff in DIY mode although I have not tested it.

With a Guest Network toc

A guest network can be created with my ISP provided Hitron cable modem.

With other modem that have that capability, the steps involved would probably be similar to those shown above. Rather disconcertingly, clicking on the Save Changes button results in a error message as can be seen below on the image on the left.

Yet, sonoffDiy does appear as an open unsecured network with a captive portal where it will be necessary to enter the network password.

I was able to connect to this guest network with my desktop computer. Unfortunately, my Android tablet cannot connect to the hotspot. I get the following error after entering the password "only allow DHCP client to use this wireless". This appears to be a bug in the Hitron modem firmware (based on a message on my ISP forum with regards to a different Hitron modem). If this cannot be fixed, it would be necessary to upgrade the Itead firmware of the Sonoff device before creating the hotspot.

A guest network of this type does not give any access to devices on the local area network. To use this Wi-Fi hotspot, it would be necessary to have a Web server running on the desktop to make the firmware file available. I have not tested this method at all, but it might be worth a try.

Since any device connected to the sonoffDiy wireless network has access to the local network and the Internet (except for the guest network), I make sure that the sonoffDiy network is active only when flashing the firmware of a Sonoff device.

Update the Sonoff Device toc

The Itead firmware must be upgraded to version 3.1.0 or newer to flash a new firmware with the Sonoff_Devices_DIY_Tools utility. The newly received Sonoff Mini had version 3.0.0, of the Itead firmware which was upgraded to version 3.3.0. I used the eWeLink application from Google Play on an Android tablet to pair the Sonoff Mini and upgrade it. There is an IOS version of the application.

Obviously, the Sonoff device must be powered up. The tablet is connected to the sonoffDiy network for this operation so that the credentials of the permanent HomeNet Wi-Fi network were not divulged. Details on how to do this may be forthcoming in a future revision of this post.

Unfortunately, I did not test if I could flash Tasmota onto the Sonoff using the procedure described below without upgrading the Itead firmware. If OTA flashing had been possible without first upgrading the Itead firmware, the process would be have been much faster.

Upload Tasmota to the Sonoff Device toc

To put the device in DIY mode, it is necessary to unplug it, to open it and to place the supplied jumper on the two pins of the connector intended for that purpose.

The easiest way to open the Sonoff Mini is to press firmly with the thumb on the side of the cover between the front and the antenna wire while pulling the cover away from the base. See the picture on the left. The pins that need to be shorted with the jumper are visible in the figure on the right.

Reconnect the Sonoff while observing the blue LED. At first it should flash briefly once a second. After a few seconds, the LED flashes twice every second. This is an indication that the module is connected to the sonoffDiy network. As soon as the Sonoff is connected you can get its coordinates using a desktop computer running avahi or bonjour.

michel@hp:~$ avahi-browse -d local _ewelink._tcp --resolve + wlp3s0 IPv4 eWeLink_10009abcde _ewelink._tcp local = wlp3s0 IPv4 eWeLink_10009abcde _ewelink._tcp local hostname = [eWeLink_10009abcde.local] address = [192.168.1.127] port = [8081] txt = ["data1={"switch":"off","startup":"off","pulse":"off","pulseWidth":500,"rssi":-47}" "seq=1" "apivers=1" "type=diy_plug" "id=1000983386" "txtvers=1"]

The parameters in bold are the data needed to use the DIY mode REST API. Only the wireless interface of the desktop was active, the wired interface was disabled. Some think that it can be difficult to locate the Sonoff device with avahi when more than one interface is active. I did notice that the module is rarely displayed with the command avahi-browse --all.

Now it's just a matter of sending HTTP requests with the POST method. This can be done with a Web browser or with the command line utility cURL as shown below.

Using Firefox and RESTer toc

I installed the RESTer extension by Jan in Firefox. Other extensions can do the same thing and the equivalent can be found for other browsers.

The REST API can be tested by closing the Sonoff relay.

Turning the switch on

  1. Start the RESTer extension by clicking on its icon in Firefox.
  2. Choose the POST method.
  3. Enter the address. Do not forget to adjust the IP address according to the information obtained with avahi-browse.
  4. Add the Content-Type variable in the HEADERS section.
  5. Set the value of the added variable to application/json.

  1. Select the BODY tab.
  2. Enter the request data:
    {
      "deviceid": "10009abcde", 
      "data": {
          "switch": "on" 
        } 
     }
  3. Click on the vertical three dots to display a menu about the format of the data.
  4. Ensure that JSON is checked.
  5. At last, click on the SEND button.

If everything works correctly, the response will be 200 OK and the JSON formatted result will be:

{
    "seq": 1,
    "error": 0
}

The red LED should come on indicating that the relay is closed.

It takes two queries to upload the firmware.

Unlocking the wireless update mechanism

The first query unblocks the wireless update mechanism. Change the URL to (step 3) http://192.168.1.127:8081/zeroconf/ota_unlock (step 3) and enter the following values:

{
  "deviceid": "10009abcde", 
  "data": {} 
 }

using the correct Sonoff identity (step 7). After clicking on SEND (step 9) almost the same response is obtained: 200 OK and

{
    "seq": 2,
    "error": 0
}

Flashing the firmware

The second query tells the Sonoff where to get the firmware. The URL must be changed to http://192.168.1.127:8081/zeroconf/ota_flash (step 3) and the request values are also different.

{
  "deviceid": "10009abcde", 
  "data": {
    	"downloadUrl": "http://192.168.1.22/sonoff/sonoff_tweak.bin", 
    	"sha256sum": "bcdef54eab28bd918321c5ef1837fc8247238a9aa4ad738f9f393bca1234def8"
 }

Obviously, it will be necessary to adjust the URL of the new firmware file and its SHA 256 checksum must be calculated. I do not know if it is verified or not because the value given was correct. Note that the binary file cannot exceed 508 KB. The file sonoff_tweak.bin is a customized version of Tasmota that works with the five types of devices I use in the house. The SHA 256 checksum was calculated with Double Commander, but it can also be calculated with a command line utility.

pi@raspberrypi:/var/www/html/sonoff $ shasum -a 256 sonoff_tweak.bin bcdef54eab28bd918321c5ef1837fc8247238a9aa4ad738f9f393bca1234def8 sonoff_tweak.bin

Even before flashing starts, the immediate response is 200 OK et

{
    "seq": 3,
    "error": 0
}

See SONOFF DIY MODE API PROTOCOL about possible error codes.

The blue Sonoff LED turns on and off more or less randomly during the binary file transfer. Then the red LED goes out while the Sonoff is reset and the relay is open. After barely a minute or two, both LEDs go out and the Sonoff/Tasmota is now functionnal. On my network the same IP address will be assigned when it reconnects to the permanent wireless network. It is therefore easy to reach the Tasmota web page.

Using cURL toc

I have just become aware that Michael Ingraham had posted a description on how to Manual[ly] Flash a Sonoff device in DIY mode two days before the first version of this note even appeared. He suggests using the command line utility cURL to send the HTTP request to the device. In that spirit, here are the three commands described above.

Turning the switch on

michel@hp:~$ curl http://192.168.1.127:8081/zeroconf/switch -XPOS --data \ > '{"deviceid":"10009abcde","data":{"switch":"on"}}' { "seq": 1, "error": 0 }

Unlocking the wireless update mechanism

michel@hp:~$ curl http://192.168.1.127:8081/zeroconf/ota_unlock -XPOS --data \ > '{"deviceid":"10009abcde","data":{}}' { "seq": 2, "error": 0 }

Flashing the firmware

michel@hp:~$ curl http://192.168.1.127:8081/zeroconf/ota_flash -XPOS --data \ > '{"deviceid":"10009abcde","data": { \ > "downloadUrl": "http://192.168.1.22/sonoff/sonoff_tweak.bin", \ > "sha256sum": "bcdef54eab28bd918321c5ef1837fc8247238a9aa4ad738f9f393bca1234def8" }}' { "seq": 3, "error": 0 }

Of course the IP address of the Sonoff and its deviceid must be changed to correspond to the device being flashed. Similarly the URL for the new firmware and its SHA 256 checksum must be set properly.

Tasmota and Domoticz Configuration toc

The Sonoff Mini is very much the same as a Sonoff Basic with the addition of an external switch on GPIO4. Below on the left is its module configuration in Tasmota

The Sonoff Mini replaces a timer switch that had a tiny tactile push button that had just become defective. It also had a much too bright LED even in the OFF position which I masked with white tape. So now we have a standard Decora style switch connected to a Sonoff Mini that just fits behind it in the wall box. A Sonoff Mini and a Decora switch cost less than a replacement wall timer switch.

Setting up the timer in Domoticzis very simple. Just edit the virtual switch in the Switches tab, and add an Off Delay of the desired length, 5 minutes here.

Since a home automation system will not mechanically change the position of the wall switch when the device is remotely turned off or on, I think it is better to use a Decora switch instead of the traditional switch which has on and off labels that will not correspond to the state of the light. Ultimately, I would like to find a sober push button type switch instead.

Conclusion toc

I regret having updated all the Sonoff Mini switches that I bought. If I had kept two or three, I could have verified some of the hypotheses made above. There will be probably be a third revision of this post after I received the Sonoff Basic R3 ordered from Itead.

What can you do if you do not have a Windows computer and do not have the hardware to use to create a Wi-Fi LAN as described above? You can use a soldering iron. Even if it requires a certain amount of dexterity, it is possible according the YouTube videos by Andreas Spiess Tutorial Sonoff Mini (incl. DIY Mode and how to Flash Tasmota), 3D Jig for Flashing the Sonoff Mini (Quickie) and Dr Zzs Sonoff Mini Finally! The Smart Switch we've been waiting for! w/Tasmota for Home Assistant esphome. I recommend viewing these videos, especially the first one by Andreas Spiess which showed how to use the DIY mode REST API. It was while seeing that video a second time that the penny dropped and I realized it would be possible to use that API to flash the device.

Otherwise one could always rename the wireless LAN during the time it takes to change Sonoff device firmware. It is not very practical if other people use the network to access the Internet.

If patient then you can hope that the author of Sonoff_Devices_DIY_Tools modifies the Python scripts so that we can use them in Linux. See his response to ThierryM in Impossible (but near) to flash firmware using DIY Tools under Ubuntu 18.04 #21.

In conclusion, the new Sonoff Mini is a well-designed device from the hardware point of view. It makes it easy to add wireless functionality to any switch with a very high WAF (Wife Acceptance Factor). Do not accuse me of sexism, because I think we should talk about the AF, GAF or PAF ([general | public]acceptance factor). Guests justifiably tease me when I give them a lesson on the use of remote controls or voice assistants to simply turn on a light insisting that it is "very important not to use the usual switch."

In an upcoming revision of the hardware, a third pin bringing out 3.3V along with the two pins used to activate DIY mode would be welcomed. I think that the GPIO port is not used otherwise and one could add a sensor with Dupont connectors if power were available. While suggesting improvements, it would be handy to add Rx and Tx to this same connector. In other words, it would be better for tinkerers that the provision for a five pin header as found in the first version of the Sonoff Basic returned. However, if it is necessary to increase the size of the Sonoff Mini to obtain this change, I prefer to do without.