This topic provides a JavaScript script template and a sample JavaScript script that you can use to parse data that is sent to custom topics.

Script template

var SELF_DEFINE_TOPIC_UPDATE_FLAG = '/user/update'  // Define the following custom topic: /user/update. 
var SELF_DEFINE_TOPIC_ERROR_FLAG = '/user/update/error' // Define the following custom topic: /user/update/error. 
/**
 * Convert data that is sent by a device to a custom topic to JSON data when the device submits the data to IoT Platform. 
 * topic: an input parameter that specifies the topic to which the device sends messages. The value is a string.  
 * rawData: the input parameter. The value is a byte array that cannot be empty. 
 * jsonObj: the output parameter. The value is a JSON object that cannot be empty. 
 */
function transformPayload(topic, rawData) {
    var jsonObj = {};
    return jsonObj;
}

Sample script

Note The following sample script can be used only to parse messages that are sent to custom topics. If you set the Data Type parameter of the product to Custom, you must also write a script to parse Thing Specification Language (TSL) messages. For information about how to write a script to parse TSL messages, see Submit a script to parse TSL data.

For information about custom data formats, see Create a product.

var SELF_DEFINE_TOPIC_UPDATE_FLAG = '/user/update'  // Define the following custom topic: /user/update. 
var SELF_DEFINE_TOPIC_ERROR_FLAG = '/user/update/error' // Define the following custom topic: /user/update/error. 
/*
  Sample data:
  Use the following custom topic to submit data:
     /user/update. 
  Input:
     topic: /${productKey}/${deviceName}/user/update
     bytes: 0x000000000100320100000000
  Output:
    {
        "prop_float": 0,
        "prop_int16": 50,
        "prop_bool": 1,
        "topic": "/${productKey}/${deviceName}/user/update"
    }
 */
function transformPayload(topic, bytes) {
    var uint8Array = new Uint8Array(bytes.length);
    for (var i = 0; i < bytes.length; i++) {
        uint8Array[i] = bytes[i] & 0xff;
    }
    var dataView = new DataView(uint8Array.buffer, 0);
    var jsonMap = {};

    if(topic.includes(SELF_DEFINE_TOPIC_ERROR_FLAG)) {
        jsonMap['topic'] = topic;
        jsonMap['errorCode'] = dataView.getInt8(0)
    } else if (topic.includes(SELF_DEFINE_TOPIC_UPDATE_FLAG)) {
        jsonMap['topic'] = topic;
        jsonMap['prop_int16'] = dataView.getInt16(5);
        jsonMap['prop_bool'] = uint8Array[7];
        jsonMap['prop_float'] = dataView.getFloat32(8);
    }

    return jsonMap;
}