With Tuya Cloud Development Platform, you can get access to calling OpenAPI of Tuya IoT Platform. Then, writing just a few lines of code will allow you to control smart devices Powered by Tuya. This demo describes how to call APIs in Python for smart device control through Tuya Cloud Development Platform.
Any devices Powered by Tuya are applicable. Find more in our TuyaGo.more
Go through the following steps to create and configure a cloud project.
You have registered an account on the Tuya IoT Platform.
A cloud project is a collection of resources on the Tuya IoT Platform. Resources distributed to different projects are isolated from each other. To get started, you need to create a cloud project first.
Log in to the Tuya IoT Platform.
In the left-side navigation bar, choose Cloud > Development.
On the My Cloud Projects page, click Create Cloud Project.
On the Create Cloud Project page, set the required parameters and click Create.
Project Name: the custom name of the project.
Description: the custom description of the project.
Development Method: In this example, select Custom from the drop-down list. For more information about the development method, see Development Method.
Industry: Select the industry type of your project, facilitating follow-up statistical analytics.
Availability Zone: Enter the server address of the region where you are located.
On the Authorize API Products page, besides the default selections, you need to subscribe to the API products such as Device Status Notification and Industry Project Client Service.
Create the original asset and original account. Then, the account will be granted access to the asset.
Note: Note down the specified account and password. You will use them when you add a device using the IoT Device Management app or call the API operations to control the devices. You can also build your asset structure based on actual business scenarios. For more information, see Manage asset structure.
After you create and configure a project, you can link devices with your project.
Add a smart device to your asset to allow device control through API calls.
Note: If you do not have a ‘Powered by Tuya’ device, we provide you with a virtual device service. For more information, see Add Virtual Device.
On the Devices tab, place the pointer over Add Device, and select Add Device with IoT Device Management App.
Scan the project QR code with the IoT Device Management app to authorize the project.
Log in to the IoT Device Management app using the initial account configured when the project was created.
The Assets and Devices page appears by default. Tap the asset to be managed to go to the Assets tab.
Tap the Add icon in the top-right corner of the page.
In the bottom menu that appears, select Pair Smart Device.
Note: This tutorial takes Pair Device as an example. To activate the edge gateway, see Activate Edge Gateway.
Add devices. Combined with the subsequent code, in this example, you need to add strip lights or a virtual device of the strip lights. A device can be added in two methods, Add Manually and Auto Scan. They are similar to those used to add devices on all-in-one apps. For more information, see Add a device.
After adding a device, you can simulate your real business scenarios by using the device debugging feature, send commands to control the devices, and check the device availability to ensure stable operation. For more information, see Step 3: Debug Device.
Alternatively, you can choose the SDKs for your preferred programming languages to develop IoT services. For more information, see Step 4: Develop IoT Services.
You can simulate your real business scenarios by using the device debugging feature, send instructions to control the devices, and check the device availability to ensure stable operation.
Note: Currently, you can only debug the devices that belong to the assets system and devices linked with the Tuya app account. This topic describes how to debug devices that belong to the assets system.
You have added a device to the cloud project.
View basic information.
On the Basic Information page, you can view the device ID, product category, and associated project and asset.
Send instructions to the device.
On the right side of the Device Debugging page, check how to enter the Standard Instruction Set and Stanard Status Set.
Note: Click Update Device Status to get the latest status of the device.
Report device data to the cloud.
You can simulate device data reporting and perform related tests such as message subscription and reception.
Note: Currently, only virtual devices can send the data reporting instructions. If there is no change in the device status, the data cannot be reported.
Click Data Reporting Simulation on the top of the page, and wait for the Communication Log to show MQTT connect success
.
Modify the parameters or switches of a data point.
Click Report at the bottom, and the communication log shows that the data is reported successfully.
The system returns logs of all the data reporting and sending operations during device debugging. On the Device Logs page, you can query logs by DP ID, device event, and time.
After the device is added and debugged, you can quickly develop IoT services on top of the IoT SDKs. For more information, see Step 4: Develop IoT Services.
This topic describes how to develop a program to control ‘Powered by Tuya’ devices based on the open capabilities and SDK of the Tuya Cloud Development Platform.
This step is based on the Tuya-connector-Python SDK. Tuya-connector
helps you efficiently create cloud development projects regarding the OpenAPI or message subscription capabilities. You can put all the focus on business logic without taking care of server-side programming nor relational databases.
Get the SDK address at Tuya-connector-Python.
Go to Projects > Get from Version Control > URL, enter the SDK address, and then click Clone.
(Independent project development) Import Python dependency package.
Note: The GitHub hosting platform contains the SDK source code. The API request used in this topic is the source code in the SDK project. If you develop an independent project, the PIP tool can be used to import the Python dependency package.
Import code: pip3 install tuya-connector-python
Configure environment variables in the py
file.
ACCESS_ID
and ACCESS_KEY
: Enter the values of Access ID and Access Key in the Authorization Key section on the Cloud Development Platform. For more information, see Query project information.
API_ENDPOINT
: the data center address of API requests. See the tuya-connector-python/tuya_connector/tuya_enums.py
file.
MQ_ENDPOINT
: the request address of message subscription. See the tuya-connector-python/tuya_connector/tuya_enums.py
file.
Location | API_ENDPOINT | MQ_ENDPOINT |
---|---|---|
China | https://openapi.tuyacn.com | wss://mqe.tuyacn.com:8285/ |
America | https://openapi.tuyaus.com | wss://mqe.tuyaus.com:8285/ |
Europe | https://openapi.tuyaeu.com | wss://mqe.tuyaeu.com:8285/ |
India | https://openapi.tuyain.com | wss://mqe.tuyain.com:8285/ |
Example:
ACCESS_ID = "xtu7m*****48ufod"
ACCESS_KEY = "479bcba6d*******d9c4e080f7"
API_ENDPOINT = "https://openapi.tuyacn.com"
MQ_ENDPOINT = "wss://mqe.tuyacn.com:8285/"
After the project parameters are edited, you can start your coding journey. Device control is a must-have feature.
The following code block is the sample code for cloud project authorization key authentication and query device details, get device instruction set, send instruction set, and query device status for your reference.
Sample code of querying devices and issuing instructions: device_control.py
import logging
from tuya_connector import TuyaOpenAPI, TUYA_LOGGER
ACCESS_ID = "xtu7m*****48ufod"
ACCESS_KEY = "479bcba6d*******d9c4e080f7"
API_ENDPOINT = "https://openapi.tuyacn.com"
# Enable debug log
TUYA_LOGGER.setLevel(logging.DEBUG)
# Init OpenAPI and connect
openapi = TuyaOpenAPI(API_ENDPOINT, ACCESS_ID, ACCESS_KEY)
openapi.connect()
# Set up device_id
DEVICE_ID ="vdevo********74966"
# Call APIs from Tuya
# Get the device information
response = openapi.get("/v1.0/iot-03/devices/{}".format(DEVICE_ID))
# Get the instruction set of the device
response = openapi.get("/v1.0/iot-03/devices/{}/functions".format(DEVICE_ID))
# Send commands
commands = {'commands': [{'code': 'switch_led', 'value': False}]}
openapi.post('/v1.0/iot-03/devices/{}/commands'.format(DEVICE_ID), commands)
# Get the status of a single device
response = openapi.get("/v1.0/iot-03/devices/{}/status".format(DEVICE_ID))
Sample response
/Users/even/Documents/SDK/Python/ttuya-connector-python1/venv/bin/python /Users/even/Documents/SDK/Python/ttuya-connector-python/example/device_control.py
[2021-08-24 16:27:21,832] [tuya-openapi] Request: method = GET,url = https://openapi.tuyacn.com/v1.0/token,params = {'grant_type': 1},body = None,t = 1629793641832
[2021-08-24 16:27:22,007] [tuya-openapi] Response: {
"result": {
"access_token": "***",
"expire_time": 6147,
"refresh_token": "***",
"uid": "***"
},
"success": true,
"t": 1629793642090
}
[2021-08-24 16:27:22,007] [tuya-openapi] Request: method = GET,url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo********74966,params = None,body = None,t = 1629793642007
[2021-08-24 16:27:22,183] [tuya-openapi] Response: {
"result": {
"active_time": 1629792940,
"asset_id": "14178********2832",
"category": "dj",
"category_name": "Light Source",
"create_time": 1629792940,
"gateway_id": "",
"icon": "smart/icon/bay161786******240908156830dd.png",
"id": "vdevo********74966",
"ip": "***",
"lat": "***",
"local_key": "***",
"lon": "***",
"model": "",
"name": "Dimmable White Light (C)_SIG-vdevo",
"online": true,
"product_id": "ppg6apfp",
"product_name": "Dimmable White Light (C)_OEM",
"sub": false,
"time_zone": "+08:00",
"update_time": 1629793223,
"uuid": "vdevo********74966"
},
"success": true,
"t": 1629793642263
}
[2021-08-24 16:27:22,183] [tuya-openapi] Request: method = GET,url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo********74966/functions,params = None,body = None,t = 1629793642183
[2021-08-24 16:27:22,256] [tuya-openapi] Response: {
"result": {
"category": "dj",
"functions": [
{
"code": "switch_led",
"desc": "switch led",
"name": "switch led",
"type": "Boolean",
"values": "{}"
},
{
"code": "work_mode",
"desc": "work mode",
"name": "work mode",
"type": "Enum",
"values": "{\"range\":[\"white\",\"colour\",\"scene\",\"music\"]}"
},
{
"code": "bright_value_v2",
"desc": "bright value v2",
"name": "bright value v2",
"type": "Integer",
"values": "{\"min\":10,\"max\":1000,\"scale\":0,\"step\":1}"
},
{
"code": "scene_data_v2",
"desc": "scene data v2",
"name": "scene data v2",
"type": "Json",
"values": "{\"scene_num\":{\"min\":1,\"scale\":0,\"max\":8,\"step\":1},\"scene_units\": {\"unit_change_mode\":{\"range\":[\"static\",\"jump\",\"gradient\"]},\"unit_switch_duration\":{\"min\":0,\"scale\":0,\"max\":100,\"step\":1},\"unit_gradient_duration\":{\"min\":0,\"scale\":0,\"max\":100,\"step\":1},\"bright\":{\"min\":0,\"scale\":0,\"max\":1000,\"step\":1},\"temperature\":{\"min\":0,\"scale\":0,\"max\":1000,\"step\":1},\"h\":{\"min\":0,\"scale\":0,\"unit\":\"\",\"max\":360,\"step\":1},\"s\":{\"min\":0,\"scale\":0,\"unit\":\"\",\"max\":1000,\"step\":1},\"v\":{\"min\":0,\"scale\":0,\"unit\":\"\",\"max\":1000,\"step\":1}}}"
},
{
"code": "countdown_1",
"desc": "countdown 1",
"name": "countdown 1",
"type": "Integer",
"values": "{\"unit\":\"s\",\"min\":0,\"max\":86400,\"scale\":0,\"step\":1}"
}
]
},
"success": true,
"t": 1629793642338
}
[2021-08-24 16:27:22,256] [tuya-openapi] Request: method = POST,url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo********74966/commands,params = None,body = {'commands': [{'code': 'switch_led', 'value': False}]},t = 1629793642256
[2021-08-24 16:27:22,386] [tuya-openapi] Response: {
"result": true,
"success": true,
"t": 1629793642470
}
[2021-08-24 16:27:22,386] [tuya-openapi] Request: method = GET,url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo********74966/status,params = None,body = None,t = 1629793642386
[2021-08-24 16:27:22,461] [tuya-openapi] Response: {
"result": [
{
"code": "switch_led",
"value": false
},
{
"code": "work_mode",
"value": "white"
},
{
"code": "bright_value_v2",
"value": 10
},
{
"code": "scene_data_v2",
"value": ""
},
{
"code": "countdown_1",
"value": 0
}
],
"success": true,
"t": 1629793642546
}
Process finished with exit code 0
# Init OpenAPI and connect
openapi = TuyaOpenAPI(API_ENDPOINT, ACCESS_ID, ACCESS_KEY)
openapi.connect()
response = openapi.get("/v1.0/iot-03/devices/{}".format(DEVICE_ID))
response = openapi.get("/v1.0/iot-03/devices/{}/functions".format(DEVICE_ID))
commands = {'commands': [{'code': 'switch_led', 'value': true}]}
openapi.post('/v1.0/iot-03/devices/{}/commands'.format(DEVICE_ID), commands)
response = openapi.get("/v1.0/iot-03/devices/{}/status".format(DEVICE_ID))
The following sample code shows how to implement the forwarding feature of the message service. For example, devices get online or offline, and device status is reported.
Note: The Message Service is required to enable this feature. For more information, see Message Service.
Sample code of message subscription: Mq.py
import logging
from tuya_connector import TUYA_LOGGER, TuyaOpenPulsar, TuyaCloudPulsarTopic
ACCESS_ID = "xtu7m*****48ufod"
ACCESS_KEY = "479bcba6d*******d9c4e080f7"
MQ_ENDPOINT = "wss://mqe.tuyacn.com:8285/"
# Enable debug log
TUYA_LOGGER.setLevel(logging.DEBUG)
# Init Message Queue
open_pulsar = TuyaOpenPulsar(
ACCESS_ID, ACCESS_KEY, MQ_ENDPOINT, TuyaCloudPulsarTopic.PROD
)
# Add Message Queue listener
open_pulsar.add_message_listener(lambda msg: print(f"---\nexample receive: {msg}"))
# Start Message Queue
open_pulsar.start()
input()
# Stop Message Queue
open_pulsar.stop()
Sample response
/Users/even/Documents/SDK/Python/ttuya-connector-python1/venv/bin/python /Users/even/Documents/SDK/Python/ttuya-connector-python/example/Mq.py
[2021-08-24 16:44:56,274] [tuya-openpulsar] start
[2021-08-24 16:44:56,274] [tuya-openpulsar] ws-client connect status is not ok.
trying to reconnect for the 1 time
[2021-08-24 16:44:56,274] [tuya-openpulsar] ---
ws-client connecting...
[2021-08-24 16:45:16,198] [tuya-openpulsar] received message origin payload: {"data":"hBfzoXBHP4H5S44R41JYQ6SoW2dYdwIBh/OVljw/BWnHceQwrrF0vuCyPhPmcgsLzQtf9wFhkSQ6IBE2P3yYPvavGWoPpl0r3fkcooWquX8JfG8gnY2R7wUL3Xn4MP48poM3HepgaRZOkpsSKmAqgdxobOPC7kNpk92hmXjB0PEOZ2Du4MbP4NSN49QcJ4MPl9NsbN/2CZpBNFtIusOL74T+aj0XxXAkcYXc/URNLpxRJ3xeyrLXEwM+0nBc+60qvhnd5XA0Y7aFpHh02iIbzZfTbGzf9gmaQTRbSLrDi+/NOqojg8fRo3AW+Cq6m/AtpGIRH8fwQo+FZ9RzGrk+V7bzGsXu3MK7mEqvJpca8eT7C2ZAat2eM9LwAcsDgOoQaWYWiLcqj04ZYzJqLETUGyRFs3pL4aNsWiTEGuQkMHNV0yTN7Nw/PmMonsmdM3aYSaAwQM37T2HC7gqa2exumamfEL7hh+lWoqymRU/hApq0SeBffyniddW2Daw8AUet","protocol":4,"pv":"2.0","sign":"0e523e66fea32a3873b122152fc04c84","t":1629794716261}
[2021-08-24 16:45:16,198] [tuya-openpulsar] received message descripted: {"dataId":"9aa9d3c4-04b7-11ec-8396-02425b0322e7","devId":"vdevo********74966","productKey":"ppg6apfp","status":[{"1":"true","code":"switch_led","t":1629794716199,"value":true},{"2":"white","code":"work_mode","t":1629794716199,"value":"white"},{"3":"10","code":"bright_value_v2","t":1629794716199,"value":10},{"code":"countdown_1","t":1629794716199,"7":"0","value":0}]}
---
example receive: {"dataId":"9aa9d3c4-04b7-11ec-8396-02425b0322e7","devId":"vdevo********74966","productKey":"ppg6apfp","status":[{"1":"true","code":"switch_led","t":1629794716199,"value":true},{"2":"white","code":"work_mode","t":1629794716199,"value":"white"},{"3":"10","code":"bright_value_v2","t":1629794716199,"value":10},{"code":"countdown_1","t":1629794716199,"7":"0","value":0}]}
This demo describes how to call basic APIs in Python for smart device control through Tuya Cloud Development Platform. Thanks to the strictly unified Powered by Tuya ecosystem, you can apply this control method to all devices Powered by Tuya. Breaking device heterogeneity lets you quickly build IoT applications and services.
Is this page helpful?
YesSuggestions