John's Musings


Yeah, Me Neither

ESP8266 Hack of inexpensive WiFi Outlet

NOTE: This is a fairly involved project that requires soldering, Chip programming, setting up a server of sorts, etc. Took me two and a half days to figure all this out with lots of community help. Took me less than 30 minutes to do the second device. So it's a quick project THE SECOND TIME AROUND.


I AM IN NO WAY SHAPE, OR FORM THE AUTHOR, DISCOVERER, INVENTOR, OR ANYTHING ELSE OF THIS PROJECT. I am documenting this in easier to follow steps as it took some time to figure all this out because it is spread out in bits and pieces everywhere.


The original project (that I merely duplicated) is located at The Great Geekery. Before you do this project you for sure need to look over his original information. Wouldn't hurt to do a google search on "Ecoplug ESP8266" and read some backgound information on the whole thing. Very enlightening.


In today's blog I'm going to hack a wifi outlet to be able to be operated from wi-fi. Wait. What? These devices are made by KAB and branded with several different names such as WiOn, Ecoplug, WorkChoice, etc. In fact I ordered a Ecoplug from Walmart to be picked up in the store and when I got there received a WorkChoice. They may have different brands, different cases, but they are the same device.


They all contain the very hackable and very popular ESP8266 wifi chip which powers much of the Internet of Things (IoT) that you're always hearing about.


When people started taking these apart for reverse engineering they also discovered another dirty little secret. By using a program called WireShark that sniffs network transmissions and packets they discovered that these devices were SENDING YOUR WIFI SSID AND PASSWORD IN THE CLEAR TO AN OVERSEAS SERVER.


DO NOT BUY ONE OF THESE AND USE IT IN YOUR HOME. If you do realize that you have no expectation of security or privacy.


However you can hack 'em. Then they can't phone home. Here's the one I got at Walmart.



Now lets get to some hardware hacking. Remove the 4 screws in the back. The ESP8266 that we're going to reprogram is under the light brown shield. Remove the three screws holding it.



Now we need to solder 5 wires to the chip. Make sure the 2 holes are at the bottom and the chip is facing towards you. We are going to locate Power, Ground, Transmit, Receive, and GPIO0 which must be held low to ground on boot to put the device into boot loader mode so it can be programmed.



Also take note of the fact that right through the arrow line that says 3.3v's is an empty space on the board that is supposed to be populated with a reset switch. Dirty dogs removed the reset switch. Some of me thinks it was to make stuff like this harder. More than likely it saves .04 cents per unit.


Now take some breadboard wires and solder them on. I used 4 female ended wires with the GPIO 0 wire being a male end.



Now you need an FTDI programmer to hook from your computer to the board wires. I use the Adafruit FTDI Friend here. It costs $15. There are FTDI's on eBay for like $3 and even less. They use a fake FTDI chip and sometimes there are issues with drivers. I think they work just fine but I don't want the headache down the line.


HERE' ANOTHER POTENTIAL ISSUE. The FTDI programmer puts out 5v. The ESP8266 input power is supposed to be 3.3v. I have programmed 2 of these outlets and various other ESP8266's with 5v before. I've never had one blow up, HOWEVER, there are folks out there who have had them fry. If you put 5v into your chip be aware there is SOME risk involved with that. If you are the careful sort you can build a voltage divider with two resistors on a breadboard and chop your 5 volts down to 3.3. If you have a 1K ohm tie it to hot. Then take a 2K ohm and tie it to ground in series with the 1k. Right in the middle of those two resistors you'll be outputting roughly about 3.5v.



Now hook the chip to the FTDI like this. (from board to chip)

Vcc to 3.3v

GND to GND

Tx to Rx

Rx to Tx

GPIO 0 held to ground. I used an alligator clip to do this.



Now the hardware is ready. Let's get the software ready. i programmed mine from Arduino IDE on Mac OS X. Get the latest from here.


Now go on the toolbar when it is opened and go to Arduino > Preferences and add the following line to Additional Boards manager and Click Ok.


http://arduino.esp8266.com/stable/package_esp8266com_index.json




Now go to Tools > Board > Board Manager



Type in "ESP8266" and add the ESP8266 by ESP8266 Community Package (mine is already installed)



Now we need to add some Libraries. Go to Sketch > Include Libraries > Manage Libraries



Go here and download Homie Firmware. Download the Zip file. See the pic above? Go to add zip library and then navigate to, and then add the zip folder you just downloaded. It will install Homie into the Arduino Library. Now go to "Manage Libraries and search for and add the following packages:

ArduinoJson

Bounce2

PubSubClient

Async-mqtt-client (download and install as zip)

ESPAsyncTCP (download and install as zip)


Now lets load firmware. This was kind of weird and I'll explain it to the best of my understanding. When I downloaded the ino file from Scott Gibson's project I couldn't get it to compile successfully. I got with the developer of the Homie firmware project who told me the firmware code changed. So I think that between the time Scott wrote it and the time I found it the Homie firmware changed a bunch. Mind you I know nothing about code but I took the example below of Scott's code below and changed where it was failing (using a homie example as a template). SOMEHOW IT WORKED! Still, the tutorial advice I am giving below is the homie firmware example and you only have to tweak the Pin, LED, and Button stuff a little.


The only difference that I can tell between the two codes is it seems like that if you push the button in Scott's firmware it turns the socket on manually. The Homie IteadSonofButton example below does not do that. But, hey, it's a wifi socket. If it ain't wi-fi-ing .......unplug it and plug your thing in the real socket. I don't see much advantage to going manual. The whole point is to have a wifi controlled socket. Here is the code I tweaked. This is Scott Gibson's code. Feel free to use it if you want. It works. If you use the Homie example well then you know for a fact there should be no compilation errors. Copy this to a new arduino sketch and verify.


#include <Arduino.h>


#include <Homie.h>


#include <Bounce2.h>
#include <Homie.h>
#include <Button.h>


const int PIN_RELAY = 15;
const int PIN_LED = 2;
const int PIN_BUTTON = 13
;




HomieNode switchNode("plug", "switch");
Button button1(PIN_BUTTON); // Connect your button between pin 2 and GND


bool lightOnHandler(HomieRange range, String value) {
  if (value == "true") {
    digitalWrite(PIN_RELAY, HIGH);
    switchNode.setProperty("on").send("true");
    Serial.println("Light is on");
  //  switchState = true;
  } else if (value == "false") {
    digitalWrite(PIN_RELAY, LOW);
    switchNode.setProperty("on").send("false");
    Serial.println("Light is off");
//    switchState = false;
  } else {
    Serial.print("Error Got: ");
    Serial.println(value);
    return false;
  }


  return true;
}






void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  //pinMode(PIN_BUTTON,INPUT_PULLUP);
  pinMode(PIN_RELAY, OUTPUT);
  digitalWrite(PIN_RELAY, LOW);
  Homie.setLedPin(PIN_LED, LOW);
  //Homie.setResetTrigger(PIN_BUTTON, LOW, 5000);
  Homie_setFirmware("ecoplug", "1.0.0");
  switchNode.advertise("on").settable(lightOnHandler);
  button1.begin();
  Homie.setup();
}


void loop() {
  Homie.loop();
  if (button1.pressed())
  {
    digitalWrite(PIN_RELAY, !digitalRead(PIN_RELAY));
  }
  


}


OKAY THIS IS THE HOMIE EXAMPLE FIRMWARE BELOW. You still need to add the homie library even if you use the code above.


Now navigate to your Arduino libraries. In Mac OS X it is under "Documents"



Open your homie-esp8266-develop folder and go to examples. Open the one that says IteadSonofButton and double click the ino file




It will look like this after you alter the pin data as mentioned below:




We're going to change the value of the top 3 pins to this: (please bear in mind someone taught me this and that I wasn't smart enough to figure it out myself).


const int PIN_RELAY = 15;
const int PIN_LED = 2;
const int PIN_BUTTON = 13;


Make sure it looks like the picture above then click on "Verify" where my yellow circle is.



Now go into Arduindo under "Tools" and set your chip to Generic ESP8266 and then make sure all the other settings are the same. Make sure you have the proper Com Port selected as well. When I took this screenshot my FTDI controller was not plugged in. Again make sure you have it plugged in and selected.



If that works click on the right arrow next to the verify button and watch it upload to your chip.




HARDWARE HACKING COMPLETE!


Now the outlet should be in WiFi Access Point Mode. Check to see what wifi address it is broadcasting and connect to it.



Now go to this address to configure it. NOTE: IT WILL NOT CONFIGURE FROM A MAC. Must use Windows, or Linux, or Chromebook or Android or something else. The developer is aware of it and confirmed to me there was a bug.


http://setup.homie-esp8266.marvinroger.fr


TAKE NOTE OF THE DEVICE ID (the numbers and letters in the Wifi SSID after the dash) AND WRITE IT DOWN. It's just the mac address of the device but you need it later. If you change the device ID........WRITE THAT DOWN TOO. First thing you'll probably see is this:



If it does that I had to connect to my home wifi and then click on the setup link I posted above and get the page started and then quickly switch back to the Homie Wi-Fi Access Point. I think that is more of a browser cache thing than a bug of some sort. Anyway if you hit it right you'll see this below:



Now hit Next and fill in the following regarding your network credentials:



Now some other config. The broker address is the address of your MQTT server. I discuss that down below. You need an MQTT server before you can proceed. You can go ahead and fill this out if you know what the IP address is going to be of the computer where you install the server at. Note my mistake below.



Now finally, give it a name and then put your device ID in. Also check the box that says OTA enabled. After you hit next it should write to the device and restart and be ready to be controlled.




Run through the configuration. The only thing I couldn't figure out was the MQTT broker. This is the LEAST intuitive part of the process. Devices have their own protocol called MQTT which is a light weight protocol which runs on top of the http protocol. Anyway you need to connect to an MQTT server somewhere. There are free cloud ones however I just made my own. I installed a program called Mosquitto (yes, with two t's) on my Ubuntu Server. I won't get into the install and configuration of Mosquitto but it wasn't horribly hard and I will note it runs on Port 1883 and if you have a crappy home router it is easy enough for someone to enter port 1883 and turn your stuff on and off. So installing and turning on mosquitto is easy, but configuring it with security is kind of geeky. I run behind a good firewall appliance so my server is not accessible to the internet.


There are MQTT servers for every platform such as Windows, Linux and Mac. I just didn't want to install it on my mac laptop because when the laptop is gone, the mqtt server is gone and no home automation.


Okay so now I have this device configured. And now I have an MQTT server running. It was at this point I had zero clue what to do next. And it isn't intuitive at all. If you were the last person on earth no way you'd figure this out alone. Basically MQTT subscribes and publishes messages from machine to machine.


By the way........although I'm showing you the commands for using MQTT to turn the switch on..........don't look to me for too much help at this part of the tutorial. I'm slightly below beginner, noobie status on MQTT.


Ultimately I figured out (somebody told me what to do) that from my MQTT server I had to issue the following command to make the outlet turn on. Make sure you have the right topic name and device ID in your string here.


mosquitto_pub -t 'homie/382b78075571/switch/on/set' -m true


IF YOU USE SCOTT GIBSON'S FILE THE DEVICE TO CONTROL WILL BE "PLUG" NOT SWITCH. Here's an example


mosquitto_pub -t 'homie/382b780742c4/plug/on/set' -m true


I'll try to explain. The outlet broadcasts all the services it is running and you would be surprised how many. One of them is switch>set>on. True turns it on, false turns it off. So here's how it works.

- mosquitto_pub means we're going to publish to the outlet.

- The broker Topic is "homie". That is the default set in the configuration.

- The next field is your device ID or Mac address (unless you changed it)

- Now we're setting switch/on/set to true

Works like a champ.




Now I know you don't want to log into your server and issue a long command every single time. There are front ends for MQTT and one of the more popular ones is Home Assistant. Home assistant makes a webpage with a toggle switch to turn it on and off.



Basically once Home Assistant is installed you have to configure a file called configuration.yaml to see the switch and run the mqtt command. It isn't hard at all.


On your Mac where Home assistant is go to the terminal and type this:


cd ~/.homeassistant


sudo nano configuration.yaml


Add this to the bottom of the file: Be sure to .change your ip address on the 2nd line. Also change your Device ID's.


mqtt:

  broker: YOUR IP ADDRESS

  port: 1883

  client_id: home-assistant-1

  keepalive: 60

switch:

  - platform: mqtt

    name: "Wall Outlet"

    state_topic: "homie/382b78075571/switch/on"

    command_topic: "homie/382b78075571/switch/on/set"

    payload_on: "true"

    payload_off: "false"

    optimistic: false

    qos: 0

    retain: true

switch 2:

  - platform: mqtt

    name: "Wall Outlet2"

    state_topic: "homie/382b780749c1/switch/on"

    command_topic: "homie/382b780749c1/switch/on/set"

    payload_on: "true"

    payload_off: "false"

    optimistic: false

    qos: 0

    retain: true




That's it in a nutshell. Once you work through this MQTT thing once it isn't as bad as it seems and it then becomes easy enough to automate many more home items. Enjoy.




24,149