HomeHome AutomationTuya SDK for beginners: Intro to Tuya Cloud API

Tuya SDK for beginners: Intro to Tuya Cloud API

Cloud API and REST for beginners

Two things have happened recently. I purchased a Bluetooth version of the temperature, humidity and luminosity sensor with an e-ink display instead of the intended ZigBee edition, and Tuya asked me to discover their Tuya Cloud API and share my experiences with you. I know, that for many of you cloud is the “evil resurrected”, but there are some interesting things to explore, and Tuya is much bigger than you think. To help out, Tuya also sent me FingerBots to play with so I have a selection of devices I can interact with.

Powered by Tuya

Tuya is a powerhouse of IoT in the East (from where I’m standing), among brands like Xiaomi, eWeLink and Aqara, Tuya brings together 1000s of manufacturers offering a complete IoT platform and integration with the most popular services like Alexa and Google Home. Inexpensive electronics and compatibility with our favourite smart assistants quickly raised Tuya’s profile among western consumers. To help you picture how big of a player the company is – here are some dry facts:

  • Tuya has welcomed more than 324,000 hardware and software developers on its open IoT development platform.
  • Tuya Cloud platform has built a thriving ecosystem that has smart-enabled more than 310,000 product SKUs in over 1,100 categories, covering over 220 countries and regions.
  • Tuya’s IoT Cloud infrastructure is currently capable of processing over 122 million AI voice interactions and over 84 billion cloud requests daily!.
  • The IoT cloud platform enables the development of an IoT app interface in 1 minute, an OEM app in 10 minutes and smart devices for mass production in 15 days.

Why does it matter?

I hate to break it to you guys, but DIY home enthusiasts made for a tiny % of the global sales, even if from our standpoint it feels completely different. Any company catering to that niche gets instant credit and love from the community (except when they fail to meet our expectations) but the fact is, we are not making them the bulk of money.

So how our DIY automation interest translates into the corporate cloud? This is where my accidental purchase comes in. As a DIY automation hobbyist you have 3 options:

  • select hardware that was made with DIY-ers in mind
  • wait and hope that consumer hardware gets hacked or modded
  • use 3rd party (cloud) integrations to add it to your ecosystem

Option 1 limits your hardware choices. Shiny new toys may never be available to us DIY mortals. Option 2 takes time and skilful people to make the hardware available to anyone who wishes to tinker.

Tuya Cloud API comes in handy. Instead of relying on 3rd party integrations, you can take charge and start experimenting with the hardware you like, rather than wait for workarounds. Yes, some of you will dismiss this instantly as it’s not run locally, therefore it does not adhere to the “DIY home automation code of moral standards”, but others just want to integrate the hardware that solves a problem for them. With 250k devices SKU, chances are that that hardware is already supported by Tuya.

FingerBot and Tuya Cloud API

Both, FingerBot, and the sensor from AliExpress use Bluetooth to talk to the internet via the Adaprox hub. It’s not my favourite interface to work with, but I have to admit that Bluetooth pairing is miles better than WiFi or ZigBee and since I’m using Tuya Cloud API, I don’t care how the devices talk to each other.

Thanks to Tuya Cloud API, there is no hacking involved. Open the Tuya app, follow the pairing instructions and you are set for use. No flashing, no hardware hacks, no workarounds. Tuya’s app is one of the more polished apps for automation out there so the experience has never been bad. As the app integrates nicely with Google Assistant or Alexa. As we are tapping in directly to Tuya Cloud API, these 3rd party services will update automatically.

FingerBot

FingerBot is a remote switch (just like SwitchBot) that toggles things on and off. It appears in the app as one and can be controlled via the Tuya app or 3rd party integrations. Each Fingerbot comes with a set of attachments to enable tugging pulling and switching.

FingerBots are small, powered by an internal rechargeable battery with USB-C (thank you!). They are easy to deploy, and fun to experiment with. Strong enough to toggle a light switch and small enough to be attached to a HiFi system or a coffee machine.

The Adaprox hub comes with an IR blaster, so if you have IR devices around (TVs etc) you can automate these too. The hub is small, powered by MicroUSB (why?) and connects to a 2.4GHz network only.

Temp, humidity and luminosity sensor with e-ink display

I really love the display of this thing. It runs on a single CR2032 cell and thanks to the e-ink display the data collected by 3 built-in sensors are accessible at glance. As this is a smart sensor, it shares the data with Tuya Cloud API for further automation.

Despite being an e-ink display, the refresh rate is pretty quick. I covered up the luminosity sensor to check how often it updates and it’s less than 5 sec on condition change. My imperial friends will be happy, as the sensor displays the data in both ℃ and ℉.

Tuya Cloud API and NodeRED

It’s easy to get lost in the development platform that Tuya provides. There is everything the IoT industry would ever need. Most of that stuff is way over my head, but it looks like you could build a re-skin of the Tuya app for Android in minutes supporting your own devices.

I don’t think I need to say how awesome that is. In fact, this goes even deeper. Thanks to virtual devices, you can interact with your prototypes as if they were added natively to your Tuya account. In plain words, you can bring all of your devices to the Tuya app even if they are not natively supported.

Simply add ie: virtual smart bulb, and link the commands through NodeRED to your IKEA lights. They will appear native to Tuya devices and you will have full control over them. Another use case would be making your own ESP32 or ESP8266 device and linking it through NodeRED to Tuya Cloud API.

Interesting opportunities ahead.

Account linking

Register your account with Tuya IoT Platform and create a new Cloud project. You can name it whatever you want. This is your project space. You will link your Tuya app account with this project and enable API.

Once you have located all the data in your account, it’s time to play. In Tuya IoT Platform enable API you want to use. Then switch over to “Link Devices” and select: “Link devices by App Account”. A QR code will appear and you can scan it using the menu from Tuya App on your phone.

Postman – making things easier

Tuya API provides you with extensive documentation. It’s a maze to navigate, but I will show you how to find the info you need and how to test API simply. Then we will take this knowledge to NodeRED so you can play yourself. This is where the Postman app comes in handy. It’s a REST API framework and Tuya API is configured to work with it.

If you rather just play with my examples, you can ignore the Postman part and jump to the NodeRED section, however, I would recommend you sit that one through as it will give you some basics on how to work with APIs in general.

You can register a free Postman account and download the app. Tuya API provides you with JSON (zipped) files that set up the postman for you. Tuya Cloud API Package should be imported in the Postman Collections menu, while Tuya Cloud API Environment Package is added when you switch over to Environments.

variableWhere I can find it
client_idDefault project tab
secretDefault project tab
access_tokengranted on authentication
refresh_tokengranted on authentication
uidon Tuya account linking page
device_idgranted on query/in linked devices tab/in Tuya app
urlTuya documentation

After successful linking, you should see all your Tuya devices from your mobile app in the IoT Platform.

Using Postman you can learn how the authentication process works and get yourself familiar with data and URL structure for Tuya Cloud API. Here is a basic rundown:

  1. Get access token (used to authorise REST requests)
  2. If your access token expires, use refresh token to generate a new one
  3. Use Get Device Listy by User ID to get the list of devices and DeviceIDs
  4. Use Get Device Info to get basic info about the device
  5. Use Get Device Data to get the information from sensors and similar
  6. Use Post to send commands to your devices

Postman will use the data specified in the Environments list. Make sure to select the active Environment as this will define the current set of variables. Each request will produce you with a sample response in JSON format, so if this is your first time with JSON I have a 5 min guide for you.

Once everything works, you can take a look at the actual request sent in different languages. It’s very handy if you are working with a specific language. For NodeRED use JavaScript jQuery. These examples will give you an overview of how your REST call should look like.

Now you are ready to write it yourself in NodeRED.

NodeRED Examples

As this is an intro only, I will focus on a couple of REST calls. I will show you how to authenticate, refresh the token, send commands, obtain the status, and query the data points for your devices. This should give you enough to play about.

Each REST call has an individual flow that does pretty much the same thing. It takes the authentication data and encrypts it for safety (SHA256), then submits the request to Tuya Cloud API. To make the process easy to follow I split each flow into sections and commented out the code so you can understand the sections better and use them in your automation.

Authentication

To authenticate, you will need to set your credentials in the 1st flow as described in the comments of the code. This will generate and store the access token for you as a NodeRED variable. You should also run refresh token flow every few hours to make sure you are authenticated (access tokens have an expiry date).

You will need to add node-red-contrib-crypto-js-dynamic from palette manager, to encrypt the data sent to Tuya Cloud. Upon successful authentication, security tokens are stored as flow variables for reuse. You will need these to authenticate further requests.

Device Lists, statuses and data

When authenticated, this flow will go through the list of linked devices and generate an entry for each device exposing basic information and deviceID. These will be saved as NodeRED flow variables and you can use these to query devices for further details or sending commands.

The device list will discover all linked to your Tuya account devices, and save them as individual entities based on their deviceID. You will need this value to obtain the status and data information for each device.

The status will provide you will a lot of metadata for each device, including the current state and data, while data points will get you the latest usable information about the device, leaving the metadata out of the query.

Commands

Apart from the access token, you will need the device ID and correct commands set to control devices. In my case, I’m using FingerBot and the command message looks like this:

{
    "commands":[
        {
            "code":"switch",
            "value":true
        }
    ]
}

Command sets can be looked up in the reference documentation for each device type It’s a copy and paste job. I included them in a separate node so you can edit it on the fly and insert the commands programmatically.

Even with the Tuya app open, the changes sent to Tuya Cloud are almost instant. It shows that working with Cloud has changed over time and things are no longer subject to visible latency.

Final thoughts

Getting started is less intimidating than I thought, although developing apps in Tuya Cloud API is a massive undertaking. This beginner guide to Tuya Cloud API should allow you to take basic control and query devices that previously weren’t controllable this way. I hope this will inspire you to try more things in the future and makes you less intimidated by API and REST requests. It’s been a journey for me and I’m always happy to share things I learned. Big shout out to Tuya for sponsoring this journey and James Wilson for updating the flow to reflect changes in the authentication process. If you have any comments please leave them in this Reddit thread.

🆓📈 – See the transparency note for details.

Project Download

Download project files here. Bear in mind that Patreon supporters have early access to project files and videos.

PayPal

Nothing says "Thank you" better than keeping my coffee jar topped up!

Patreon

Support me on Patreon and get an early access to tutorial files and videos.

image/svg+xml

Bitcoin (BTC)

Use this QR to keep me caffeinated with BTC: 1FwFqqh71mUTENcRe9q4s9AWFgoc8BA9ZU

Smart Ideas with

Automate your space in with these ecosystems and integrate it with other automation services

client-image
client-image
client-image
client-image
client-image
client-image
client-image
client-image
client-image

Learn NodeRED

NodeRED for beginners: 1. Why do you need a NodeRED server?

0
To server or not to server? That's a very silly question!

Best Automation Projects

NEST your old thermostat under $5

0
Nest-ing up your older thermostat under $5

Sonoff Zigbee Bridge – review

0
Sonoff line up will soon include Sonoff Zigbee Bridge and more Zigbee sensors - here is the first look

DIY Smart Washing Machine – for about 15 bucks!

0
Learn how to add washing machine notifications to your Google Home on the cheap

Nora – Google Assistant in NodeRED

0
Integrate Google Assistant with NodeRED thanks to Nora - NodeRED home automation

Things they don’t tell you about IKEA Trådfri

0
There are things you should know about IKEA Tradfri before you make your purchase

Smart Home

Multi-lights for your ceiling from Aqara

0
This is the biggest light I held in my hands so far. It's ZigBee and it comes from Aqara - meet Aqara Ceiling Light T1M

Almost the fastest PIR sensor you can buy

0
ITEAD introduced a new ZigBee sensor - Sonoff PIR (SNZB-03P) which is also the fastest PIR sensor in their line up. Is it good? Read more!

Smart Panel automation by Tuya

0
I'm checking out two smart panels by Tuya. Both run Linux systems, fit inside the wall switch cavity and offer a range of automation options

Adding Matter to Sonoff BasicR4

0
Sonoff goes back to basics with Sonoff BasciR4 - a new and improved basic smart relay - and I'm about to add Matter to it (and Tasmota)

Sonoff Presence Sensor (SNZB-06P) is not what you think

0
This mm wave radar sensor combines cool tech and ZigBee 3.0, but it's not what you think it is. Closer look at Sonoff Presence Sensor