All Products
Search
Document Center

IoT Platform:Push device data to DingTalk groups

Last Updated:Aug 15, 2023

This topic describes how to push data that is submitted by a device to a DingTalk group by using a data forwarding rule. In this example, a thermo-hygrometer is used.

Scenario

The data that is submitted by thermo-hygrometers in office rooms must be sent to a DingTalk chatbot.

Process

温湿度传感器流转数据流程

Step 1: Create a product and a device

  1. Log on to the IoT Platform console.

  2. On the Overview page, select an environment, find the instance that you want to manage, and click the instance ID or instance name.

  3. In the left-side navigation pane, choose Products and create a product named thermo-hygrometer. When you create the product, set the Node Type parameter to Directly Connected Device.

    Use the default values for other parameters. For more information, see Create a product.

  4. Click Create TSL. On the Define Feature tab, click Edit Draft. In the Default Module section, add custom features to the product.

    In this example, the temperature and humidity properties are added to the product. For more information, see Add a TSL feature.物模型

  5. In the left-side navigation pane, choose Devices > Devices. Create a device named TH_sensor under the thermo-hygrometer product. For more information, see Create a device.

    In the The devices have been added dialog box, click Learn More to obtain the device certificate that contains the ProductKey, DeviceName, and DeviceSecret. You must save the device certificate in a secure place. The certificate is a key credential for communication between the device and IoT Platform.

  6. On the Device List tab, find the device that you created and click View in the Actions column. The device details page appears. In the Tag Information section, click Edit to add tags to the device.

    In this example, the tags that are described in the following table are added. For more information, see Tags.

    Key

    Value

    Description

    tag

    Room 00XS, Floor F, Building X, YY Town

    The location of the device.

    deviceISN

    T20180102X

    The serial number (SN) of the device.

Step 2: Configure Function Compute

Function Compute is an event-driven and fully managed computing service. Function Compute supports Java, Node.js, and Python. For more information, see How to use Function Compute.

  1. Specify the webhook URL of a DingTalk chatbot.

    1. Log on to DingTalk on your PC.

    2. In the DingTalk chat window, click the 群设置 icon. In the panel that appears, click Group Assistant.

    3. Click Add Robot, and then click the 添加机器人 icon.

    4. Click Custom, and then click Add.

    5. Configure the Chatbot name and Security Settings parameters, select I have read and accepted <DingTalk Custom Robot Service Terms of Service>, and then click Finished.

    6. Click Copy to save the webhook URL on your PC.

  2. Write a Function Compute script.

    In this example, the Node.js runtime environment is used. The function obtains device data from IoT Platform, processes the data based on the specified DingTalk message format, and then sends the data to the webhook URL of the specified DingTalk chatbot by using the HTTPS POST method. The device data includes the device location, device SN, real-time temperature and humidity data, and the time when the device submits the data to IoT Platform.

    After you write the script, name the script file as index.js, and then compress the file into a package named index.zip. The following sample code provides an example of the script.

    You must replace accessToken with the value of the access_token parameter in the webhook URL.

    const https = require('https');
    const accessToken = 'Specify the value of the access_token parameter in the webhook URL.'
    module.exports.handler = function(event, context, callback) {
    var eventJson = JSON.parse(event.toString());
    // DingTalk message format
    const postData = JSON.stringify({
    "msgtype": "markdown",
    "markdown": {
    "title": "Thermo-hygrometer",
    "text": "#### Temperature and humidity details\n" +
    "> Device location: " + eventJson.tag + "\n\n" +
    "> Device SN: " + eventJson.isn+ "\n\n" +
    "> Temperature: " + eventJson.temperature + "℃\n\n" +
    "> Humidity: " + eventJson.humidity + "%\n\n" +
    "> ###### " + eventJson.time + " published by [IoT Platform](https://www.aliyun.com/product/iot) \n"
    },
    "at": {
    "isAtAll": false
    }
    });
    const options = {
    hostname: 'oapi.dingtalk.com',
    port: 443,
    path: '/robot/send?access_token=' + accessToken,
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(postData)
    }
    };
    const req = https.request(options, (res) => {
    res.setEncoding('utf8');
    res.on('data', (chunk) => {});
    res.on('end', () => {
    callback(null, 'success');
    });
    });
    // Return an error.
    req.on('error', (e) => {
    callback(e);
    });
    // Write the data.
    req.write(postData);
    req.end();
    };
  3. Create a service and a function.

    1. Activate Alibaba Cloud Function Compute. For more information, see Activate Function Compute.

    2. Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.

    3. Click Create Service, set the Name parameter to IoT_Service, and then click OK.

    4. On the Services page, click IoT_Service, and then click Create Function.

    5. On the Create Function page, select Use Built-in Runtime.

    6. Configure the parameters that are shown in the following figures. Use the default values for other parameters. Then, click Create.

      • Basic Settings

        Set the Function Name parameter to pushData2DingTalk, and set the Request Type parameter to Event Requests, as shown in the following figure.

        基本设置
      • Code

        Select Node.js 14 from the Runtime Environments drop-down list, and then upload the index.zip file that you created, as shown in the following figure.

        函数代码

Step 3: Forward data to Function Compute

Configure a data forwarding rule to forward the temperature and humidity data submitted by the TH_sensor device to the pushData2DingTalk function.

  1. Go to the IoT Platform console IoT Platform console, and then go to the details page of your instance. In the left-side navigation pane, choose , and then click Create Rule. Enter the rule name Temperature_humidity_forwarding and click OK.

    Important

    If the Data Forwarding page of the latest version appears, click Back to Previous Version in the upper-right corner of the page. When the Data Forwarding page of the previous version appears, click Create Rule.

  2. On the Data Forwarding Rules page, click Write SQL Statement to write the SQL statement used to process data.

    In this example, the following fields are specified to filter data:

    • The fields that specify the device information: deviceName, tag, and deviceISN.

    • The fields that specify the submitted data: temperature and humidity.

    Sample SQL statement:

    SELECT 
    deviceName() as deviceName, 
    attribute('tag') as tag, attribute('deviceISN') as isn, 
    items.temperature.value as temperature, items.humidity.value as humidity, 
    timestamp('yyyy-MM-dd HH:mm:ss') as time 
    FROM 
    "/g5j3o***/TH_sensorthing/event/property/post"
    编写SQL
  3. On the Data Forwarding Rules page, click Add Operation to forward data to Function Compute.

    In this example, the IoT_Service service and the pushData2DingTalk function are selected. For more information, see Forward data to Function Compute.转发数据

  4. On the Data Forwarding page, find the Temperature_humidity_forwarding rule that you created, and click Start in the Actions column to enable the rule.

Step 4: Connect the thermo-hygrometer device to IoT Platform and submit the temperature and humidity data

Connect the device to IoT Platform over Message Queuing Telemetry Transport (MQTT) by using the device certificate. Then, simulate the submission of the temperature and humidity data.

  1. Download and install Node.js on the Windows or Linux operating system. In this example, Windows 10 (64-bit) is used. Download the node-v14.15.1-x64.msi installation package.

  2. Open a Command Prompt window and run the following command to view the node version:

    node --version

    If the package is installed, the following version number appears:

    v14.15.1
  3. Create a JavaScript file, such as iot_device.js, on your PC to store the Node.js sample code.

    The following Node.js sample code provides an example on how to connect the device to IoT Platform and submit the data.

    const mqtt = require('aliyun-iot-mqtt');
    // 1. Specify the device certificate information.
    var options = {
        productKey: "g18l***",
        deviceName: "TH_sensor",
        deviceSecret: "b2e6e4f102458d84***",
        host: "iot-cn-***.mqtt.iothub.aliyuncs.com"
    };
    
    // 2. Establish an MQTT connection.
    const client = mqtt.getAliyunIotMqttClient(options);
    // Subscribe to the topic that is used to receive commands from IoT Platform.
    client.subscribe(`/${options.productKey}/${options.deviceName}/user/get`)
    client.on('message', function(topic, message) {
        console.log("topic " + topic)
        console.log("message " + message)
    })
    
    setInterval(function() {
        // 3. Submit the temperature and humidity data at a specified interval.
        client.publish(`/sys/${options.productKey}/${options.deviceName}/thing/event/property/post`, getPostData(), { qos: 0 });
    }, 5 * 1000);
    
    function getPostData() {
        const payloadJson = {
            id: Date.now(),
            version: "1.0",
            params: {
                temperature: Math.floor((Math.random() * 20) + 10),
                humidity: Math.floor((Math.random() * 20) + 10)
            },
            method: "thing.event.property.post"
    
        }
        console.log("payloadJson " + JSON.stringify(payloadJson))
        return JSON.stringify(payloadJson);
    }

    Parameter

    Example

    Description

    productKey

    g18l***

    The device certificate information that you saved after you created the device.

    You can view the information on the Device Details page of the TH_sensor device in the IoT Platform console.

    deviceName

    TH_sensor

    deviceSecret

    b2e6e4f102458d84***

    host

    iot-cn-***.mqtt.iothub.aliyuncs.com

    The endpoint that is used by the device to access IoT Platform over MQTT.

    For information about how to obtain the endpoint, see Manage the endpoint of an instance.

  4. Open the Command Prompt window and run the cd command to go to the directory where the iot_device.js file resides. In this directory, run the npm command to download the aliyun-iot-mqtt library. The following figure shows the downloaded library file.

    npm install aliyun-iot-mqtt -Saliyun-iot-mqtt

  5. After the MQTT library is downloaded, enter the following command in the Command Prompt window and run the iot_device.js code to start the device:

    node iot_device.js

Result

The following response indicates that the device is connected to IoT Platform and the data is submitted:

payloadJson {"id":161848***,"version":"1.0","params":{"temperature":22,"humidity":15},"method":"thing.event.property.post"}

The following figure shows the message that is received by the DingTalk chatbot.

钉钉机器人