English
English
简体中文
Contact Us
Register
Log In

Integration with Environmental Monitoring Devices

Last Updated on : 2022-07-06 03:14:36download

This topic describes how to integrate smart environmental monitoring devices with the Tuya IoT Development Platform by using Tuya IoT Edge Gateway.

Architecture

Tuya provides the following solution to help you connect smart environmental monitoring devices to the Tuya IoT Development Platform by using Tuya IoT Edge Gateway. The architecture is shown as follows:

Integration with Environmental Monitoring Devices

Integration protocol

During communications over the MQTT protocol, the environmental monitoring gateway works as a client, and Tuya IoT Edge Gateway works as a broker.

Device features

The following table lists the specified properties of a smart environmental monitoring device for your reference.

DP ID DP name Identifier Data transfer type Data type DP property
1 Air monitoring data env_detect_data Report only (read-only) string /
2 Air speed windspeed_gust Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
3 Wind wind_power Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
4 Wind direction wind_direct Send and report (read-write) enum The enumeration values.
  • north: north.
  • north_north_east: north northeast.
  • north_east: northeast.
  • east_north_east: east northeast.
  • east: east.
  • east_south_east: east southeast.
  • south_east: southeast.
  • south_south_east: south southeast.
  • south: south.
  • south_south_west: south southwest.
  • south_west: southwest.
  • west_south_west: west southwest.
  • west: west.
  • west_north_west: west northwest.
  • north_west: northwest.
  • north_north_west: north northwest.
5 Wind direction value wind_direct_value Send and report (read-write) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
6 Temperature, humidity, EC, and pH value of soil 1 soil_data_1 Report only (read-only) raw {
“humidity”:“”,// Soil humidity
“temp”:“”,// Soil temperature
“ecValue”:“”,// The EC value of the soil
“phValue”:“”,// The pH value of the soil
}
7 Temperature, humidity, EC, and pH value of soil 2 soil_data_2 Report only (read-only) raw {
“humidity”:“”,// Soil humidity
“temp”:“”,// Soil temperature
“ecValue”:“”,// The EC value of the soil
“phValue”:“”,// The pH value of the soil
}
8 Temperature, humidity, EC, and pH value of soil 3 soil_data_3 Report only (read-only) raw {
“humidity”:“”,// Soil humidity
“temp”:“”,// Soil temperature
“ecValue”:“”,// The EC value of the soil
“phValue”:“”,// The pH value of the soil
}
9 Temperature, humidity, EC, and pH value of soil 4 soil_data_4 Report only (read-only) raw {
“humidity”:“”,// Soil humidity
“temp”:“”,// Soil temperature
“ecValue”:“”,// The EC value of the soil
“phValue”:“”,// The pH value of the soil
}
10 Outdoor humidity humidity_outdoor Send and report (read-write) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
11 Outdoor temperature temp_outdoor Send and report (read-write) value
  • Value range: -1,000,000 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: °C
12 Noise noise_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: dB
13 Atmospheric Pressure atmospheric_pressture Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: kPa
14 Lighting intensity light_intensity Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: lux
15 Rainy & Snowy Status rain_snow_state Report only (read-only) enum The enumeration values: snowy and normal.
16 Ultraviolet index uv_index Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
17 Total radiation radiation_total Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
18 Photosynthetically active radiation radiation_pho Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
19 Cumulative rainfall rain_total Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: mm
20 Actual rainfall rain_current Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: mm
21 Instantaneous rainfall rain_instant Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: mm
22 Daily rainfall rain_1h Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: mm
23 O3 concentration o3_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: ppm
24 CO concentration co_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: ppm
25 SO2 concentration so2_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: ppm
26 O2 concentration o2_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
27 H2S concentration h2s_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: ppm
28 Evaporation amount evap_total Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
29 PM2.5 concentration pm25_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: ug/m3
30 PM10 pm10 Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: ug/m3
31 Nitrogen nitrogen_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
32 Phosphorus phosphorus_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
33 Potassium potassium_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
34 Negative oxygen ion air_anion_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
35 NH3 concentration nh3_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
36 VOC concentration voc_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
37 Power status setting relay_status Send and report (read-write) enum The enumeration values: on and off.
38 Status state Send and report (read-write) enum The enumeration values: run and stop.
39 Residual chlorine concentration ppm_value Send and report (read-write) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
40 PH value ph Send and report (read-write) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
41 Water quality water_quality Report only (read-only) enum The enumeration values: normal and alarm.
42 Turbidity turbidity_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
44 Fault alarm fault Report only (read-only) fault The fault values: fault, sensor_fault, and amb_temp_fault.
47 Air quality air_quality_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
49 Battery capacity battery_percentage Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: mA
50 NO2 concentration no2_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: ppm
51 CO2 concentration co2_value Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3
  • Unit: ppm
52 Remaining height height Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 3

Device MQTT API reference

Overview

An MQTT message consists of a fixed header, variable header, and payload.

For more information about the format of fixed headers and variable headers, see MQTT Specification. The format of the payload is defined by Tuya as follows.

The MQTT syntax and API details shall conform to MQTT Specification.

Common MQTT message types include CONNECT, SUBSCRIBE, and PUBLISH.

  • CONNECT: A client requests a connection to a server. It is the main parameter of a payload. For more information, see Connection authentication.
  • SUBSCRIBE: A client requests to subscribe to a specified topic. For more information about the topic name in a payload, see the specified topic whose subscriber is a device in the Topic definition.
  • PUBLISH: The platform publishes messages.
    • The Topic name in a variable header refers to a specified topic whose publisher is a device during reporting to the Tuya IoT Development Platform. For more information, see Topic definition.
    • The main parameter in a payload is the complete message content between the device and the platform. It is currently a JSON object.

Limitations

  • An uplink topic indicates that the device sends a request to the platform, reports data, or replies with a response.
  • A downlink topic means that the platform sends commands to the device or replies with a response.
  • After the device establishes a connection with the platform, the device must subscribe to the downlink topic. Otherwise, the device will not be able to receive the command or response sent by the platform.

Communication between the device and the platform

The device connects to and communicates with Tuya IoT Edge Gateway. The following figure shows how the communications between the device, Tuya IoT Edge Gateway, and Tuya IoT Development Platform work.

Integration with Environmental Monitoring Devices

The device reports data to Tuya IoT Edge Gateway

The device connects to and communicates with Tuya IoT Edge Gateway. The device can report data to the platform in the following ways.

Device property reporting: The device reports property data to the platform in the format defined in the product model.

The application server sends commands to the device.

After the connection is established, Tuya IoT Edge Gateway can send commands to the device as follows.

Platform command sending: The application server sends control commands to the device in a format defined in the product model.

Topic definition

After the device connects to Tuya IoT Edge Gateway over the MQTT protocol, the platform communicates with the device through topics. The following table lists the preset topics:

Type Topic Publisher Subscriber Purpose
Device sync topic gateway_id/{gateway_id}/devices/sync Device Platform Activate devices.
Device sync topic gateway_id/{gateway_id}/devices/sync/response Platform Device The platform returns an activation response.
Device command topic gateway_id/{gateway_id}/commands Platform Device The platform sends commands to the device.
Device command topic gateway_id/{gateway_id}/commands/response Device Platform The device returns a command response.
Device property topic gateway_id/{gateway_id}/properties/report Device Platform Report device properties.
Device property topic gateway_id/{gateway_id}/properties/report/response Platform Device The platform returns a response to property reporting.
Device online/offline topic gateway_id/{gateway_id}/devices/status Device Platform Report device online and offline events.

{gateway_id} is used to identify the target device of the topic route. When the device subscribes to the topic or sends messages to the topic, this value needs to be replaced with the gateway ID used when the device establishes an MQTT connection with the platform.

QoS level setting

The MQTT protocol specifies the quality of service (QoS) to ensure the reliability of message delivery in different network environments. The MQTT protocol has designed three QoS levels.

  • QoS 0: The message is delivered at most once. If the client is unavailable at that time, the message will be lost.
  • QoS 1: The message is delivered at least once.
  • QoS 2: The message is delivered exactly once.

The higher the QoS level, the more complex the process, and the greater the consumption of system resources. Applications can choose the appropriate QoS level based on the network scenarios and business requirements.

We recommend that you set the QoS level to 1 for message publishing and subscription during device integration.

Connection authentication

On the Tuya IoT Development Platform, devices support the connect message interface of the MQTT protocol. After the authentication is passed, the MQTT connection between the device and the platform is established.

Parameters

Parameter Required Type Description
broker Yes String The IP address of Tuya IoT Edge Gateway, to be provided by Tuya.
port Yes String The TCP port number is 58090 and the SSL/TLS port number is 21883.
clientId Yes String The unique ID of a specified third-party gateway.
username Yes String The username to identify a third-party manufacturer, to be provided by Tuya.
password Yes String The value of a password is generated using the MD5 encryption algorithm. For more information, see Password generation rules.

SSL/TLS is a one-way authentication mode.

Password generation rules

Concatenate the clientId and username variables, and then encrypt the concatenated variables with the MD5 encryption algorithm.

The following sample shows how to generate a connection password for Go.

func generatePassword() string {
	var (
		clientId string
		username string
		password string
	)
	// clientId username   Assign values first
	password = md5V(clientId + username)
	return password
}

// MD5 encryption algorithm function
func md5V(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}

Return code of native MQTT protocol

The following table lists the return codes when a device establishes a connection to the platform over the native MQTT protocol.

Return code Identifier Description Reason
0x00 / The connection is successful. The connection is successful.
0x01 unacceptable protocol version The request is rejected because the protocol version is incorrect. The server does not support the MQTT protocol version, based on which the client sends the request.
0x02 identifier rejected The request is rejected because the client identifier is invalid. The clientId is not in the required format or the heartbeat interval does not meet the platform requirements.
0x03 server unavailable The request is rejected because the server is unavailable. The platform service is unavailable.
0x04 bad user name or password The request is rejected because the username or password is incorrect. The username or password is incorrect.
0x05 not authorized The request is rejected because the client is not authorized. The client is not authorized to establish a connection.

Synchronize devices

It is used for device synchronization. After the device gateway is connected to the MQTT server of Tuya IoT Edge Gateway, send the device synchronization command. Then, Tuya IoT Edge Gateway will add or update devices based on the reported device data.

Sub-devices must be synchronized before subsequent operations. Otherwise, the system will return an error message to indicate that devices cannot be found.

Topic

  • Uplink: gateway_id/{gateway_id}/devices/sync

  • Downlink: gateway_id/{gateway_id}/devices/sync/response

Uplink parameters

Field Required Type Description
t Yes Integer The Unix timestamp.
request_id Yes String The identifier of a specified request. We recommend that the request identifier be generated by using the UUID algorithm.
param Yes Object The object.
param.cid Yes String The ID of a specified third-party device, to be defined by the device. It can be a unique readable identifier of the device, such as device SN or IMEI.
param.product_id Yes String The ID of a specified product.
param.vendor_code Optional String The code of a specified manufacturer.
param.comm_type Optional String The communication mode between a device and a gateway. Enter mqtt.
param.device_ip Optional String The IP address of a specified device.
param.mac_address Optional String The MAC address of a specified device.
param.device_desc Optional String The description of a specified device.
param.install_location Optional String The installation location of a specified device.
param.device_server_id Optional String The ID of a specified device server.
param.product_sub_type Optional String The sub-type of a specified product.

Downlink parameters

Field Required Type Description
t Yes Integer The Unix timestamp.
request_id Yes String The unique identifier of a request.
param Yes Object The object.
param.cid Yes String The CID of a specified device.
param.msg Yes String The error message. See Global error codes.
param.code Yes Integer The execution result of a specified command. Valid values:
  • 0: success
  • Other values: failure

Sample of uplink parameters

Topic: gateway_id/{gateway_id}/devices/sync
Data format:
{
    "t":1627280***,
    "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a085****",
    "param":{
        "cid":"92dda538fc2e636fd4b0c37f980b****",
        "product_id":"sie4****",// Enter the PID of a specified product
        "vendor_code":"",// The code of a specified device manufacturer
        "comm_type":"",
        "device_ip":"",
        "mac_address":"",
        "device_name":"",
        "device_desc":"",
        "install_location":"",
        "device_server_id":"",
        "product_sub_type":""
    }
}

Sample of downlink parameters

Topic: gateway_id/{gateway_id}/devices/sync/response
Data format:
{
    "t":1627280***,
    "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a085****",
    "param":{
        "cid":"92dda538fc2e636fd4b0c37f980b****",
        "msg":"success",
        "code":0
    }
}

Device commands

Send a command from the platform

Send a device control command from the platform to a specified smart device. After the command is sent, the device needs to return the execution result to the platform in time. If the device does not respond, the platform will consider the command execution timed out.

Topic

  • Downlink: gateway_id/{gateway_id}/commands
  • Uplink: gateway_id/{gateway_id}/commands/response
Downlink request parameters
Field Required Type Description
t Yes Integer The Unix timestamp.
cid Yes String The ID of a specified third-party device, to be defined by the device. It can be a unique readable identifier of the device, such as device SN or IMEI.
request_id Yes String The identifier of a specified request. We recommend that the request identifier be generated by using the UUID algorithm.
param Yes Object The object.
param.id Yes String The ID of a specified data point.
param.value Yes Not fixed The execution parameters of device commands.
Uplink response parameters

Respond to the commands in JSON format.

Field Required Type Description
t Yes Integer The Unix timestamp.
cid Yes String The ID of a specified third-party device, to be defined by the device. It can be a unique readable identifier of the device, such as device SN or IMEI.
request_id Yes String The unique identifier of a specified request. We recommend that the request identifier be generated with the UUID algorithm.
param Yes Object The object.
param.msg Yes String The execution result. Enter success to indicate a successful execution.
param.code Yes Integer The execution result of a specified command. Valid values:
  • 0: success
  • Other values: failure
Sample downlink request
Topic: gateway_id/{gateway_id}/commands
Data format:
{
  "t":1627280***,
  "cid": "92dda538fc2e636fd4b0c37f980b****",
  "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a085****",
  "param": {
    "id":"1",
    "value": "1"
  }
}
Sample uplink response
Topic: gateway_id/{gateway_id}/commands/response
Data format:
{
  "t":1627280***,
  "cid": "92dda538fc2e636fd4b0c37f980b****",
  "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a085****",
  "param": {
    "msg": "success",
    "code":0
  }
}

Device properties

Report device properties

The device reports property data to the platform in the format defined in the product model. After receiving the reported message, the platform will return the execution result to the device.

Topic

  • Uplink: gateway_id/{gateway_id}/properties/report

  • Downlink: gateway_id/{gateway_id}/properties/report/response

Uplink parameters
Field Required Type Description
t Yes Integer The UTC timestamp when a device connects to the platform.
request_id Yes String The unique identifier of a specified request. We recommend that the request identifier be generated with the UUID algorithm.
param Yes Object The object.
param.cid Yes String The ID of a specified third-party device, to be defined by the device. It can be a unique readable identifier of the device, such as device SN or IMEI.
param.product_id Yes String product_id: the ID of your product.
param.id Yes String The ID of a specified data point.
param.value Yes Refer to the DP type The property value of a specified device.
Downlink parameters
Field Required Type Description
t Yes Integer The Unix timestamp.
request_id Yes String The unique identifier of a request.
param Yes Object The object.
param.cid Yes String The ID of a specified third-party device, to be defined by the device. It can be a unique readable identifier of the device, such as device SN or IMEI.
param.msg Yes String The error message. See Global error codes.
param.code Yes Integer The execution result of a specified command. Valid values:
  • 0: success
  • Other values: failure
Sample of uplink parameters
gateway_id/{gateway_id}/properties/report
{
    "t":1627280***,
    "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a085****",
    "param":{
        "cid":"ee1880aca6b****",
        "product_id":"r2fz6uv6aufd****",
        "id":"1",
        "value":"run"
    }
}
Sample of downlink parameters
Topic: gateway_id/{gateway_id}/properties/report/response
Data format:
{
    "t":1627280***,
    "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a085****",
    "param":{
        "cid":"92dda538fc2e636fd4b0c37f980b****",
        "msg":"success",
        "code":0
    }
}

Report device online and offline event

Report device online and offline events

The device gateway needs to regularly synchronize the device’s online and offline status to the Tuya IoT Edge Gateway. We recommend that the status of the sub-devices be reported at least once every minute.

Topic

Uplink: gateway_id/{gateway_id}/devices/status

Uplink parameters
Field Required Type Description
t Yes Integer The UTC timestamp when a device connects to the platform.
request_id Yes String The unique identifier of a specified request. We recommend that the request identifier be generated with the UUID algorithm.
param Yes Object The array of objects.
param.cid Yes String The ID of a specified third-party device, to be defined by the device. It can be a unique readable identifier of the device, such as device SN or IMEI.
param.status Yes Bool The device status.
  • true: The device is online.
  • false: The device is offline.
Sample of uplink parameters
Topic: gateway_id/{gateway_id}/devices/status
Data format:
{
  "t":1627280***,
  "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a085****",
  "param": [{
    "cid": "92dda538fc2e636fd4b0c37f980b****",
    "status":true
  },
  {
    "cid": "da538fc2ebffdb463692dfdb0c37****",
    "status":false
  }
 ]
}

Sample application

To help you make API requests, we provide development samples for Java, PHP, and Go, and demonstrate basic features such as service connection, verification, encryption and decryption of sensitive information, and message subscription. Development libraries for more languages will be available in the near future.

Java

Add the dependency definitions shown below to the Maven POM file.

<dependencies>
    <dependency>
        <groupId>org.eclipse.paho</groupId>
        <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
        <version>1.2.0</version>
    </dependency>
</dependencies>
// Message publishing
public class Publish {
    public static void main(String[] args) {
        String clientId = "";                     // The gatewayID that identifies the third-party manufacturer
        String topic = "";                        // The topic
        String content = "";                      // The content
        int qos = 1;                              //  The QoS
        String broker = "";                       // The IP address of the server
        String userName = "";                     // The username, to be provided by Tuya
        String password = "";                     // The password. See password generation rules.
        // The memory
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            // Create a client
            MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            // Create link parameters
            MqttConnectOptions connOpts = new MqttConnectOptions();
            // Remember state on reboot and reconnection
            connOpts.setCleanSession(false);
            // Set a username used for connection
            connOpts.setUserName(userName);
            connOpts.setPassword(password.toCharArray());
            // Establish a connection
            sampleClient.connect(connOpts);
            // Create a message
            MqttMessage message = new MqttMessage(content.getBytes());
            // Set the message QoS
            message.setQos(qos);
            // Publish the message
            sampleClient.publish(topic, message);
            // Close a connection
            sampleClient.disconnect();
            // Close the client
            sampleClient.close();
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
}
// Message subscription
public class Subscribe {

        public static void main(String[] args) throws MqttException {  
        String clientId = "";                     // The gatewayID that identifies the third-party manufacturer
        String host = "";                      // The IP address of the server
        String topic = "gateway/in/" + clientId;  // The topic
        int qos = 1;                              //  The QoS
        String userName = "";                     // The username, to be provided by Tuya
        String password = "";                     // The password. See password generation rules.
        try {
            // In MemoryPersistence, set where to save the clientid. The clientid is saved in the memory by default.
            MqttClient client = new MqttClient(host, clientid, new MemoryPersistence());
            // Set the MQTT connection
            MqttConnectOptions options = new MqttConnectOptions();
            // Specify whether to clear the session. Being false means that the server will keep the connection record of the client, and being true means that a new identity is used every time the client connects to the server.
            options.setCleanSession(true);
            // Set a username used for connection
            options.setUserName(userName);
            // Set a password used for connection
            options.setPassword(passWord.toCharArray());
            // Set a timeout value in seconds
            options.setConnectionTimeout(10);
            // Set a session heartbeat interval in seconds
            options.setKeepAliveInterval(20);
            // Set a callback function
            client.setCallback(new MqttCallback() {

                public void connectionLost(Throwable cause) {

                }
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    // Message processing
                    System.out.println("message content:"+new String(message.getPayload()));

                }
                public void deliveryComplete(IMqttDeliveryToken token) {

                }

            });
            client.connect(options);
            // Subscribe to the message
            client.subscribe(topic, qos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Go

package main

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"log"
	"os"
	"time"
)

const broker = ""                   // The IP address of the server. Contact Tuya's administrator.
const username = ""                 // The username, to be provided by Tuya.
const password = ""                 // The password. See password generation rules.
const clientID = ""                 // The gatewayID, the gateway ID of the third-party manufacturer.
const topic = ""                    // The theme
const port = "21883"                // The port number of the server

// Message subscription topic = "gateway/in/" + clientID
// Message publishing topic = "gateway/out/" + clientID

var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	fmt.Printf("TOPIC: %s\n", msg.Topic())
	fmt.Printf("MSG: %s\n", msg.Payload())
}

func main() {
	mqtt.DEBUG = log.New(os.Stdout, "", 0)
	mqtt.ERROR = log.New(os.Stdout, "", 0)
	opts := mqtt.NewClientOptions().AddBroker(fmt.Sprintf("tcp://%s:%s", broker, port)).SetClientID(clientID).
		SetUsername(username).SetPassword(password)
	
	
	opts.SetKeepAlive(60 * time.Second)
	// Set a message callback function
	opts.SetDefaultPublishHandler(f)
	opts.SetPingTimeout(1 * time.Second)
	
	
	c := mqtt.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	
	
    // Subscribe to the topic
	if token := c.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}
	
	
    // Publish the message
	token := c.Publish(topic, 0, false, "Hello World")
	token.Wait()
	
	
	time.Sleep(6 * time.Second)
	
	
    // Unsubscribe from the topic
	if token := c.Unsubscribe(topic); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}
	
	
    // Close a connection
	c.Disconnect(250)
	time.Sleep(1 * time.Second)
}

PHP

Publish a message

<?php
require("");                                // Import the MQTT file.
$server    = '';                            // The IP address of the server. Contact Tuya's administrator.
$port      = 21883;                         // The port number of the server.
$username  = '';                             // The username, to be provided by Tuya.
$password  = '';                             // The password. See password generation rules.
$client_id = ''                             // The gatewayID that identifies the third-party manufacturer.

$mqtt = new Bluerhinos\phpMQTT($server, $port, $client_id); // Instantiate the MQTT class.

if ($mqtt->connect(true, NULL, $username, $password))       // Establish a connection.
{
    $topic = 'gateway/in/'.$client_id;          // The topic.
    $key =  ''      // The encryption key, which is the password used for connection authentication.
    $msg = '';     // The message in the above-mentioned format.
    // qos = 0: Send only once, regardless of whether it is received or not.
    // qos = 1: Keep sending a message if no result is returned, and a duplicate message might be received.
    // qos = 2: Make sure the message must be received and not repeated.
    $mqtt->publish($topic, $msg, 0);// Send the data.
    $mqtt->close();                  // Close a connection.
}
else
{
    echo "Time out!\n";
}

Subscribe to a message

<?php
require("");                                // Import the MQTT file.
$server    = '';                            // The IP address of the server. Contact Tuya's administrator.
$port      = 21883;                         // The port number of the server.
$username  = '';                             // The username, to be provided by Tuya.
$password  = '';                             // The password. See password generation rules.
$client_id = ''                             // The gatewayID that identifies the third-party manufacturer.

$mqtt = new Bluerhinos\phpMQTT($server, $port, $client_id);

$mqtt->debug = true;

if(!$mqtt->connect(true, NULL, $username, $password))
{
    echo "Connection failed!\n";
    exit(1);
}
$topic = 'gateway/in/'.$client_id;          //  The topic
// Subscription list
$topics = [
    $topic => ['qos' => 0, 'function' => 'procmsg'],
];

$mqtt->subscribe($topics, 0);

while ($mqtt->proc()){}

$mqtt->close();



function procmsg($topic, $msg)             //  The message processing function
{
    $key =  ''                              
    echo $msg;

}

Global error codes

If errors occur when you make API requests, custom error messages will be returned. This section describes the global error codes.

Error code Error message Description
400 tedge error: uplink specific error message The uplink error to be defined by the uplink service.
500 system error, please contact the admin System error. Contact the administrator
1001 request time is invalid The request time is invalid.
1100 params is empty The parameter is empty.
1101 params range invalid The parameter value is out of range.
1102 params is null The parameter is null.
1103 params type is incorrect Parameter type error.
1104 request pid is invalid The PID is invalid.
1105 id does not exist in pid The data point ID does not exist in the PID.
2001 device is offline The specified device is offline.
2002 command or value not support The command or value is not supported.
2003 device not exist The specified device does not exist.