device access

Device access Tuya Smart Cloud

Connection Methods

Device Access Frame

As shown above, graffiti cloud support equipment to HTTPS, MQTT access graffiti clouds. HTTPS access to the scene are: access to device configuration information, access to device upgrade information. MQTT access and other scenes are: subscribe to device control instructions, publish the device status.


  • HTTP / HTTPS Tuya Smart Cloud HTTP (ATOP gateway) API is based on HTTP or HTTPS protocol to call, the developer can be Tuya Smart Cloud ATOP protocol to encapsulate the HTTP request to call.

  • MQTT MQTT is an Internet of Things transport protocol that is designed for lightweight publish / subscribe messaging. MQTT is developed specifically for the Internet of Things lightweight transport protocol. Graffiti cloud platform support MQTT way to call, and provide the corresponding AppKey and AppSecret for users to use.


  • MQTT subscriptions are recommended for real-time control instructions or hardware-reported data class data.

Call the entry

Tuya Smart Cloud According to Chinese enterprises in the export of submarine cable distribution area and the global cities of the measured results, the deployment covers Asia, Europe and the United States three available areas.

Call the API service domain name as follows:

Available area protocol domain name Data security level Service Area
AY http/https/mqtt * HTTPS+AES Asia
AZ http/https/mqtt * HTTPS+AES America
EU http/https/mqtt * HTTPS+AES Europe

Note: Note: Tuya Smart cloud provides http, https, mqtt and other communication protocols, according to business needs can be flexibly choose to use.

  • https: a1.tuya (cn/eu/us).com/api.json (APP call, such as:
  • http: (cn/eu/us).com/gw.json (hardware calls, such as:
  • mqtt: mq.mb.tuya (cn/eu/us).com (APP calls, such as: tcp://
  • mqtt: (cn/eu/us) .com (hardware calls, such as: tcp://

Protocol Overview

  • HTTP / HTTPS     - Call the process     The detailed steps for invoking a cloud service over HTTP / HTTPS are as follows: Fill parameters> Generate signature> Assemble HTTP request> Initiate HTTP request> Get HTTP response> Explain the json result.

The general procedure is as follows:


  • Common parameters     Calling any API must pass the public parameters are:
Parameter name Parameter type Must be Whether sign Parameter description
a String Yes Yes API Name
v String Yes Yes API Interface Version
t String Yes Yes timestamp, formatted as number, in seconds to non-milliseconds, time zone is the standard time zone, for example: 1458010495. API server allows the client to request a maximum time error of 540 minutes.
sign String Yes No API input parameters signature results, the signature algorithm is described below
devId String No Yes Device Id, which returns a new devId for each invocation of the registered interface, which must be set by the API call after device activation
uuid String No Yes ** Device unique identifier, which must be set by the API call before device activation **

Note: For non-mandatory parameters and participation in the signature, the value is empty in the case of participation in the signature, only in the case of value to participate in the signature.

  • MQTT
  • Call the process     According to MQTT agreement, through the MQTT and cloud interactive detailed steps: the use of MQTT client connection -> user name password connection authentication -> Topic subscription -> heartbeat maintenance.

The general procedure is as follows:     MQTT     MQTT

Access the tutorial

HTTP / HTTPS Connection Method

Business Parameters

In addition to API call contains public parameters, each API itself may have specific business-related parameters also need to be imported (each API’s business-level parameters, please refer to the API list). For example, if the API has two service parameters, devId and productId, the URL format is data = {“devId”: “123”, “productId”: “123”}.


  • The service parameters need to be encrypted before transmission, but are not signed.
  • Encryption key: Before activating the related interface, the key is the first 16 characters of the accessKey of the device. The related interface key after activation is used as secKey

AES encryption algorithm used in business parameters, AES encryption is also required after the hexadecimal conversion, as follows::

public String encrypt(String key,String data) throws Exception {
SecretKeySpec key = new SecretKeySpec(key, "AES");
Cipher c = Cipher.getInstance("AES");
c.init(1, key);
byte[] encVal = c.doFinal(data.getBytes());
String encryptedValue = byte2hex(encVal);
return encryptedValue;

public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";

for(int n = 0; n < b.length; ++n) {
stmp = Integer.toHexString(b[n] & 255);
if(stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;

return hs.toUpperCase();

Other parameters

API call In addition to public parameters, business parameters, but also provides the URL parameter other (other parameters). The other parameters are also needed because the service parameters need to be encrypted at the time of transmission. Therefore, only the sensitive data is put into the service parameters. For non-sensitive service parameters can be put into other parameters to reduce the encryption of data, improve the efficiency of decryption and encryption, and for some interface decryption business parameters need to use the associated information also need to put other parameters. All other parameters into the URL parameters other passed to the server, for example, the API has other parameters token, the format is other = {“token”: “jkiuythu”}.


  • Other parameters need to participate in the signature.

Request Signature

In order to prevent the API call process by hackers malicious tampering, call any API need to carry the signature, ATOP server based on the request parameters, signature verification, signature invalid request will be rejected.

Note: For parameters that need to participate in the signature (refer to each specific API), do not participate in the signature if the value is empty, and participate in signing only when there is a value.

Each step of the signature algorithm is described in detail below, assuming that the API request parameters are as follows:

a =
v = 1.0
t = 1431078303
devId = jdkd8dkf89dkid76dyt5
data = 8bf04fa8023db7c846a8826bdf2b8309 - Note: data is the encrypted data
other = {"token": "khuyghyt"}

Since the business parameter data does not participate in the signature, the following results are sorted by dictionary name of the parameter name:

a =
devId = jdkd8dkf89dkid76dyt5
other = {"token": "khuyghyt"}
t = 1431078303
v = 1.0

Arrange the sorted parameter names and parameter values ​​together, the parameters between the || connection, the results are:||devId=jdkd8dkf89dkid76dyt5||other={"token":"khuyghyt"}||t=1431078303||v=1.0

After concatenating the keys of the device and the cloud (the secKey returned after each activation) after the resulting signature input string, assuming that the key is qwertu87tyredser, the last signature string is:||devId=jdkd8dkf89dkid76dyt5||other={"token":"khuyghyt"}||t=1431078303||v=1.0|| qwertu87tyredser

Finally, the assembled signature string using utf-8 encoding, the byte stream of encoded MD5 summary.

Signature Special Note:

  • The key used by the API call before device activation is the first 16 characters of the authorization key (accessKey) granted to each device during production test. The key used by the API call after device activation is the secKey returned after activation. .

  • The signature D5 digest algorithm MUST use the following MD5 digest algorithm, which is different from the standard MD5 algorithm.

public static String getMD5 (byte [] source) throws Exception {
    String s = null;
    Char [] hexDigits = new char [] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 'A', 'b', 'c', 'd', 'e', ​​'f'};

    MessageDigest e = MessageDigest.getInstance ("MD5");
    E.update (source);
    Byte [] tmp = e.digest ();
    Char [] str = new char [32];
    Int k = 0;
    For (int i = 0; i & lt; 16; ++ i) {
        Byte byte0 = tmp [i];
        Str [k ++] = hexDigits [byte0 >>> 4 & 15];
        Str [k ++] = hexDigits [byte0 & 15];
    S = new String (str);
    Return s;

Call Examples

Take the call to as an example (assuming the cloud communication key of the device is: qwertu87tyredser), the steps are as follows:

  1. Set the parameter value

Common Parameters:

a =
v = 1.0
t = 1431078303
devId = klsdjflkasdjflkjdsalfkjd

Service parameters:

Encrypted data
data = 89C408184EBA34952CA4F8829042E906FA42CC0AA00B334020C26666F2D2984327C02F1756863EF72C21B0DEB011B6E328390AC5416DF81C4C05FF9CD99086DE

Other parameters:

  1. Sort the parameters in dictionary order
  1. Mosaic parameter names and parameter values ​​and communication keys||devId=klsdjflkasdjflkjdsalfkjd||other={"token":"khuyghyt"}||t=1431078303||v=1.0 ||qwertu87tyredser
  1. Generate signatures
Md5(the signature string generated by the last UTF-8 encoded byte array)=de68028527c6f0f2510b2ef8f9d5e7fb
  1. Assemble the HTTP request

All parameter names and parameter values ​​are URL encoded with utf-8 (optional parameter order, but must include signature parameters), and then through the GET or POST request, assuming the request of China, the URL is as follows:

a = & devId=klsdjflkasdjflkjdsalfkjd&other={"token":"khuyghyt"}&t=1431078303&v=1.0&data=89C408184EBA34952CA4F8829042E906FA42CC0AA00B334020C26666F2D2984327C02F1756863EF72C21B0DEB011B6E328390AC5416DF81C4C05FF9CD99086DE&sign=8d106035a74c4392113a128c8fc44692

Device Lifecycle



  • All request and response data encoding are utf-8 format, the URL of all parameter names and parameter values ​​do URL encoding
  • Request a different domain, please use the appropriate domain name

Note Why provide multiple different domain names:

  • Different domain names can be resolved by different DNS service providers to provide the best analytical stability of the region and accelerate the service.
  • Can be more effective in avoiding operator hijacking.
  • Reduce the number of parsing, you can more stable optimization of some remote DNS service provider performance problems.

MQTT Connection Method

Device Cloud MQTT BROKER

  • Through the MQTT initiative to push a variety of instructions to the networking module, the module can also MQTT initiative to report data to the cloud and APP.
  • Connection URL: The WIFI device obtains the URL of the corresponding free area by using the API (tuya.device.config.get)

MQTT CLIENT connection parameter settings

Parameter Name Set Value Description
ClientId devId returned after device registration
UserName devId user name ,returned after device registration
Password MD5 (seckey returned after device active), taking the middle 16 bits password
ProtocolVersion 4 Protocol version number, 4 for MQTT3.1.1
CleanSession 1 Client disconnect does not hold the message to push
KeepAlive Recommended for greater than 30 seconds Heartbeat detection interval
Retain 0 The MQTT server does not hold the message
Qos 1 Message QOS Level set to 1, at least once
Will Flag 1 Set Up a Wishful Message
Will Qos 1 QOS Level is set to 1, at least once
Will Retain 0 The MQTT server does not keep the last message
Wilty tuya/smart/will TOPIC
Will Message {“clientId”: “{devId returned for device registration}”, “deviceType”:“GATEWAY”} Will Message

Connection return value

Return Value Hexadecimal Description
0 0x00 Connection Accepted
1 0x01 Connection Refused: unacceptable protocol version
2 0x02 Connection Refused: identifier rejected
3 0x03 Connection Refused: server unavailable
4 0x04 Connection Refused: bad user name or password
5 0x05 Connection Refused: not authorized


The topic-by-vid distinction for each device:
Command reception: smart/device/in/devId, which receives the control commands from APP and the cloud by subscribing to this topic
Report data: smart/device/out/devId, through the topic to send the reported data

MQTT message format

MQTT The data format for data interaction is as follows

Protocol version number (3 bits) md5 signature (16 bits) aes Encrypted data (base64 encoding)
2.1 6358012863580128 1rACuvQlqIHDjpzZF5hqvPLdWu0bd7SKADwzK893

MQTT Message body The final payload of the payload is 2.163580128635801281rACuvQlqIHDjpzZF5hqvPLdWu0bd7SKADwzK893

MQTT Message Encryption and Signature Algorithm

Assume that the localKey is 8bb486f35dbc57dd

1, data encryption: aes (binary conversion to string “base64 encoding”)

2, anti-tamper signature: md5 (the generated 32-bit string, into 16-bit string, the algorithm: take 32 of the middle 16, that is 8-24)     Each parameter is formatted as “key = val”, assembled (using the key ascending order), the assembled string format such as: k1=v1||k2=v2, and then add the key such as: k1=v1||K2=v2 … kn=vn||key, the entire string of MD5.    Parameters include: data, pv and key, where data is aes encrypted data, pv is the current version of the communication protocol version of the module, the device is registered to return to the key localkey

Md5 str: data = YzE/13Vp6p84PA1dV/1rACuvQlqIDsHDjpzZF5hqvPLdWu0bd7SKADwzK893HfHKMl4rdHb5Qc1qPOqfSFVcD1eqGhvwDO7pqCLmArcUpYDSEiSjFCfRKh1hnsbZrXEj||pv=2.1||8bb486f35dbc57dd
Sign: md5(str)The result is: 326053f1f965e98d6db781a6010def3b
Take 32 in the middle of 16, that is 8-24, the result is f965e98d6db781a6

MQTT Interactive Data Format

Protocol number (different protocol numbers represent different functions)

Protocol Number Description
4 Device Data Report
5 device instructions
11 Cloud Start Device Removal Operation *** Note: If the communication data has the type attribute and the value is reset_factory, it indicates that the device has been reset to factory settings. This time, you need to re-register the device to restart the device. Otherwise, you only need to restart the device and do not need to register the device again. ***
15 The user confirms the device firmware upgrade, informs the device that the firmware is ready to be upgraded
16 Firmware Upgrade Progress
17 The device reports status information
18 The device requests data from the cloud and distinguishes between different data types by reqType
19 cloud to the device to send the requested data, different data types by reqType distinguish
21 The device reconnects the new available area

Data Interactive Format

  "protocol": 4,
  "t": 1459168450,
  "data": {
    "devId": "002dr00118fe34d9a124",
    "subId": "2k9u800118fe34d8y6t5", - Only the gateway sub-device has this attribute
    "dps": {
      "1": true,
      "2": 30,
      "3": ""
  "protocol": 5,
  "t": 1459168450,
  "data": {
    "devId": "002dr00118fe34d9a124",
    "subId": "2k9u800118fe34d8y6t5", - Only the gateway sub-device has this attribute
    "dps": {
      "1": true,
      "2": 30,
      "3": ""
  "protocol": 11,
  "type": "reset_factory", - Note: type has the value and the value "reset_factory" means to restore the factory settings, otherwise remove the device
  "t": 1459168450,
  "data": {
    "devId": "002dr00118fe34d9a124",
    "subId": "2k9u800118fe34d8y6t5" - Only the gateway sub-device has this attribute
  "protocol": 15
  "t": 1459168450,
  "data": {
    "devId": "002dr00118fe34d9a124"
  "protocol": 17
  "t": 1459168450,
  "data": {
    "devId": "002dr00118fe34d9a124",
    "subId": "2k9u800118fe34d8y6t5", - Only the gateway sub-device has this attribute
    "softVer": "device firmware version number (may not fill)",
    "protocolVer": "device firmware communication protocol version number (may not fill)",
    "baselineVer": "device firmware baseline version number (may not fill)",
    "mcuVer": "Device MCU version number (can not fill)"
  "protocol": 18
  "t": 1459168450,
  "data": {
    "reqType": "cloud_time" - Currently only cloud_time is supported, cloud time is requested from the cloud, and the device can be used to calibrate local time
  "protocol": 19
  "t": 1459168450,
  "data": {
    "reqType": "cloud_time", - Returns the reqType of the request for easy comparison
    "time": 1459168450,
    "validTime": 1800
  "protocol": 21
  "t": 1459168450,
  "data": {
    "devId": "002dr00118fe34d9a124",
    "url": {"apiUrl": "api call url address", "mqttUrl": "mqtt connection url address"}