How to Connect openHAB and Tuya Devices

 

Smart Switches are pretty much a must-have on any home automation project but surprisingly, the market isn’t flooded with these type of devices yet.  In addition to this, most of the options aren’t very affordable.

Recently, I got the opportunity to test some devices from SmartHomeProducts, some smart switches among them. They work great but unfortunately, they aren’t compatible out of the box with openHAB.

This is not the end of the story though…

On this tutorial, I have compiled and explained a couple of ways you can get openHAB to work with smart switches from SmartHomeProducts or any devices that use the Tuya firmware.

If you are looking to get some Smart Switches or want to know how to connect openHAB and Tuya stick around.

 

Description of the Products

First of all, I would like to thank the guys at SmartHomeProducts for providing the samples for testing. They were very confident in their product and ready to answer every question that I would throw at them. They are a US based company that distributes smart devices that use the Tuya Firmware.

I have tested several products but my favorite ones are the smart dimmer (very good looking) and the mechanical switch. They have other switches as well, but the mechanical one is more responsive than the others and feels more natural.

 

3rd Party Integrations

Out of the box, these devices are compatible with the SmartLife App, Alexa, Google Home and IFTTT.

Unfortunately, they are not compatible with open-source Home automation systems, at least AS-IS.

If you have been following the blog for some time you will probably know that I am a big advocate for Open Source Home Automation Systems, like openHAB or Home Assistant. Unfortunately, there is no connectivity out of the box for these kinds of systems.

However, this is never the end of the story for us, makers, we love a good challenge. Even if there is no support out of the box, there are definitely alternatives and I will tell you about them.

On this post, I want to go through 2 different options, the first one is quick and more or less clean. The second one is a bit hacky but not too complicated to implement. Each of them has its pros and cons so let’s get started…

 

Tuya Smart Home Devices

As I said earlier this method should cover pretty much every Tuya device out there that uses the ESP8266 chipset. Here is a list of the different products I have tried myself in case you want to check them out.

Description
Smart Outlet Check Price
Smart Light Dimmer Check Price
Smart Wall Switch Check Price
Smart Plug Check Price
Smart Bulb Check Price

Table of Contents

In case you want to jump directly to one particular method, go ahead and click on the link.

  1. Connecting openHAB and Tuya using IFTTT
  2. openHAB and Tuya: Local Control using a MiM Attack.
  3. Flash Tuya Devices with Tasmota Using Tuya-Convert

 

Connecting openHAB and Tuya using IFTTT

Although the set of devices from SmartHomeProducts aren’t supported by openHAB directly, they do support IFTTT out of the box and we can use it to bridge the communication.

 

Advantages of this Strategy

  • The strategy is fairly clean to implement.
  • It does not require too much technical knowledge.
  • Once implemented, it is very stable.

Disadvantages of this Strategy

  • We introduce an additional point of failure.
  • Bridging the connection through IFTTT may introduce a 1 or 2 seconds delay sometimes.
  • There is no feedback from the devices. This means that openHAB doesn’t know if the switch is ON or OFF.

Let´s get started with the process.

 

Creating an IFTTT Account

In order for this process to work for you, you need an IFTTT account. It is completely free and it takes about two minutes to set it up.

I already wrote a tutorial about openHAB and IFTTT  and if you have questions setting up the account you can definitely check it out. However, in the part that relates to connecting IFTTT to openHAB I will be using a different approach so make sure you come back to this post.

 

Connecting the Devices with the SmartLife App

Before you start connecting the devices to IFTTT, it is required to register them in the SmartLife App. That will connect your new smart switches to the Tuya cloud and will make them available to IFTTT.

The user guide that comes with the products is very minimalistic but more than sufficient to get them up and running in about 5 to 10 minutes.

Here you have a small summary of the steps:

Before you start the process you may want to have you wifi password in handy, you will need it.

  1. Download the SmartLife app on your smartphone.
  2. Click on add devices and select the device type.
  3. Set the device in pairing mode (normally holding the ON button for more than 5 seconds)
  4. Go ahead and pair the devices.

 

Connecting Tuya Devices to IFTTT

Let’s get to the good stuff, go ahead and login into your IFTTT account. It is time to start adding devices.

Before we do that, I want to give you some context.

openHAB actually has a binding to connect directly to IFTTT, however, after testing the binding for quite some time I noticed that there were significant delays triggering some of the events. I attribute it to the fact that there were too many clouds involved in the process,  Tuya Cloud + IFTTT Cloud + openHAB cloud…that is pretty much the whole storm.

For this tutorial, I will be using a pretty cool functionality from IFTTT which is called Webhooks. It basically allows you to trigger any IFTTT applet using a web service call.

This method has endless potential becuase you can connect any device supported by IFTTT to any home automation system that supports web service calls (pretty much all the open source ones).

This method has given me much better results than using the openHAB binding and it is also more versatile. If you have any device for which there isn’t an openHAB binding but it is supported by IFTTT, here is how you can use it.

Let’s get started…

The first step is to login into your IFTTT account and create a new applet. Every applet involves a trigger and an action, so let’s go ahead and select the trigger.

openHAB and Tuya

 

IFTTT will show you a very long list of services, you can pick webhooks and then select the only available option, Receive a web request.

 

openHAB and Tuya

 

 

 

 

openHAB and Tuya

 

 

The only configuration required for the webhook is the event name. Choose something meaningful since you will have to use it in your web service call.

openHAB and Tuya

We are done with the trigger so let’s go ahead an add an action.  Among the array of options provided by IFTTT you will find SmartLife. Select it and connect to it.

After connecting, you will be prompted with a window to put on your SmartLife credentials, the same ones you used in the smartphone app.

 

openHAB and Tuya

 

 

openHAB and Tuya

 

openHAB and Tuya

 

 

 

IFTTT will now display all the different actions available. You will have to create one different applet for every different action that your device provides.

For example, if I am installing a smart switch, I have to repeat this process twice, one for the ON function and one for the OFF function.


openHAB and Tuya

At this point, you should have already created one applet per action that your device allows. I am adding a switch so I only need two applets linked to two webhooks events.

KITCHEN_ON

KITCHEN_OFF

In order for you to trigger the applet, you will need a token from IFTTT which you can get from the webhook settings page. Your token will be the funky string of characters that comes after /use/ in the URL.

 

openHAB and Tuya

 

The web service endpoint will look like this:

After replacing the details:

 

Everything is ready to test the event. Give it a shot with a simple curl command to make you followed the steps correctly.

 

If everything went OK, this command should turn on your light.

 

Trigger IFTTT Webhook using openHAB

To trigger the web service request from openHAB, you will need the HTTP binding, no worries it is very simple to use.

I like to install my bindings using the configuration files but you can use PaperUI if you are more comfortable with it.

Edit the file  /etc/openhab2/services/addons.cfg. 

It will have different parameters to configure, you just care about binding though.

 

Add http1 at the end of the list and wait for a couple of minutes until openHAB installs the binding. Once the binding is installed you can create an item in openHAB to control the Smart Switches.

Edit your preferred items file, they all should be under /etc/openhab2/items/ and create an item as follows:

 

That’s it, openHAB and Tuya are now integrated. Now you can use that item as you would with any other. Don’t forget to replace the event name and the token from IFTTT with your own.

 

openHAB and Tuya: Local Control

Using IFTTT to connect the Tuya devices to openHAB has obvious disadvantages, mainly the delay triggering the event. If you are not happy with the other solution, keep reading, this one has it all but it needs some legwork.

With this method you will be able to control the devices locally (no cloud involved) with minimal to no lag.

Before I go any further, I would like to thank AgentK  for putting together the MQTT wrapper and codetheweb for the TuyaAPI. They have done all the work that made this connection possible, I have only put the information together.

Also thanks to Arilux in the openHAB forums for compiling all the info. His method to retrieve the local key didn’t work for me but it is worth checking if you have issues/reservations with the process on this post.

Preconditions:

Before you go ahead with the installation there are three things to keep in mind:

  • You should have an MQTT broker connected to openHAB.
  • All the devices that you want to control with openHAB should be added to the SmartLife App first.
  • Make sure you do all the steps in the process using the openHABian user.

Installing Required Node Modules

  1. SSH into the Raspberry pi and navigate to /etc/openhab2/scripts
  2. Install all the required NodeJS Modules

If you are using openHABian you will most likely run into permission issues, you can install the package with sudo although I would fix the permissions instead of doing that. You will avoid future issues.

 

MITM Attack

Here is the funky part of the project…All the Tuya devices are identified by 3 parameters; ID, IP and Local Key. The first two of them are very easy to get, the last one…not so much.

The Tuya devices use the local key to secure the communications between the cloud and the device. We would need to decrypt the messages between the SmartLife App and the Tuya Cloud, and in a way, that is what we are doing.

We will do something called Man-In-The-Middle Attack. This basically means sitting between the SmartLife App and the internet reading the communications between the two.

It sounds very complicated and in a way it is, however, the contributors of the TuyaApi have made the process very simple.

The first step is to create a proxy in your Raspberry PI that will bridge the connections.

  1. Use Anyproxy to generate a certificate.

 

openHAB and Tuya

Anyproxy will generate a certificate that you will have to download from your smartphone and trust. If you don’t trust the certificate, your phone will detect there is something going on and will shut down the communication.

2.  Execute the list function in the tuya-cli app in order to start the MITM attack.

 

If everything went OK, a gigantic QR code should be generated in the terminal.

openHAB and Tuya

 

Using a QR Scanner App in your smartphone, go ahead and scan the code. The code is storing a URL to download the certificate. Once you download it, your phone will ask you if you want to trust it, which is required for you to continue. You should untrust it as soon as you are done with the tutorial.

3. Now that you have installed the certificate in your phone, it is time to configure your connection in order to use the Proxy that you have just created. Things might be slightly different here, depending if you have an Android  or an iPhone. The details of the proxy should be right below the QR code, IP and port.

Don’t forget to make sure that you are on the same wifi as the smart switches.

Now your phone should be connected through the proxy and all the connections will be bridged through the Raspberry Pi.

4. After the proxy is configured in your phone, open the SmartLife App and refresh the devices.

openHAB and Tuya

 

Like magic, the list of Tuya devices should show up on your terminal, including the elusive local key. Copy those details and keep them in handy, maybe on a spreadsheet so you can have all the information organized.

 

Configure the Tuya-MQTT Wrapper

This script will act as an interface between openHAB and the Tuya devices using MQTT.

Before you continue, gather all the details on a spreadsheet so you are ready to configure everything. You will need primarily 3 data points for each Tuya Device that you want to control.

  • Id
  • Key
  • IP

You already got the id and key from the prior step so you only need the IP. There a few ways you can get this.

  1. First, get the MAC address of the device from the device properties in the Tuya App.
  2.  Go to the admin page of the router and check the IP assigned to the device with that MAC address.
  3. If you don’t have access to the router or just can’t do it this way, you can use the following command in Linux.

 

Make sure you input the MAC address in lower case.

Name ID KEY IP
Bathroom Switch 217261bf250809 bc55c9230a 192.168.1.101
Kitchen Switch 024285bcdd97ba 920d0cf7bc 192.168.1.107

 

Once you have all this information, you can move forward with the next step.

  1. Navigate to /etc/openhab2/scripts
  2. Clone the Tuya-MQTT repository from GitHub

3. Navigate to /etc/openhab2/scripts/tuya-mqtt and create a configuration file.

4. Edit the Configuration file with the details of your MQTT Broker.

Before you go ahead with these steps, make sure your MQTT Broker is up and running and it is connected to openHAB.

You will need at least, a thing and an item.

 

openHAB Things

Let’s define a new MQTT generic thing to communicate with the Tuya-MQTT Script.

There are a few details you need to pay attention to here:

Fill out correctly the details of the MQTT broker:

Configure the tuya topics correctly:

State Topic: The topic where the devices publish the state of the device.

tuya/lightbulb/{ID}/{KEY}/{IP}/state

Example:

tuya/lightbulb/02428575b2fa97ba/920d0ca09f7bc/192.168.1.102/state

Command Topic: The topic where the device receives ON and OFF commands.

tuya/lightbulb/{ID}/{KEY}/{IP}/command

Example:

tuya/lightbulb/02428575bcda97ba/920d0ca9f7bc/192.168.1.102/command

I am using the object lightbulb in the topic, but it is valid for smart switches as well.

openHAB Items

The items are much more straight forward…

 

Now you can use the items in openHAB to control the Smart Switches. This approach takes a bit more time but once it is up and running, you can set and forget  about it.

 

Run the openHAB Tuya Script as a service

This is optional but I highly recommend you to do it, otherwise, you will have to bring up the script every time you reboot your openHAB server.

You can test your script first to iron out potential issues:

 

Navigate to /etc/openhab2/scripts/tuya-mqtt and run the following command:


You are good to go! Restart your raspberry pi and test your new openHAB and Tuya Integration.

 

Troubleshooting

Forever path is not found

If you run into issues becuase the forever command is not found check this out.

Forever-service not found for Sudo

Similar to the issue above but when adding the script as a service. Check this out.

That’s all the is, if you have feedback on the topic make sure you leave it on the comments.

 

 

Flash Tasmota on Tuya Devices using Tuya-Convert

The next approach and, the one I currently use for all my Tuya devices, is based on the Tuya-Convert project. The Tuya-Convert project allows you to free up from the cloud most of the Tuya devices that are based on the ESP8266 chipset.

You may have noticed that I have said most of and the reason is that Tuya has been trying to prevent their devices from being flashed, which they have achieved at least during some time.

The relentless community behind the project recently released a new version that makes this hack possible again.

The Tuya-Convert hack basically allows you to install an ESP8266 compatible firmware into your devices, like Tasmota, and lets you control them locally using HTTP or MQTT. I flashed all the devices and I have been using them for two months. I couldn’t be happier, Tasmota is rock solid and has endless possibilities.

Let’s get started.

Requirements

There are some hardware requirements that you need to fulfill to perform this hack. I will tell you what I used but I am sure it is not the only option.

  • Raspberry Pi 2 with Raspbian Installed.
  • Wifi Dongle Linux Compatible. I tried a few different ones and I struggled with them until I got the Panda PAU05. In case you need to buy one, you should consider that one.

 

Download and install the Tuya-Convert Project

1. Clone the Tuya-Convert project. 

 

 

2.Navigate into the Folder

 

3.Install Prerequisites

This is a very long process, it can take 20 to 30 minutes so go get yourself some coffee while you wait.

 

Flashing Process

1. Open a second window to monitor the logs.

the logs files are created the first time you execute the script so you won’t see anything until you start running it.

2. Have your phone in handy to connect to the wifi that the script will create.

3. Start the Flashing Process

The first screen will show you the usual disclaimer. Please, keep in mind that you are doing this at your own risk and you could potentially brick your device. I have done it with several devices, however, and I haven’t had any issue so far.

Type yes, hit enter and get ready to start the party.

4. Before you proceed with the next step make sure of the following 2 messages show up. It will be required for you to be able to flash the device. 

5. Connect your phone to the AP created by the script. 

If everything went OK, you should see a wifi called vtrust-flash which you can connect using the password flashmeifyoucan. If you can connect to the wifi but there is no internet, review the logs and check if there was an issue creating the AP.

6. Put the Tuya device Device in Pairing Mode

Put the tuya device in pairing mode. Every device is a little different so check your user manual to make sure you understand how to do it in your device. After the device is in pairing mode, hit enter and wait for the magic to happen.

After a few seconds (minutes sometimes) you should see a screen like this one:

That means you are doing great. The script is backing up the current version of the firmware on the device and getting it ready to upload a new one.  The process should not take more than a couple of minutes and after that, you should see something like this.


Before getting on with the next step, make sure the active user space is user2. If it is not, run the following command!!

Upload Tasmota Firmware

The following command will start uploading the firmware to the tuya device. The tuya-convert project should already come packaged with the latest version of Tasmota but don’t worry if it isn’t the last one since the first thing that we will do is to upgrade the firmware.

Almost instantly you will get the following message on the screen which is extrmely disconcerting since you don’t know what to do next. Don’t freak out, I got you covered.

 

Now you have to keep an eye on the wifi’s in range until you see something like the following showing up.

** In the latest version of the firmare is tasmota-****

Connect to the wifi and use your browser to go to 192.168.4.1.

 

Configure Tasmota

The first screen you will see when you open 192.192.4.1 is a page to configure your home wifi.

Wifi Connectivity

  1. Hit the link below to start searching for wifi’s within range.

 

2. Select your home wifi in the list that pops up.

3. Provide the wifi password.

Make sure you copy and paste it from somewhere to avoid a fat finger situation and then save.

That’s it, your wifi is configured. If everything went OK, the device should now connect to your home network.

If the password was incorrect, it should default to the initial configuration and make the AP available again.

 

You will need to find out the IP that has been assigned to the device, you can normally do this through the page of the router.

Upgrade the firmware

After we provide the wifi connection details, the tuya device will be assigned an IP from your router that you will need to access to it.

Use the configuration page of your router to find out the IP of the new device. It should have a name similar to the name of the AP. Paste the IP on the browser to access the Tasmota configuration page.

Before we configure anything on the device, we should make sure you are up to date with the version of the firmware. Let’s go ahead a do a firmware upgrade.

 

Configure the Tuya Device

Tasmota is a multipurpose firmware but in order to use a specific device, you need to provide the configuration with the different inputs and outputs.  This used to be a big deal but now with the repository that blakadder put together, it is a piece of cake.

  1.  Go to the Blakadder repository to locate your device and click on it.

2. Copy the template and paste it somewhere in handy.

 

 

3. Go to the Tasmota configuration page again and paste the template.

** Make sure you hit activate before saving the template, otherwise it won’t work.

 

Configure MQTT Connectivity

The device is already flashed and functional but if you want to use it with openHAB or any other open-source home automation system through MQTT, it is a good idea to configure the MQTT Connectivity.

Make sure you provide a Topic name so you can identify the MQTT messages.  The commands for every device type are slightly different so you may want to read carefully the commands page

 

This Post Has 19 Comments

  1. Would these devices be candidates for flashing with Tasmota or Espeasy? If so, do you see this as a viable third approach or perhaps an unnecessary complication?

  2. Hi Michael,

    The devices are ESP based so you could flash a different firmware (I haven’t done it myself). There is a project called tuya-convert that you may want to look into. It is definitely a third approach although it requires to tamper a bit more with the device. I personally use the second option and it is pretty stable.

    Have you tried them out?

  3. David, I have not tried these specific devices but many similar 8266-based ones. They work well but do required disassembly and flashing. I’m not sure if your code approach is specific to these devices but flashing essentially makes all of them roughly equivalent. All use simple (well, at least mine) MQTT to transfer data to OH. Sonoff makes an extensive range of devices. It is also workable with general purpose devices like Nodemcu and Wemos.

  4. Hi!

    Your comment shows as Anonymous by the way!

    Yes, they are ESP based so in theory you should be able to flash tasmota with them. There is a project called tuya-convert that goes on that direction. The approach in the post is to control them without flashing the devices. It is what I am using now, maybe I will try at some point.

  5. I am trying your second method. I get to the point where I have the wifi of the phone proxy configured to the HTTP proxy specified in your instructions (where the scan of the image is). the app says it is waiting for request…
    I have tested that the phone is diverting to the proxy by having my iphone safari app go to an internet site. I am sure it us using wifi as I put the phone in airplane mode an tested to an internet site. I stopped the proxy on my computer and was no longer able to connect. After restarting the proxy, I went to Smart Life and did the refresh but Smart Life says Network Connection error, please check the network. In Smart life, I went to one of my switches and in that switch under more, I did the check device network which worked fine. Device information request though gave the network error. I should note that I currently have switches defined that are currently offline in the Smart Life app. Any suggestions on steps I might try to get it working correctly.
    PS my computer is op is Ubuntu 18.04 and it and Iphone are up to date.

  6. I get lost at this section:
    “openHAB Things
    Let’s define a new MQTT generic thing to communicate with the Tuya-MQTT Script.
    Bridge mqtt:broker:mosquitto [ host=”localhost”, secure=false, username=”{USERNAME}”, password=”{PASSWORD}” ]”

    What file is this in?
    I have a Linksio (L’Image) smart socket partially set up, in paperui, but there are no files in /etc/openhab2/things or items.
    Thanks,
    Joe W

  7. Hi Joe,

    By default you won’t have files but they can be created. Just create a file under /etc/openhab2/things and name it mqtt.things (or whichever name as long as the extension is things)

  8. Hi Hiflyer,

    The network error is actually expected. When you refresh the list of devices it should show the keys on the terminal but the phone itself won’t be able to connect to the internet through the proxy. Once you have the keys from tuya you can ditch the proxy and continue with the setup.

  9. I think you missed the point, I do not get the keys. I get “Waiting for request…” on the app on my Ubuntu 18.04 computer. The app on my iphone “smart life” says “Network is unavailable, please check the network” – I do not get the keys.
    I have installed the njstuya as well and it does see produce the list of ip, gwID & productKey but I cannot this is not the localkey which I think your method is trying to get. So any suggestions as to what I might need to do.
    PS I checked in the .anyproxy/certificates directory, which originally had 2 rootCA files which now have many certificates probably based on my web browsing tests. 2 of these certificates are for a1.tuyasus.com.crt and a1.tuyaus.com.key
    Dont really know why they should be there.

  10. Hi all,
    I got all the necessary info about my tuya switch (actually a Jinvoo switch) id, key and ip but I have a question about topic configuration: do I have to replace the “lightbulb” part with “switch” or similar?
    Thanx in advance

  11. Thank you for sharing with us, I always learn something new from your posts.

  12. Thanks a lot for the very good instruction, I like to ‘be able’ to run a man-in-the-middle attack on my own devices 😂

    I got it to work immediately with the four power-sockets I had around, so I got myself four more.
    Unfortunately, they somehow won’t let me do the trick 😏

    I did all the CA-stuff again and this time received eight pairs of ID & key.
    Added them to my MQTT-integration and everything worked out as expected at first.

    Since the last reboot of my system though, I cannot execute anything via MQTT on the new sockets, while the old ones still work fine!?
    Any idea what could have gone wrong, where to look for error-logs or what to re-setup, clear or whatever?
    I just don’t get it…

    One thing to mention: I don’t actually think it has anything to do with the stuff not working, but who knows…
    I realised the first four sockets’ IDs all start with ‘41688601’ followed by the corresponding MAC-address.
    The new ones don’t – they all have completely different first numbers (still followed by the corresponding MAC-address).
    All are the same product from the same vendor, but – and I hope that is the hint for anyone for telling me how to get that ‘hacked’ – when looking in the SmartHome-App, the old ones list a FW-Version of V1.0.0 while the new ones are showing V1.0.1!

    Thanks in advance

  13. Hi Manu,

    I have never seen that issue with the Tuya devices although I recently flashed Tasmota into all of them (very happy with it). Di you try to go through the process again and see if the devices get rediscovered?

  14. Hi L.V. not necessarily, I am actually using the topic for smart switches.

  15. I am impressed. I don’t think I’ve met anybody who understands as much about the topic. You should make a career of it, seriously, amazing blog

  16. Having the same issue as Hiflyer. Nothing is sent through the proxy when I open the Smart Life or Tuya apps. “Network is unavailable, please check the network”.

  17. With the MITM approach will I have to repeat these steps every now and then? Or in other words, does the local jet ever expire?

  18. Hi Antoine,

    You shouldn’t have to. Just make sure your router always assign the same IP.

    Lately I am moving everything to Tasmota though.

  19. Hi Erik,

    I have a smart bulb that I haven’t been able to flash with Tasmota I am going to give it a try and see If I reproduce the issue.

Leave a Reply

Close Menu