Michaela Merz's personal blog site

Hardware hack: Liberating a Chinese Power Plug

Hardware hack: Liberating a Chinese Power Plug

Cheap IoT devices like power plugs are mostly manufactured in China. They connect to “bridging” servers we don’t really have control over, they are usually not documented and those required “bridging” services may  fail or even be terminated at any time.  Which would of course render your (or my) “smart” power plugs useless. Time to do something about it.

A word of caution: I flashed the first devices with line power connected. That’s not a good idea. Always disconnect the “smart plug” from power when the case is open. Always power the chip from your development setup. You have been warned.

I bought a number of cheap “Wifi Mini Socket Outlets”from Amazon and they are easy to install and integrate beautifully. Without going into details (can be found here) all connected devices need a “bridge” server that connects your devices to Amazon’s “Alexa” service. The user doesn’t know what server that is, who is running it and where it is located. I guess most people don’t care. It works – and that’s that. But I am a bit different. I want to rely as little on “foreign” (as in .. not mine) technology as possible. I can’t, for the time being, circumvent a third party voice recognition (though Mozilla is getting close to an open source solution), so “Alexa” (or something else) is a given. But I want to run my own “bridge” servers – and that’s why I had to develop my own devices and .. well .. that’s why I “liberated” that poor little “Wifi Mini Socket Outlet”.

It took one screw and some un-snapping to get the plug open. Inside I found the usual power supply, the relay and an ESP-12, which is  a CE certified ESP8266 WiFi chip. I worked on those little buggers over the last weeks, so I thought I knew all about it and was able to proceed swiftly. Well – it turned out to be a bit of an adventure.

I hooked the test-clamps to rx0, tx0 and ground to the Serial-USB converter but all I got was some hieroglyphics on boot (of the plug) – a sure sign for a wrong baud rate. But what baud rate would I need? Google delivered the answer: 77400 . Weird.

And of course – all Linux terminal programs (to connect to a serial device) support only the “usual” standard system baud rates. And 77400 is NOT standard. But nothing beats experience. I hacked a small “C” utility program utilizing the “BOTHER” flag for “c_cflag” to set the baud rate I wanted. And voila – the unit was talking to me. I couldn’t talk to the unit and the unit wasn’t sending any useful data – so I went ahead with the next step: Getting ready for flashing.

That requires the Pin18 (GPIO0) to be pulled to ground. I fiddled with a magnifier in one hand and the test-clamp(s) in the other to get  good connections. It took a number of attempts to get all three hooked up – and Cocoa – my Amazon parrot – might have learned a few new words in the process. I finally soldered the ground wire because I just could get a clamp to hold on. I started the Arduino environment (pre-configured for the ESP8266 chip set) and a few minutes later, my device had it’s first “Ela” made software installed.

I wanted the device to work exactly the way it worked before. With three LEDs  (small blue, large blue, large red) giving an idea of the status and a push button to manually control the relay. That would require 5 GPIO pins The ESP8266 has 17 GPIO pins (0-16), but one can only use 11. GPIO 6 – 11 are used to connect the flash memory chip and GPIO 1&3 are used for serial. A few loops helped to find the correct GPIOs.

Relay:  12 to high – switch relay on
Button: Pulls 13 to low if pressed
Small Blue led: 2 to low
Big blue led: 4 to low

As a matter of fact: Just switching GPIO2 and GPIO4 to INPUT makes the LEDs come on. So to switch them off, one has to set the GPIO to high. The red LED comes on automatically if the relay is powered.

All that remained to do was to knit some logic and a web server around the GPIO setting and getting action. But that’s easy with the Arduino environment. It just took half an hour or so.

Integrating this new “open source” switch into my personal “Alexa Home” environment took another 30 minutes. It now controls my .. emm .. electric … fireplace. We’d like to turn it on to watch the “flames” once in a while – even if its 70 degrees outside (we live in South Central Texas).

Usually most Chinese products are co-branded so I am pretty sure that this “hack” will work with other cheapo wireless outlets as well.

Which brings me to the next question: Though parts like power supplies, relays and the ESP8266 chips may cost a total of $6 or $7 – is it really worth it building the devices myself? I still need a plug, a box, an outlet, a few LEDs and maybe even a push button .. and this little Chinese fellow was $12 or so ..


I just ordered two more “Nice2MiTu Smart Plug Wi-Fi Switch Sockets” from the jungle ($21.99 for two). I am pretty sure I can convince them to do what I want them to do. Though I am planning to put a self-made “smart” switch into my jukebox. But that’s a different story.

Let me know if I can help you with your project.

UPDATE: As suspected, the Nice2MiTu Switch Sockets were exactly the same on the inside. So far, I flashed 7 “smart” plugs with my software. One of them resisted every attempt to be flashed – so unless I come up with a better idea – I consider this one dead.

Here’s what my software does:

If the unit doesn’t recognize any stored value in the EEprom, it becomes an AP itself and starts an MDNS responder. That makes it easy to find and connect to it and to configure the WiFi SSID, the WiFi password and a name for the device (small LED flashes rapidly). After reboot, the unit finds the data in the EEprom and tries to hook up to the WiFi (small LED flashing slowly). If successful, the large blue LED will light up steady. Again an MDNS responder is launched and web clients may connect to it to switch the relay on (red LED turn on). The unit can be reset on this page, but it is also possible to reset the unit by pressing the manual “on/off” button for 10 seconds. The unit is now ready to be used in any environment one can think of.

UPDATE 2: I purchased the slightly cheaper KMC “smart plugs” that are manufactured by Hangzou Kaite Co. LTD . Those units are available for around $8 to $9 and therefore cheaper than almost any home-brew solution. Though they look almost the same, there are several differences to the “Beauty Flower” switches described in detail above. First: There seems to be a problem with circuit isolation and I blew one up just by grounding the appropriate wire on the ESP chip. The unit was plugged into a power socket across the room and I expect there must have been some difference in potential that discharged when I grounded the unit to the USB on my computer. Weird. But stuff happens. Second: They only have one LED. They still have the small one on the chip, but the case is designed in a way that blocks this let from being visible once assembled. Third: The GPIO setting is completely different to the “Beauty Flower” :

Relay:  14 to high – switch relay on
Button: Pulls 0 to low if pressed
Small Blue led: 2 to low
Big green led: 13 to low

And last but not least: The whole internal design has been somewhat cheapened (I think). Some assembly will be required to get the unit setup again after flashing.

I updated my software to be able to signal the unit’s status via a single LED (very fast flashing: SoftAP, fast flashing: Trying WiFi, slow flashing: All Ok, steady: Relay is on).  But they work quite well once everything has been flashed.

UPDATE (September 2018): I wrote a new blog post dedicated to the power measuring circuit within the KMC “smart plugs” . You’ll find it HERE.



22 thoughts on “Hardware hack: Liberating a Chinese Power Plug

  1. Hi Michael,
    thanks for this. Agreed this makes more sense than messing around with parts if you just want a WiFi enabled socket (I came via your ESP8266 relay Hackster.io comment) although my goal is to integrate it with a (24v DC) boiler control board. I’ll stick with the LCTech relay module for that but will give the plug a try too for other applications! Your unit looks like https://www.ebay.co.uk/itm/Sonoff-S20-WIFI-Smart-APP-Remote-Control-Timer-Socket-US-EU-Plug-Home-Automation/332451657277 , do you agree? (I want the UK version)

    I take it you are using Arduino firmware rather than e.g. nodeMCU? Any chance you can share your code?

    Btw- gtkterm allows you to specify arbitrary bauds (I think minicom too). For the AI-Thinker firmware, the weird baud is documented at http://wiki.ai-thinker.com/_media/esp8266/esp8266_series_modules_user_manual_v1.1.pdf but as 74880. I have also seen 76900!


    1. Howdy Peter:

      Well .. the boot-up baud rate is 77400 on my chips. All the standard terminal programs on Linux do not support custom baud rates (only those available to stty) and will complain when one tries to set something different. Haven’t tried gtkterm though. I just ordered a sh*t load of esp8266-2, 5V and 3.3V power supplies a few single channel relay cards and sensors from the land of the 炒面 . All in all I had to shell out $50 bucks or so – a significant investment here – that will keep me occupied over the holiday.

      As to the code – you’re right, I am using the Arduino IDE to keep in line with previous developments. I made the developments under contract. The company that hired me wants to control a number of things in their 100+ stores all around the US. So unfortunately I am not free to share. However – I am willing to answer all related questions. AMA 😀


      1. Thanks Michaela, totally understand about sharing the code.

        Re. GtkTerm- I just noticed in the version history that arbitrary rates were only introduced in 0.99.6 (and I hadn’t actually tried minicom).

        I haven’t tried Arduino but want to play soon!

        1. You might want to try Tasmota. It is available on GitHub and provides support for MQTT for these types of devices. The KMC version includes a power measuring circuit which is not isolated, which means you will blow something up if you have it powered and hooked up to your computer.

          1. Thanks for the info. Those Sonoff modules look interesting. Question: Do you know how the KMC plugs actually do the power measuring or how to access the data? And .. you are right .. hooking a unit up under power creates a nice spark. Killed my serial-to-usb and an USB port on my computer. Lesson learned.

          2. I don’t have one of the KMC devices yet. I saw them on Amazon and was searching to see if they would be compatible with Tasmota. They have the esp8266 so that is good. A link seemed to indicate they used a serial protocol to switch the relay (which would make them like the Sonoffs Dual) but above it looks like they use a standard GPIO to do the switching. I would expect they use the HLW8012 for measuring power. The Tasmota software has code to read that:

            How hard were they to put back together?
            They seem like a good price for power switches, so I might have to get some.

  2. I got some of those KMC smart plugs and found that they have standard TYWE3S ESP8266 boards in them. I soldered lines to VCC, GND, TXD, and RXD (see https://fccid.io/2AFNL-TYWE3S/User-Manual/Users-Manual-3525098 for pinouts) and flashed with Tasmota for sophisticated control (see https://github.com/arendst/Sonoff-Tasmota/). No need to solder GPIO0 — holding down the main button while powering on the unit through the USB-TTL serial converter pulls GPIO0 low and puts the board in flash mode. They do have a power usage monitor that can be accessed through Tasmota, though I’m doubtful of its accuracy.

    1. Thanks for the input. We developed our very own environment, including ESP8266 software for plugs, sensors, switches and even ESPnow environments incorporating additional encryption and protection against manipulation as we want to have the stuff super safe 😀 Good point with GPIO 0 and the button – I figured that out not too long ago. As to the power usage monitor – you are right, it’s not that accurate. But it gives you an idea. Though even that is relatively unimpressive if you run LED lights behind it 😀

  3. I’m considering going with the KMC (b/c they’re cheap, and I’m using a bunch). I’m mostly interested in power monitoring, and am a bit concerned re: the comment, “doubtful of its accuracy”. Care to elaborate?

    Also, I don’t quite follow the ESP8226->HLW8012. I read above there’s code to handle it, but not sure how the KMC’s wired up. I doubt the code will work out of the box.

    .. and a shout out to Michaela Merz! I’m sharing a thread with a celebrity 🙂

    1. Hey Tom: Well – those units are not sensible enough to measure individual watts. But I assume part of the problem is the measurement of the pulse width. This IS a very sensitive matter and a few microseconds make a difference. As to the wiring of the KMC – I have the PIN assignments in the blog post. You may have to tweak the shunt and voltage divider circuits. Other than that – it’s pretty much only a matter of

      attachInterrupt(GPIO_CF1_PIN, your_function,CHANGE);

      and the measurements of the time since last interrupt. AFAIK the sonos library has the code for the KMC built in.


      Update: http://blog.michaelamerz.com/wordpress/measuring-power-voltage-and-current-with-an-esp8266/

  4. I just bought a bunch of these KMC Smart plugs and will be hacking them to use new firmware. The issue with measuring power is that power must be measured over many 60 cycles and averaged based on the waveform voltage and current. Modern devices use switching power supplies that make spikey demands on the power line, so some measurements will have zero load, while others will have a significant load, but only for millisecond(s). I’m sure the KMC firmware was written to measure power usage using such an algorithm. The good news is voltage, watts and power factor all should be measurable with the cute little plug.
    I’ve been away from developing IOTInventor for over a year, but am restarting development, but the web site is a bit stale and the unreleased beta is well, needing a bit of updating.

    1. Hey Shannon – I am not very much interested in ‘just’ measuring power. For me it’s more interesting to track power flow in order to piggy-back other action on it. As a matter of fact, I use the KMCs in line with devices that are not really working well with #iot – like televisions or the Stereo equipment. So – if the KMC senses the TV drawing power, it triggers other action like dimming the lights, turn the fire place on (no heat for the moment 🙂 – stuff like that. But it took a while to get reliable power on/off readings on modern power supplies. You want the power change “alarm” to go off as soon as possible, but I need around 3 seconds to be sure it’s a valid change. I just had a look at http://www.iotinventor.com – I very much like the idea. Are you planning to support ESP8266 to?

      Happy hacking – Michaela

      1. Michaela, hi, just got back to this site after being a bit busy. As far as supporting the ESP8266, yes, and ESP32 as well. The original design of IOTInventor was focussed on Arduino Mega or Uno using serial commands coming through a 900mhz radio module. or directly from USB/serial with a host PC/Raspberry Pi as the gateway to the internet and the cloud server hosting the database and account info, device config etc. The client app (iOS/Android/Raspberry Pi/Mac and Windows) provide the remote control and monitoring app and device builder and programming capability. Anyway, I like these KMC smart plugs and am thinking about how to reprogram them and use their internal temperature sensor (assume it is just the internal ESP8266 temp sensor) and there isn’t a separate sensor. I asked the question about accessing temperature info and got a vague response from KMC. Anyway, thanks for the info you’ve dug up on these. Best, Shannon

  5. How does the Gosund smart plug pair with the SmartLife app works to get WiFi network credentials? Over WiFi? Soft AP? I tried to sniff the OTA traffic but did not see any connection between the phone and the plug. Help.

    1. I usually crack one open to see what kind of chip they are using. If its something related to an ESP8266, you can most likely flash with your own operating system. Other than that I suspect they are communicating (encrypted?) with some remote host host and its tough and usually not worth it to try to learn something from it. Because without flashing your own OS – you would have to do a lot of “adjustments” to convince the device to talk to you instead of some other remote server.

Leave a Reply

Your email address will not be published. Required fields are marked *