Integration with Smart Electricity Meter

Last Updated on : 2024-06-20 03:20:25download

This topic describes how to integrate smart electricity meters with the Tuya Developer Platform.

Overview

We provide the following solution to help connect smart electricity meters to the Tuya Developer Platform by using Tuya IoT Edge Gateway. The architecture is shown as follows:

Integration with Smart Electricity Meter

Integration protocol

During communications over the MQTT protocol, the smart electricity meter gateway works as a client, and Tuya IoT Edge Gateway works as a broker.

Development guide

The following table lists the specified properties of a smart electricity meter for your reference.

Standard property values of a smart electricity meter

DP ID DP name Identifier Data transfer type Data type DP property
1 Switch switch Send and report (read-write) bool /
2 Circuit breaker number breaker_id Report only (read-only) string /
3 Actual power power_current Report only (read-only) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: W
5 Actual voltage voltage_current Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: V
6 Maximum current current_max Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: A
7 Actual current cur_current Report only (read-only) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: mA
8 Device information device_info Send and report (read-write) raw /
9 Status synchronization status_query Send and report (read-write) raw /
10 Actual temperature temp_current Report only (read-only) value
  • Value range: -100 to 1,000,000,000
  • Pitch: 1
  • Scale: 2
  • Unit: °C
11 Undervoltage value voltage_under Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: V
12 Overvoltage value voltage_over Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: V
13 Leakage alarm value leakage_warn_value Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: mA
14 Leakage fault value leakage_fault_value Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: mA
15 Leakage current leakage_current Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: mA
16 Leakage protection leakage_protection Report only (read-only) enum The enumeration values:
  • no_leak_pro_without_value: no leakage protection, without leakage value displayed.
  • no_leak_pro_with_value: no leakage protection, with leakage value displayed.
  • leak_pro_with_value: leakage protection, with leakage value displayed.
17 Enabling switch switch_enabled Send and report (read-write) bool /
18 Overcurrent duration over_current_duration Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 2
  • Unit: second (s)
19 Fault alarm fault Report only (read-only) fault The fault value.
  • short_circuit_alarm: short circuit alarm
  • surge_alarm: surge alarm
  • overload_alarm: overload alarm
  • ov_vol: overvoltage alarm
  • undervoltage_alarm: undervoltage alarm
  • temp_dif_fault: temperature anomaly alarm
  • leakagecurr_alarm: leakage alarm
  • self_test_alarm: leakage self-check anomaly
  • fire_alarm: electric arc alarm
  • high_power_alarm: high power alarm
  • ov_cr: overcurrent fault
  • outage_alarm: outage event alarm
  • magnetism_alarm: magnetic influence alarm
  • credit_alarm: insufficient balance alarm
20 The level of a specified alarm. alarm_level Report only (read-only) enum The enumeration values:
  • general: general alarm
  • serious: serious alarm
  • urgent: urgent alarm
21 Device alarm device_alarm Report only (read-only) string /
30 Report phase-A voltage, current, and power phase_a Report only (read-only) raw voltage indicates the voltage, current indicates the current, power indicates the power, and electricity indicates the electric power.
{
“voltage”:“”, // The voltage
“current”:“”, // The current
“power”:“” // The power
“electricity”:“”// The electric power
}
31 Report phase-B voltage, current, and power phase_b Report only (read-only) raw voltage indicates the voltage, current indicates the current, power indicates the power, and electricity indicates the electric power.
{
“voltage”:“”, // The voltage
“current”:“”, // The current
“power”:“” // The power
“electricity”:“”// The electric power
}
32 Report phase-C voltage, current, and power phase_c Report only (read-only) raw voltage indicates the voltage, current indicates the current, power indicates the power, and electricity indicates the electric power.
{
“voltage”:“”, // The voltage
“current”:“”, // The current
“power”:“” // The power
“electricity”:“”// The electric power
}
33 Leakage action value leakage_action_value Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
34 Over-temperature value over_temp_value Send and report (read-write) value
  • Value range: -100 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
35 Overvoltage and undervoltage protection time over_vol_protect_time Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: min
36 Overvoltage and undervoltage protection recovery time over_vol_recovery_time Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: min
37 Effective power power_effective Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: W
38 Reactive power power_reactive Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: W
39 Daily electricity consumption data daily_energy Send and report (read-write) raw /
40 Power factor power_factor Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
41 Grid power supply frequency supply_frequency Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
42 On/off times switch_times Report only (read-only) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 0
43 Number of times a short circuit happened short_times Report only (read-only) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 0
44 Total electricity electric_total Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: kW·h
45 Daily electricity consumption electric_daily Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: kW·h
46 Monthly electricity consumption electric_month Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: kW·h
47 Remaining electricity residual_electricity Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: kW·h
48 Power limit power_limit Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: W
49 Electricity consumption alert value electric_warm_value Send and report (read-write) value
  • Value range: 0 to 1,000,000,000
  • Pitch: 1
  • Scale: 4
  • Unit: kW
50 Forward total active electricity forward_energy_total Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 4
  • Unit: kW
51 Reactive electricity energy_reactive Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 4
  • Unit: kW
52 Apparent power power_apparent Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 4
  • Unit: kV
53 Shared usage of cold water cold_stall_userdata Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 4
54 Sharing type of cold water cold_stall_type Send and report (read-write) enum The enumeration values:
  • square_area: the area in square meters
  • ignore: ignore
  • consumption: electricity consumption
  • proportion: proportion
  • lease: lease
  • power: power
55 Shared usage of hot water hot_stall_userdata Report only (read-only) value
  • Value range: 0 to 999,999,999.
  • Pitch: 1
  • Scale: 4
56 Sharing type of hot water hot_stall_type Send and report (read-write) enum The enumeration values.
  • square_area: the area in square meters
  • ignore: ignore
  • consumption: electricity consumption
  • proportion: proportion
  • lease: lease
  • power: power
57 Switch status switch_state Send and report (read-write) bool /
58 Last reading time of a day d_end_time Report only (read-only) string /
59 Last reading time of a month m_end_time Report only (read-only) string /

API reference

MQTT API reference for the device

Read before use

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 Developer 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’s IoT Edge Gateway, and Tuya Developer Platform work.

Integration with Smart Electricity Meter

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 third-party device integration.

Connection authentication

Interface description

On the Tuya Developer 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 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 connection accepted 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 the reported devices.

Note: Sub-devices must be synchronized before subsequent operations. Otherwise, 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. If the result is 0, it indicates success. All other values indicate failure.
Sample of uplink parameters
Topic: gateway_id/{gateway_id}/devices/sync
Data format:
{
    "t":162728*****,
    "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a0****",
    "param":{
        "cid":"92dda538fc2e636fd4b0c37f****",
        "product_id":"",// 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":162728****,
    "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a08****",
    "param":{
        "cid":"92dda538fc2e636fd4b0c37f9****",
        "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 the command 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 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. If the result is 0, it indicates success. All other values indicate failure. If this parameter does not exist, it indicates success.
Sample downlink request
Topic: gateway_id/{gateway_id}/commands
Data format:
{
  "t":162728****,
  "cid": "92dda538fc2e636fd4b0c37f98****",
  "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a****",
  "param": {
    "id":"1",
    "value": "1"
  }
}
Sample uplink response
Topic: gateway_id/{gateway_id}/commands/response
Data format:
{
  "t":162728****,
  "cid": "92dda538fc2e636fd4b0c37f980b****",
  "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a****",
  "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 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.id Yes String The ID of a specified data point (DP) among properties of a smart electricity meter.
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. If the result is 0, it indicates success. All other values indicate failure.
Sample of uplink parameters
gateway_id/{gateway_id}/properties/report
{
    "t":162728****,
    "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230****",
    "param":{
        "cid":"ee1880aca6****",
        "id":"1",
        "value":"run"
    }
}
Sample of downlink parameters
Topic: gateway_id/{gateway_id}/properties/report/response
Data format:
{
    "t":162728****,
    "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a0****",
    "param":{
        "cid":"92dda538fc2e636fd4b0c37****",
        "msg":"success",
        "code":0
    }
}

Report online and offline event

Report 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 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":16272****,
  "request_id":"cd0fd3c3-bd15-42f6-8bf9-d230****",
  "param": [{
    "cid": "92dda538fc2e636fd4b0c37f****",
    "status":true
  },
  {
    "cid": "da538fc2ebffdb463692dfd**** ",
    "status":false
  }
 ]
}

Sample application

To help you make API requests, Tuya provides development samples for Java, PHP, and Go, and demonstrates basic features such as service connection, verification, encryption and decryption of sensitive information, and message subscription. Development libraries for more languages will be available soon.

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();
            // Set whether to clear the session. `false` means that the server will keep the connection record of the client, and `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 topic
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, 1, nil); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(1)
	}
	
	
    // Publish the message
	token := c.Publish(topic, 1, 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 mqtt class 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/out/'.$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 mqtt class 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)	 						// 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 A system error occurs while processing your request. Contact your 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 range is invalid.
1102 params is null The parameter is null.
1103 params type is incorrect The parameter type is incorrect.
2001 device is offline The device is offline.
2002 command or value not support The command or value is not supported.
2003 device not exist The device does not exist.