Alicloud Internet of things platform custom Topic script parsing function demonstration


Before, all the customized topics on the Internet of things platform were used for direct transmission of messages, instead of data script analysis similar to the model of things. The latest self defined Topic script parsing function of the platform. The device reports data through the self-defined Topic with the parsing mark (? sn=default). After receiving the data, the Internet of things platform calls the data parsing script submitted by you on the console, converts the self-defined format data into a JSON structure, and then flows it to the subsequent business system. This paper mainly demonstrates the realization of this function.

Step By Step

1. Create products and devices

2. Add script

Sample script

3. The device simulates uplink data through a custom Topic

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;

// Transmission equipment test
public class IoTDemoPubSubDemoForPersonalTopic {

    // Device triple information
    public static String productKey = "a1wJG******";
    public static String deviceName = "Device1";
    public static String deviceSecret = "40YEyiGzXmvhDdpvbUVFCHjC********";
    public static String regionId = "cn-shanghai";

    private static String pubTopic = "/"+ productKey + "/" + deviceName  + "/user/update?_sn=default";//Script analysis of custom Topic
    private static MqttClient mqttClient;

    public static void main(String [] args){

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

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

     * 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+"";

            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



     * Reporting attributes
    private static void postDeviceProperties() {

        try {
            //Reporting data
            System.out.println("custom Topic Escalation attribute value");
            String hexString = "000000000100320100000000";
            byte[] payLoad = hexToByteArray(hexString);
            MqttMessage message = new MqttMessage(payLoad);
            mqttClient.publish(pubTopic, message);
        } catch (Exception e) {

     * hex String to byte array
     * @param inHex Hex string to be converted
     * @return  Converted byte array result
    public static byte[] hexToByteArray(String inHex){
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1){
            //Odd number
            result = new byte[(hexlen/2)];
        }else {
            //Even numbers
            result = new byte[(hexlen/2)];
        int j=0;
        for (int i = 0; i < hexlen; i+=2){
        return result;

     * Hex String to byte
     * @param inHex Hex string to be converted
     * @return  Converted byte s
    public static byte hexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);

Reference link: LoRaWAN device data analysis and open source MQTT SDK device end simulation

4. Uplink message view

5. Precautions

1. When creating a user-defined Topic on the Internet of things platform, it is defined as a normal Topic without adding the parsing tag;
2. Only analyze the data reported by the device in the cloud, not the downlink data in the cloud;
3. Only the payloads of the reported data are parsed, and the parsed payloads are returned;
4. Before and after analysis, the Topic of data remains unchanged. For example, the data sent by the device to / ${productKey}/${deviceName}/user/update is still in the Topic after parsing.

Reference link

Overview of custom data analysis Topic

LoRaWAN device data analysis and open source MQTT SDK device end simulation

Keywords: Java Eclipse SDK JSON

Added by ojeffery on Thu, 30 Jan 2020 06:41:58 +0200