A thermo-hygrometer reports temperature and humidity data to IoT Platform. After IoT Platform forwards the temperature and humidity data to a DingTalk chatbot based on a data forwarding rule, the specified DingTalk group can receive the temperature and humidity data.

Background information

  • Scenario:

    Report the data that is collected by a thermo-hygrometer in an office to a DingTalk chatbot.

  • Business logic:

    Connect the thermo-hygrometer to IoT Platform by using Message Queuing Telemetry Transport (MQTT), which allows the thermo-hygrometer to report temperature and humidity data to IoT Platform. Configure a data forwarding rule to forward the temperature and humidity data to the pushData2DingTalk function in Function Compute. A Node.js script processes the data and sends the processed data to the webhook URL of the specified DingTalk chatbot. Then, the specified DingTalk group can receive the temperature and humidity data that is sent by the DingTalk chatbot.

    Figure 1. The following figure shows the procedure of reporting temperature and humidity data.

Procedure

  1. Configure a DingTalk chatbot.
    1. Log on to DingTalk for PC.
    2. In the Group Settings panel, click Group Assistant.
    3. Click Add Robot, select Custom, and then click Add.
    4. Specify the name of the chatbot and click Finished.
  2. Write a function script.
    1. Activate Function Compute.

      Function Compute is an event-driven, fully managed computing service. The programming languages that are supported by Function Compute include Java, Node.js, and Python.For more information, see How to use Function Compute.

    2. Write a function script. In this example, Node.js is used. The function obtains the device location, device serial number (SN), temperature, humidity, and the time of reporting from IoT Platform, and splices the data based on the specified DingTalk message format. The result is sent to the webhook URL of the specified DingTalk chatbot by using the HTTPS POST method.
    3. Log on to the Function Compute console and create a service. In this example, the created service is named IoT_Service.
    4. Create a function. You can create a blank function and do not set a trigger. The following figure shows the basic information about the function.
      Figure 2. Basic configurations

      The following code provides an example on how to define the pushData2DingTalk function:

      
      
      
      
      const https = require('https');
      const accessToken = 'Specify the webhook accessToken of the DingTalk chatbot';
      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. In the IoT Platform console, create a product and a device, add one or more device tags, and configure a data forwarding rule.
    1. Log on to the IoT Platform console.In the left-side navigation pane, choose Devices > Products and create a thermo-hygrometer product. IoT Platform generates a productKey.
    2. On the Product Details page of the product, click the Topic Categories tab. On the Topic Categories tab, click the Topic Category tab and then Edit Topic Category to create a topic category that has the permission to publish messages. In this example, the created topic category is /productKey/${deviceName}/user/data.
    3. In the left-side navigation pane, choose Devices > Devices. On the Devices page, click Add Device and set the parameters as required to create a thermo-hygrometer device. Obtain the deviceName and deviceSecret, which are used to authenticate the device when the device is connected to IoT Platform.
    4. In the Tag Information section of the Device Details page, click Edit to add one or more tags for the device.

      The following table describes the tags that are added in this example.

      Key Value Description
      tag Room 00XS, Floor F, Building X, Yunqi Town The location of the device.
      deviceISN T20180102XnbKjmo**** The SN of the device.
    5. Create and configure a data forwarding rule that is used to forward temperature and humidity data that is collected by the thermo-hygrometer to the function in Function Compute.
      1. Choose Rules > Data Forwarding. On the Data Forwarding page, click Create Rule and set the parameters as required to create a data forwarding rule.
      2. Configure the SQL statements that are used to process data.

        The rules engine supports SQL statements.

        In this example, fields are defined to obtain the following information:

        • Device name (deviceName) and device properties (tag and deviceISN).
        • Temperature value (temperature) and humidity value (humidity) from the payload of the messages that are sent from the thermo-hygrometer.

        The following content shows the sample SQL statement:

        
        SELECT
        deviceName() as deviceName,
        attribute('tag') as tag,
        attribute('deviceISN') as isn,
        temperature,
        humidity,
        timestamp('yyyy-MM-dd HH:mm:ss') as time
        FROM
        "/productKey/ + /user/data"
      3. Configure the operation of data forwarding to forward data to Function Compute.
    6. On the Data Forwarding page, find the rule that you want to enable and click Start in the Actions column to enable the rule.
  4. Connect the thermo-hygrometer device to IoT Platform and report temperature and humidity data to IoT Platform.

    To facilitate debugging, you can use a Node.js program to simulate the thermo-hygrometer device and report the collected temperature and humidity data. The aliyun-iot-mqtt library is used in this example. The demo.js file contains the following code:

    
    
    
    const mqtt = require('aliyun-iot-mqtt');
    const client = mqtt.getAliyunIotMqttClient({
    productKey: "The key of the product",
    deviceName: "The name of the device",
    deviceSecret: "The secret of the device"
    });
    const topic = 'the topic that is configured to forward data to Function Compute';
    const data = {
    temperature: 18,
    humidity: 63,
    };
    client.publish(topic, JSON.stringify(data));
  5. Simulate the process of sending a DingTalk group message.
    1. The program sends temperature and humidity data.
      
      $ npm install
      $ node demo.js
    2. The DingTalk chatbot receives the data and sends a message to the DingTalk group. The following figure shows the message that is received by the DingTalk group.
      Figure 3. DingTalk group message