Last Updated on : 2024-06-20 03:28:08download
This topic describes how to integrate smart water meters with the Tuya Developer Platform.
We provide the following solution to help connect smart water meters to the Tuya Developer Platform by using Tuya IoT Edge Gateway. The architecture is shown as follows:
During communications over the MQTT protocol, the smart water meter gateway works as a client, and Tuya’s IoT Edge Gateway works as a broker.
The following table lists the specified properties of a smart water meter for your reference.
DP ID | DP name | Identifier | Data transfer type | Data type | DP property |
---|---|---|---|---|---|
1 | Water flow | water_flow | Report only (read-only) | value | Value range: 0 to 999999999 . Unit: ㎥. |
2 | Total monthly water consumption | monthly_water_total | Report only (read-only) | value | Value range: 0 to 999999999 . Unit: ㎥. |
3 | Total daily water consumption | daily_water_total | Report only (read-only) | value | Value range: 0 to 999999999 . Unit: ㎥. |
4 | Switch status | switch_state | Send and report (read-write) | bool | / |
5 | First reading of a day | d_begin_water_total | Report only (read-only) | value | Value range: 0 to 999999999 . Unit: ㎥. |
6 | Last reading of a day | d_end_water_total | Report only (read-only) | value | Value range: 0 to 999999999 . Unit: ㎥. |
7 | First reading time of a day | d_begin_time | Report only (read-only) | string | The Unix timestamp. |
8 | Last reading time of a day | d_end_time | Report only (read-only) | string | The Unix timestamp. |
9 | Valve status | valve_state | Send and report (read-write) | enum | Enumeration values: opened , closed , opening , and closing . |
10 | First reading of a month | m_begin_water_total | Report only (read-only) | value | Value range: 0 to 999999999 . Unit: ㎥. |
11 | Last reading of a month | m_end_water_total | Report only (read-only) | value | Value range: 0 to 999999999 . Unit: ㎥. |
12 | First reading time of a month | m_begin_time | Report only (read-only) | string | The Unix timestamp. |
13 | Last reading time of a month | m_end_time | Report only (read-only) | string | The Unix timestamp. |
14 | Shared usage of cold water | cold_stall_userdata | Report only (read-only) | value | Value range: 0 to 999999999 . Unit: ㎥. |
15 | Sharing type of cold water | cold_stall_type | Send and report (read-write) | enum | Enumeration values: square_area , ignore , consumption , proportion , lease , and power . |
16 | Shared usage of hot water | hot_stall_userdata | Report only (read-only) | value | Value range: 0 to 999999999 . Unit: ㎥. |
17 | Sharing type of hot water | hot_stall_type | Send and report (read-write) | enum | Enumeration values: square_area , ignore , consumption , proportion , lease , and power . |
18 | Valve openness | valve_open_degree | Send and report (read-write) | value | Value range: 0 to 999999999 . Unit: %. |
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 Device 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.
Topic name
in a variable header refers to a specified topic whose publisher is a device during reporting to the platform. For more information, see Topic definition.Limitations
The device connects to and communicates with Tuya’s IoT edge gateway. The following figure shows how the communications between the device, Tuya’s IoT edge gateway, and Tuya Developer Platform work.
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.
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.
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.
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.
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.
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.
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
)
// Assign values to clientId and username 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))
}
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. |
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.
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
Field | Required | Type | Description |
---|---|---|---|
t | Yes | Integer | The Unix timestamp. |
request_id | Yes | String | The identifier of a specified request. We recommend 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. |
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 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. |
Topic: gateway_id/{gateway_id}/devices/sync
Data format:
{
"t":162728***,
"request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a***",
"param":{
"cid":"92dda538fc2e636fd***",
"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":""
}
}
Topic: gateway_id/{gateway_id}/devices/sync/response
Data format:
{
"t":162728***,
"request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a08***",
"param":{
"cid":"92dda538fc2e636fd4b0c37f***",
"msg":"success",
"code":0
}
}
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
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 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. |
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. |
Topic: gateway_id/{gateway_id}/commands
Data format:
{
"t":162728***,
"cid": "92dda538fc2e636fd4b0c37f980***",
"request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a08***",
"param": {
"id":"1",
"value": "1"
}
}
Topic: gateway_id/{gateway_id}/commands/response
Data format:
{
"t":162728***,
"cid": "92dda538fc2e636fd4b0c37f980***",
"request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a***",
"param": {
"msg": "success",
"code":0
}
}
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
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 water meter. |
param.value | Yes | Refer to the DP type | The property value of a specified device. |
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 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. |
gateway_id/{gateway_id}/properties/report
{
"t":162728***,
"request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a0***",
"param":{
"cid":"ee1880aca6b***",
"id":"1",
"value":"run"
}
}
Topic: gateway_id/{gateway_id}/properties/report/response
Data format:
{
"t":162728***,
"request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a085***",
"param":{
"cid":"92dda538fc2e636fd4b0c37f98***",
"msg":"success",
"code":0
}
}
The device gateway needs to regularly synchronize the device online and offline status to the Tuya IoT Edge Gateway. We recommend the status of the sub-devices be reported at least once every minute.
Topic
Uplink: gateway_id/{gateway_id}/devices/status
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 means online and false means offline. |
Topic: gateway_id/{gateway_id}/devices/status
Data format:
{
"t":162728***,
"request_id":"cd0fd3c3-bd15-42f6-8bf9-d230a08***",
"param": [{
"cid": "92dda538fc2e636fd4b0c37f98***",
"status":true
},
{
"cid": "da538fc2ebffdb463692dfdb0c3***",
"status":false
}
]
}
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.
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 {
MqttClient client = new MqttClient(host, clientid, new MemoryPersistence());
// Set the MQTT connection
MqttConnectOptions options = new MqttConnectOptions();
// Set whether to clear the session. `false` means the server will keep the connection record of the client, and `true` means every time the client connects to the server with a new identity.
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();
}
}
}
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)
}
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;
}
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. |
Is this page helpful?
YesFeedbackIs this page helpful?
YesFeedback