Alibaba cloud IOT platform data forwarding to function calculation example

Summary

Using the data flow function of the rules engine of the Internet of things platform, you can forward data messages in topics to other topics or other Alibaba cloud products for storage or processing. In this paper, we mainly demonstrate how to use the rule engine to transfer the uplink message to the function calculation, and send the message to the nail robot through the function calculation.

Step By Step

Product and equipment preparation

1. Create product

2. Definition model

3. Add device

4. Using the SDK uplink message, refer to the link: Connect alicloud IoT based on open source JAVA MQTT Client

import com.alibaba.taro.AliyunIoTSignUtil;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class IoTDemoPubSubDemo {

    // Device triple information
    public static String productKey = "a16MX********";
    public static String deviceName = "device1";
    public static String deviceSecret = "YGLHxUr40E1JaWhk3IVAm0uk********";
    public static String regionId = "cn-shanghai";

    // Object model - attribute reporting topic
    private static String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
    // User defined topic, defined in the product topic list location
    private static String subTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";

    private static MqttClient mqttClient;

    public static void main(String [] args){

        initAliyunIoTClient();
        ScheduledExecutorService scheduledThreadPool = new ScheduledThreadPoolExecutor(1,
                new ThreadFactoryBuilder().setNameFormat("thread-runner-%d").build());

        scheduledThreadPool.scheduleAtFixedRate(()->postDeviceProperties(), 10,5, TimeUnit.SECONDS);

        try {
            mqttClient.subscribe(subTopic); // Subscribe to Topic
        } catch (MqttException e) {
            System.out.println("error:" + e.getMessage());
            e.printStackTrace();
        }

        // Set subscription listening
        mqttClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {
                System.out.println("connection Lost");

            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                System.out.println("Sub message");
                System.out.println("Topic : " + s);
                System.out.println(new String(mqttMessage.getPayload())); //Printout message payLoad
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });

    }

    /**
     * Initialize Client object
     */
    private static void initAliyunIoTClient() {

        try {
            // Parameters required to construct a connection
            String clientId = "java" + System.currentTimeMillis();
            Map<String, String> params = new HashMap<>(16);
            params.put("productKey", productKey);
            params.put("deviceName", deviceName);
            params.put("clientId", clientId);
            String timestamp = String.valueOf(System.currentTimeMillis());
            params.put("timestamp", timestamp);
            // cn-shanghai
            String targetServer = "tcp://" + productKey + ".iot-as-mqtt."+regionId+".aliyuncs.com:1883";

            String mqttclientId = clientId + "|securemode=3,signmethod=hmacsha1,timestamp=" + timestamp + "|";
            String mqttUsername = deviceName + "&" + productKey;
            String mqttPassword = AliyunIoTSignUtil.sign(params, deviceSecret, "hmacsha1");

            connectMqtt(targetServer, mqttclientId, mqttUsername, mqttPassword);

        } catch (Exception e) {
            System.out.println("initAliyunIoTClient error " + e.getMessage());
        }
    }

    public static void connectMqtt(String url, String clientId, String mqttUsername, String mqttPassword) throws Exception {

        MemoryPersistence persistence = new MemoryPersistence();
        mqttClient = new MqttClient(url, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        // MQTT 3.1.1
        connOpts.setMqttVersion(4);
        connOpts.setAutomaticReconnect(false);
//        connOpts.setCleanSession(true);
        connOpts.setCleanSession(false);

        connOpts.setUserName(mqttUsername);
        connOpts.setPassword(mqttPassword.toCharArray());
        connOpts.setKeepAliveInterval(60);

        mqttClient.connect(connOpts);
    }

    /**
     * Reporting attributes
     */
    private static void postDeviceProperties() {

        try {
            //Reporting data
            //Advanced version model - attribute reporting payload
            System.out.println("Escalation attribute value");
            String payloadJson = "{\"params\":{\"CurrentTemperature\":13,\"Humidity\":10}}";
            MqttMessage message = new MqttMessage(payloadJson.getBytes("utf-8"));
            message.setQos(1);
            mqttClient.publish(pubTopic, message);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

5. Operation status view

Function calculation creation and configuration

1. Create app

2. Apply add function below

3. Edit script

const https = require('https');

const accessToken = 'fill in accessToken,Nail robot webhook Of accessToken';
module.exports.handler = function(event, context, callback) {
var eventJson = JSON.parse(event.toString());
console.log(event.toString());
//Pin message format
const postData = JSON.stringify({
"msgtype": "markdown",
"markdown": {
"title": "Equipment temperature and humidity sensor",
"text": "#### Temperature and humidity sensor report \ n "+
"> Equipment name:" + eventJson.deviceName+ "\n\n" +
"> Real time temperature:" + eventJson.Temperature + "℃\n\n" +
"> Relative humidity:" + eventJson.Humidity + "%\n\n" +
"> ###### "+ eventJson.time +" publish by [Internet of things 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');
});
});
// Abnormal return
req.on('error', (e) => {
callback(e);
});
// Write data
req.write(postData);
req.end();
};

To obtain the reference link of the accessToken of webhook, a nail robot: Alibaba cloud IoT Studio service development timed light off function example Demo : 2.3 acquisition part of the nail robot Webhook.

4. Quick test

Rule engine configuration

1. Create rule engine

2. Configure processing data

SQL field

deviceName() as deviceName, items.Humidity.value as Humidity, items.CurrentTemperature.value as Temperature, timestamp('yyyy-MM-dd HH:mm:ss') as time

3. Configure forwarding data

4. Start the SDK on the device side, periodically send uplink messages, and view the notifications by pinning groups

5. Uplink log view

Reference link

Report data from hygrometer to nail group robot

Tags: Java Attribute JSON SDK

Posted on Fri, 07 Feb 2020 10:02:22 -0500 by ungovernable