Skip to main content

Using ESPEasy with Home Assistant via MQTT

Preface: I've just started playing around with Home Assistant on a Raspberry Pi and exploring the world of MQTT to control devices on the network. Learning curve is a bit steep but worth the effort as MQTT is very fast.

The hardware and software tools I'm using are as follows:
2 x Sonoff relay units
2 x NodeMCU Boards
ESPEasy firmware (must be version 121 or above as that contains the MQTT 'retain' flag option.
Home Assistant software on Raspberry Pi2
MQTT Test Software:
PC: MQTT.fx
Android: MQTT Dashboard



IMPORTANT: To ensure ESPEasy MQTT works with Home Assistant, make sure you set the MQTT protocol to OpenHAB MQTT under the config tab.

I have flashed the Sonoff units with ESPEasy (R121) and there is plenty of info online on how to do that. The code to use with the rules section for relay control via the switch is below. It will also report the relay state via the LED if remotely controlled via MQTT.
on relay#state do
  if [relay#state]=0
    gpio,13,1
  else
    gpio,13,0
  endif
endon
on button#state do
  if [button#state]=0
    gpio,12,0
    gpio,13,1
  else
    gpio,12,1
    gpio,13,0
  endif
endon
Note that the items highlighted refer to devices that have been configured in the devices list below and must match (case sensitive).




To control the relay via MQTT, send /{devicename}/gpio/12 with payload 0 or 1 so for ESP03 it would be:

/ESP03/gpio/12 with payload 1 for on. Note there is no trailing forward slash (/) after the gpio number but there is one preceeding the {devicename} if the ESPEasy defaults are left. Note: The sonoff has the relay connected to gpio 12 and the LED on 13.

If you subscribe to {devicename}/relay/state you get a response back from the sonoff whether the relay is flipped using MQTT or the button (either a 0 or 1).

If you loose access to any ESP8266 device with ESPEasy on it, you can connect to it’s local AP when it goes into AP mode which is normally ESP## and use the passphrase ‘configesp’. Once connected to that AP, you can reach the device on 192.168.4.1 where you can reconfigure the WLAN or MQTT broker information.

How to get feedback using MQTT on a ESP8266 device when you are using /{devicename}/gpio/{pin#}
You do not need to configure anything on ESPEasy for gpio control so if you want to turn a relay on that is configured on gpio 14, you can send either send HTTP or MQTT as shown below:

MQTT:
/{devicename}/gpio/{pin#} with payload of 1 for on or 0 for off.
HTTP:
http://<ESP IP address>/control?cmd=GPIO,<pin>,0
http://<ESP IP address>/control?cmd=GPIO,<pin>,1

If using http, the webpage will return the pin state. If you are using MQTT, you will need to subscribe to {devicename}/status and then by sending the following, you’ll get a json report on that subscription.

Sonoff via MQTT (two ways)
Publish to {devicename}/cmd with the payload gpio,12,0 to turn the relay off (and LED if you have rules set) or gpio,12,1 to turn the relay on. You’ll get the following back on {devicename}/status:


On:
{
"log": "GPIO 12 Set to 1",
"plugin": 1,
"pin": 12,
"mode": "output",
"state": 1
}

Off:
{
"log": "GPIO 12 Set to 0",
"plugin": 1,
"pin": 12,
"mode": "output",
"state": 0
}


You can also publish status,gpio,12 directly to query the gpio pin. This also works directly in the serial console. Just type status,gpio,12 to check the relay state and you’ll get Jason back like this:

>status,gpio,12
{
"log": "",
"plugin": 1,
"pin": 12,
"mode": "output",
"state": 1
}

Many thanks to this post.

I used Sonoff configuration mentioned here which provides feedback on /{devicename}/relay/state.

This was mirrored on my NodeMCU device and the GPIO pin that was used for my relay was configured as a switch under the devices tab. Simply choose the gpio pin you are using for the relay output under the 1st GPIO section as shown below.


If you then subscribe to /{devicename}/relay/state, when you publish a 0 or 1 to /{devicename}/gpio/{pin#}, you will get either a 0 or 1 back. If you have more than one relay, best to call them say relay12 and relay14 (corresponding to the GPIO #) so you know what relay fires if you monitor /{devicename}/+/state.

Note: The downside of configuring the GPIO as a switch input to allow MQTT status reports (at least during my testing) is that if you configure the pin using /{devicename}/pwm/14 and payload from 0 to 1000 for dimming the LED, this will confuse ESPEasy and you’ll get repeating state messages alternating from 0 to 1 and back again until you send pwm 0. Best to configure another GPIO if you want PWM control.

The full ESPEasy command reference is available here.

And lastly, below is an extract from my swiches.yaml file which shows how Home Assistant is configured with MQTT

# switch 1:
- platform: mqtt
  name: "GPIO14"
  state_topic: "/ESP01/relay14/state"
  command_topic: "/ESP01/gpio/14"
  payload_on: "1"
  payload_off: "0"
  qos: 1
  retain: true
 
# switch 2:
- platform: mqtt
  name: "Sonoff1"
  state_topic: "/sonoff1/relay/state"
  command_topic: "/sonoff1/gpio/12"
  payload_on: "1"
  payload_off: "0"
  qos: 1
  retain: true
 
# switch 3:
- platform: mqtt
  name: "Sonoff2"
  state_topic: "/sonoff2/relay/state"
  command_topic: "/sonoff2/gpio/12"
  payload_on: "1"
  payload_off: "0"
  qos: 1
  retain: true
 
# switch 4:
- platform: mqtt
  name: "Sonoff3"
  state_topic: "/sonoff3/relay/state"
  command_topic: "/sonoff3/gpio/12"
  payload_on: "1"
  payload_off: "0"
  qos: 1
  retain: true

I trust this has been helpful in some way as it took me many weeks to get here but so far it is working well and rock solid.

Oooh, and my advanced settings page from my ESPEasy R121 is shown below (user request)

Comments

  1. Excellent article..Would you also please screenshots of the ESP EASY advanced for sonoff..i am having issues with the subscribing topic

    ReplyDelete
  2. Thank you very much. Your blog is very useful for people who use Home Assistant and cheap Sonoff. I am using almost 20 of Sonoffs with Home assistant in my house. They work very well with home Assistant except that my Sonoffs always take very long time (from 10 minutes to 3 hours) to start working properly after booting up from electricity recovery. I would like to try ESPEasy. I know how to flash Sonoff via Arduino IDE. But I was wondering how to flash Sonoff with ESPEasy. When I downloaded ESPEasy R120, there are ESPEasy_R120_512.bin, ESPEasy_R120_1024.bin and ESPEasy_R120_4096.bin and also some of .ino files. I don't know which correct one should I use. Do I have to flash with .bin file? Do I have to upload .ino file later? and Is ESPEasy.ino the file used to upload to Sonoff? If you could kindly suggest, I would be very glad. Thank you in advanced.

    ReplyDelete
    Replies
    1. You're welcome. Took me weeks to compile all that stuff online and many late nights testing. Flashing is dead easy. In your download, there is a file called flash.cmd. Simply double click that, choose the COM port your programmer/Sonoff is connected to by just entering a number (after putting the Sonoff in programming mode), enter 1024 (the flash size of a Sonoff) and then the version you want to upload, in your case 120. It will push the file to your Sonoff and you're done. Power cycle then connect to the ESPEasy AP that appears using the password "configesp". From there, connect to it via a web browser on 192.168.4.1. If you want to compile a newer version, info on how to do that here http://www.esp8266.nu/index.php/Tutorial_Arduino_Firmware_Upload

      Delete
  3. Whoops. Make sure your ESPEasy is set to OpenHAB MQTT if you want it to work with Home Assistant.

    ReplyDelete
  4. Peter
    Thank you for this detailed explination, has save me a lot of time.
    Not sure if this is the right place to ask, but i have a blinds running of the SDP8266-12E with ESPEasy 120.

    My yaml configuration is like this:
    switch:
    platform: command_line
    switches:
    bedroom_blinds:
    command_on: curl -k http://192.168.1.128/control?cmd=Servo,2,16,170
    command_off: curl -k http://192.168.1.128/control?cmd=Servo,2,16,5
    # command_state: Bedroom Blinds
    value_template: '{{ value == "online" }}'
    friendly_name: Bedroom Blinds

    As you can see I am using command line switch, so I did not have to do anything on the ESP

    What I would like to know, is it possible to do this with MQTT

    ReplyDelete
    Replies
    1. Hi Chrisl. Sorry, that ones a bit out of my depth. Best to post on the HA forums.

      Delete
  5. Hi xbmcnut! Mad props for this documentation. I just got a bunch of the electrodragon dual-relay boards and when I model my rules after yours, the relays just click on/off repeatedly.

    I'm on r147 and going to try some different releases, but wondering if you had any odd challenges with the electrodragon models or if i'm just having some growing pains.

    ReplyDelete
    Replies
    1. Thanks. I found the Sonoff rules don't work so well with the Electrodragon. Here are some notes I made regarding ESPEasy on the ED.

      To program with ESPEasy, hold down button 2 while powering up. Flash size is 4M like NodeMCU.

      Relay 1 is on GPIO13, active high
      Relay 2 is on GPIO12, active high
      The user LED is on GPIO16, active high
      BTN1 is on GPIO2, active low
      BTN2 is on GPIO0, active low
      DHT sensor is on GPIO14
      * OP1 and OP2 output LED’s are tied to the relay control transistor and not a GPIO so will always track relay state.

      ESPEasy Rules:

      on button1#state do
      if [button1#state]=0
      gpio,13,1
      else
      gpio,13,0
      endif
      endon
      on button2#state do
      if [button2#state]=0
      gpio,12,1
      else
      gpio,12,0
      endif
      endon


      If you want to have separate inputs and outputs, do not use the rules above and instead use Automation inside Home Assistant. Using the code above will always link the input to the output (relay).

      To have the inputs act as digital inputs to track sensors states, the device settings for button1 and button2 need to define the switch as a ‘Normal Switch’. Hold the button down will register 0, letting it go will register 1.

      To use the buttons with rules in order to toggle the relay, the “Switch Button Type” needs to be defined as a “Push Button Active Low”.

      If using the Electrodragon with ESPEasy and Home Assistant via MQTT, the “Send Boot state” must be unchecked otherwise the button will send its state (high) on boot and toggle back based on the “Retained flag” on the MQTT broker. This will erroneously send ‘Garage Opened’ and ‘Garage Closed messages’, one after the other.

      Hope that helps.

      Delete
    2. Yes, most helpful! I have the relays working in HA using rules. I need both rules and physical buttons to work (wife acceptance factor) so it looks like I will need to looking into using HA automation. You have a paypal or bitcoin address? Would gladly contribute to the nerd-hardware/beer fund.

      Delete
    3. Thanks again for all your help and examples. I found a way to properly control an esp8266 with relay on one gpio and button on another gpio using espeasy rules.

      https://community.home-assistant.io/t/ha-ecoplug-wion-mqtt-success/8851

      Delete
  6. Where do I put in the logic to actually have the button to work? I'm currently using my Sonoff in a stand-alone mode, but I would still like the button to work. Thanks!

    //M

    ReplyDelete
  7. I posted earlier on the rules, but I have figured that out now.

    I have edited your rules a bit as I could get the button to turn off on first press if the relay was turned on using (in my case) http. On the second press it did work though :)

    I don't use the state of the button, but only look at the relay state and act accordinly:

    on Relay#state do
    if [Relay#state]=0
    gpio,13,1
    else
    gpio,13,0
    endif
    endon
    on Button#state do
    if [Relay#state]=0
    gpio,13,0
    gpio,12,1
    else
    gpio,13,1
    gpio,12,0
    endif
    endon

    I have tried to set the state of the button as well, but that don't seem to work out, so for now I'm just ignore it completely..

    //M

    ReplyDelete
  8. Such a great tutorial. This is exactly what i needed, just moving over form Domoticz with sonoff devices to MQTT with home assistant on the raspberry pi. I have spent a couple of hours getting it all setup and working so if i press the button on the sonoff the relay switches on (also the led) and then the switch status is updated in home assistant as on and then also works for off and from being controlled from home assistant. My only issue is that if i switch the power off to the sonoff and then switch it on its default is to switch relay and led to on. This happens if the relay is on or off before the power is turned off and back on. Is there a way to restore the last state when powered up or at least when powered up set to off. It just seems with this setup if i have a power cut when it all comes back on every sonoff switch will be set to on. Any help would be very grateful.

    ReplyDelete
    Replies
    1. Thanks for the feedback. Ensure 'send boot state'is off under the button and relay device settings.

      Delete
  9. Hello pete, how are you? I want to know the following: I have a sonoff RF version. My question is: I can use sonoff with the physical button and at the same time use the home assistant. If I turn on a lamp in the home assistant it stays on but if I turn it off in the physical button of sonoff the state in the home assistant changes? If it is possible can I do it like?

    ReplyDelete
    Replies
    1. I am well, thank you. And yes, that's how it works. Any client (HA, Phone app etc.) that is subscribing to the topic that the Sonoff is publishing to gets the updates. My latest video here shows that in action https://www.youtube.com/watch?v=s5gbdy0niAs

      Delete

Post a Comment

Popular posts from this blog

My Notepad++ tricks when editing YAML files in Home Assistant

To comment out a whole section in one go: Highlight the text you want to comment out and use CTRL + Q. If you do this at the start of a line, it will only comment that line. CTRL + Q is toggle mode (comment on/off). CTRL + K will allow you to add multiple comments one after the other.

Installing ha-bridge on your Raspberry Pi

EDIT: Updated 14th June 2017 to reflect version 4.5.5. Default port is now 80 to keep Google Home happy and service now supports MQTT! Advice on backups also added 7th Feb. Version 4x also supports adding a Home Assistant instance which is great! Want to control your Vera, Harmony hub or Home Assistant entities with your Amazon echo or Google Home? ha-bridge is the best way to achieve that and installation is actually quite easy and takes less than 5 minutes. Here are the steps.