Hacking a Sonoff to Work With Home-Assistant and MQTT

45K9335

Intro: Hacking a Sonoff to Work With Home-Assistant and MQTT

OK So my third Instructable and here we're dealing with another Sonoff device, the original Sonoff WiFi smart switch. Theses devices are again based around the ESP8266 and are easily hacked. The devices can switch up to 10A @ 240V so are ideal for switching lights, TV's, games consoles etc. Please don't try running a kettle through one of theses, it's not rated for that sort of current and will go pop, or more likely BANG!

STEP 1: What You're Going to Need

  • Sonoff
  • FTDI or and Arduino Uno with a DIL Atmega chip
  • 4 Jumper leads, Red, Black, Yellow, Orange
  • Phillips screwdriver
  • Spudger
  • Soldering iron and solder
  • A large blob of Bluetac
  • 5 Way header
  • Magnifying glass/helping hands

Arduino IDE install and ready to go

Overview of Arduino install for ESP8266 by TrakerJ

The following libraries will also be needed to be installed in your Arduino IDE
WifiManager by tzapu

PubSubClient by Nick O'Leary

Installing Arduino Libraries by MertArduino

STEP 2: Dismantling the Sonoff

Remove the four screws and set them aside in a safe place.

Using the spudger gently pry the bottom of the case away from the top

When you have split the case carefully remove the top section and set aside, then lift the pcb out of the bottom half of the case and set the bottom aside.

STEP 3: Modifying the PCB

We now need to solder a 5 way header onto the board, plug your iron in and while we wait insert the header into the board.

Now take that blob of Bluetac and push it onto the header so squidged down enough to hold the header in place but still sticks proud of the other components.

Flip the board over and push it down so that the Bluetac hold the board steady.

You now have a nice stable board and the header held in place making it easier to solder.

Once your Iron is hot enough, solder a single pin, either Gnd or 3v3 once the solder has cooled you can remove the Bluetac and carry on soldering the rest of the board, I don't like leaving it there while I solder the rest of the board as it can get a bit stinky if it gets hot.

STEP 4: Hook It Up to Your FTDI/Uno

As I've said before, I use an Uno instead of an FTDI, using an FTDI is no different, I just can't be asked to hunt one out when I need it.

So with your Dupont wires, hook them up as follows.

Header Colour Arduino

3V3 Red 3V3

RX Orange TX

TX Yellow RX

GND Black GND

Check your connections over paying particular attention to the Red lead, make absolutely sure it's connected to 3V3 as connecting to 5V will likely kill the ESP8266.

STEP 5:

Download the Sonoff.ino sketch and save it to a folder called Sonoff.

Load it into your Arduino IDE and edit the following lines:

Line 25:
const PROGMEM char* MQTT_CLIENT_ID = "sonoff";

Change "sonoff" to something suitable for your installation.

Line 26:

const PROGMEM char* MQTT_USER = "MQTT User";

Change "MQTT User" to the user name used to connect to your MQTT server and

Line 27:

const PROGMEM char* MQTT_PASSWORD = "MQTT Password";

Change "MQTT Password" to your MQTT servers password

Lines 28 and 29:

const char* MQTT_LIGHT_STATE_TOPIC = "room/sonoff/status";

const char* const char* MQTT_LIGHT_COMMAND_TOPIC = "room/sonoff/switch";

Set the state and command topics inline with your naming conventions

Line 79:

WiFi.hostByName("your_mqtt.server.co.uk", MQTT_SERVER_IP);

Change "your_mqtt.server.co.uk" to the fully qualified domain name of your MQTT server.

Give your changes the once over to make sure they are correct then verify the sketch correcting any Issues.

Once all issues are fixed, hold down the button on the Sonoff and connect your USB lead, this puts it into flash mode ready to receive the sketch.

Make sure your IDE is connected to the right port and send the sketch over.

STEP 6: Connect the Sonoff to the Wireless Network

Open up the Serial Monitor in the Arduino IDE, change the baud to 115200

If this Sonoff has never had a sketch uploaded to it using the WiFiManager library you should be seeing something similar to this...

Ver: 1.3

*WM:

*WM: AutoConnect

*WM: Connecting as wifi client...

*WM: Using last saved values, should be faster

*WM: Connection result:

*WM: 0

*WM: SET AP STA

*WM:

*WM: Configuring access point...

*WM: ThingMaBob

*WM: AP IP address:

*WM: 192.168.4.1

*WM: HTTP server started

If not and you would like to start from scratch, you will need to uncomment line 63: //wifiManager.resetSettings(); resend the sketch to the Sonoff, then comment the line out again and resend once more to the Sonoff.

Now we are set to connect the Sonoff to your local wireless network.

Using a smartphone or a pc with a WiFi adapter bring up the list of available networks.

Click on the network named ThingMaBob and connect to it.

You will then need to Authenticate, on Android clicking the Authenticate icon at the top of the screen will take you to the pages built into the WiFiManager, you can now select your local network and then enter your wifi key.

When you click save the settings will be written back to the Sonoff so that it will automatically connect on boot. The Sonoff will now reboot and connect to your local WLAN and attempt to connect to the MQTT server.

STEP 7: Adding the Sonoff to Home Assistant

I separate all of my devices into separate files which I then include in the main configuration.yaml.

Please add the device to wherever you keep yours.

platform: mqtt

name: "sonoff"

state_topic: "room/sonoff/status"

command_topic: "room/sonoff/switch"

payload_on: "ON"

payload_off: "OFF"

optimistic: false

You can alter the names to whatever you like, but you must make sure state_topic and command_topic match what you entered in the sonoff sketch on lines 28 and 29.

Finally run a test to make sure everything is ok with your new entry

/usr/local/bin/hass -c ./ --script check_config

If all appears ok restart hass service

hass-daemon restart

You should now see the new switch in the home assistant gui. Check you can toggle the switches from within Home assistant.

Now you can hook your device up to the switch and reassemble the case. Please make sure if there is an earth wire in the cable that continue the earth. I just join the earth together with a chocolate block

27 Comments

What is command for On and Off. "mosquitto_pub -h localhost -t "room/sonoff/switch" -m "xxx"
What is xxx?
payload_on: "ON"
payload_off: "OFF"
Can anyone tell me the Github link for FS.h?
Thanks
I have these all over the house and I never have changed the software. My espresso machine never has " Popped" and I use one on a remote heater also. So. I dunno. Guess they are magic.
The reason I use my own firmware is to integrate them with my home automation solution, Home assistant. Out of the box they don't support mqtt. I also don't like the fact they are exposed to the internet.
I see. Thanks. My router has a firewall enabled. I would have thought that was good enough.
If you have a device inside of your network establishing a connection to the outside, through your firewall, it could be a vector for attack. As I said, not a risk I'm gonna take ;)
outohstyle, the problem is they are all connecting back to a server in China. Over which you have no control or any idea of what data is being pushed back from your network to the server or more worryingly can those servers be used as a point of intrusion into your network?

Only last weekend some Hive cameras where hacked in the US and a fake announcement was made over them to say that nuclear war had broken out between the US and North Korea.

Not a risk I'm prepared to take ;)
I have one question
I am running Homeassistant and MQTT succesful.
I get response status back to homeassistant when I use manual switch on sonoff.
But when I switch on - off in homeassistant It seems "void setLightState()" doesn't get called .
I can only see the trigger of the payload in debug once I made a manual switch trigger.
I have checked all parameters in debug .Do you have any suggestions ?

Obviously with out seeing your configuration It's nigh on impossible too diagnose.

I would suggest you start looking at the configuration files in Home Assistant, they are based on YAML which is an absolute PITA to work with at times.

I'm having I say I'm havin trouble getting this to work on a newer version of the Sonoff basic. I have v1.1 2017-5-5. It won't work at all using the latest esp8266 libs. I found another site that suggested reverting to v2.30 of the library and using DOUT as the Flash mode. When I do those two things I can make this run on the two boards I have. On both I can connect and configure my WiFi and connect to my MQTT broker, but after about 20 seconds it crashes and disconnects from the broker. Can you offer any guidance on the setup. The version I have has an 8Mbit flash chip so I set it up for 1M (128 SPIFFS). I'm sure it is some kind of compatibility issue but I'm a newbie to Arduino and the ESP8266.

Sorry to hear your having issues Foghorn, All of mine seem to be rocksteady thought they are all quite old and I'm not sure what version they are. I'll pop one at the weekend and see if I can see any versions on the boards.

With regards to libraries I'm using 2.4.0-rc2 of the board library and 2.6.0 for pubsubclient.

I have the programming settings as generic esp8266, Flashmode DIO, Flashsize:512K (64K Spiffs), debug disabled, debug level: none, reset: CK, Crystal F: 26Mhz, Flash F: 40Mhz, CPU F: 80Mhz, Upload: 115200

Thanks for the quick response El Ape. I tried 2.4.0-rc2 and it worked the same as 2.3.0. I am using pubsubclient 2.6.0 already. I tried Flashmode DIO and it wont respond after boot. When I switch back to DOUT I am back to it starting ok then getting a socket error on the MQTT server.

At first I thought it was crashing but that was a bad assumption. I now see that it is just dropping the connection to the mqtt server. On the server side (Mosquitto server running on a RPI3) it says:

Client xxx has exceeded timeout, disconnecting.

Socket error on client xxx disconnecting.

After a few minutes more the sonoff client shows

INFO: Attempting MQTT connection.....ERROR: failed, rc=-2DEBUG: try again in 5 seconds.

On the next attempt it connects to the server successfully again, then looses the connection again.

I will keep digging deeper and try to better understand what the MQTT server expects. Could just be a server setting? When I was a kid they told me if I dig deep enough I will end up in China. Now it appears to be true after all:)

El Ape, I made a change in the code to call client.loop(); inside of the loop() function like the example on pubsubclient. It works nicely now. I can turn the load on and off and receive status from another client on android. I wouldn't think I would need to call client loop for every program loop and I don't understand how the keep alive timer works. Will dig some more. Almost to China. Maybe when I get there I'll find those ESP8266 modules I ordered from Aliexpress 3 weeks ago....

Hey Foghorn.,

nice one, thanks for letting me know. Now I've finished moving all my services over to RasPi's. I'll have a look over the weekend at the code and check out my switches to see if I made a boo boo when I uploaded the code to here. I've had one sat on my desk for a fortnight now that I am supposed to be finishing off with OTA code and it hasn't skipped a beat in all that time so I'm guessing I have done something stupid with the uploaded code ;)

Hi Edgar,

couple of things,

Is the MQTT Server running on the same server as your HASS.IO installation?

If so you will need to point to this address.

Do you have an internal DNS server and have you set up your MQTT server A record in it?

If not, you will need to remove or remark out the line

"WiFi.hostByName("your_mqtt.server.co.uk", MQTT_SERVER_IP);"

And add the following to the top of the code with the other declarations.

const PROGMEM char* MQTT_SERVER_IP = "your.i.p.address";

Of course your.i.p.address needs to be replaced with the address of your HASS.IO/MQTT server.

Cheers

Hi Ape,

Thanks for this amazing tutorial, I'm using Home Assistant Hass.io with Mosquitto broker, I can't found the MQTT server adress :(

hello to all, I have encountered a problem on the settings mqtt, the sonoff connects to the network but then begins to give an error: INFO: Attempting MQTT connection ... ERROR: failed, rc = -2DEBUG: try again in 5 seconds. and then the loop continues indefinitely would someone know how to help me? thank you very much

Hi there,

This error message means the device is not able to connect to your MQTT server. Do you have any other devices connecting to the MQTT server? Have you set the correct address for the MQTT server, is the IP address resolving correctly for you MQTT server?

Is you MQTT Server running?

Regards

More Comments