JavaScript script examples

Updated at:

This topic provides templates and examples of data parsing scripts for Thing Specification Language (TSL) models in JavaScript.

Script template

You can use the following JavaScript template to write a data parsing script for a TSL model.

Note This template applies only to products for which the Data Format is set to Pass-through/Custom.
/**
 *  Transforms data from the Alink protocol to a format that a device can recognize. This function is invoked when IoT Platform sends data to the device.
 *  Input parameter: jsonObj, an object. Cannot be empty.
 *  Response parameter: rawData, a byte[] array. Cannot be empty.
 *
 */
function protocolToRawData(jsonObj) {
    return rawdata;
}

/**
 * Transforms custom-format data from a device to data in the Alink protocol. This function is invoked when the device uploads data to IoT Platform.
 * Input parameter: rawData, a byte[] array. Cannot be empty.
 * Response parameter: jsonObj, an object. Cannot be empty.
 */
function rawDataToProtocol(rawData) {
    return jsonObj;
}
            

Scripting notes

  • Avoid using global variables. They can cause inconsistent execution results.
  • The script processes data using two's complement. The two's complement range for [-128, 127] is [0, 255]. For example, the two's complement of -1 is 255 in decimal.
  • The input parameter of the function that parses data uploaded by a device (rawDataToProtocol) is an integer array. Perform an AND operation with 0xFF to obtain the corresponding two's complement.
  • The function that parses data sent from IoT Platform (protocolToRawData) returns an array. The array elements are integers with a value range of [0, 255].

Script example

The following script is based on the properties and communication protocol defined in TSL data parsing example.

var COMMAND_REPORT = 0x00; // Reports properties.
var COMMAND_SET = 0x01; // Sets properties.
var COMMAND_REPORT_REPLY = 0x02; // Returns the result for reported data.
var COMMAND_SET_REPLY = 0x03; // The device returns the result for a property setting operation.
var COMMAD_UNKOWN = 0xff;    // Unknown command.
var ALINK_PROP_REPORT_METHOD = 'thing.event.property.post'; // IoT Platform topic. The device uploads property data to the cloud.
var ALINK_PROP_SET_METHOD = 'thing.service.property.set'; // IoT Platform topic. The cloud sends property control instructions to the device.
var ALINK_PROP_SET_REPLY_METHOD = 'thing.service.property.set'; // IoT Platform topic. The device reports the result of a property setting operation to the cloud.
/*
Example data:
The device reports data.
Input parameters ->
    0x000000000100320100000000
Outputs ->
    {"method":"thing.event.property.post","id":"1","params":{"prop_float":0,"prop_int16":50,"prop_bool":1},"version":"1.0"}

Result returned for a property setting operation.
Input parameters ->
    0x0300223344c8
Outputs ->
    {"code":"200","data":{},"id":"2241348","version":"1.0"}
*/
function rawDataToProtocol(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 = new Object();
    var fHead = uint8Array[0]; // command
    if (fHead == COMMAND_REPORT) {
        jsonMap['method'] = ALINK_PROP_REPORT_METHOD; // Alink JSON format - topic for reporting properties.
        jsonMap['version'] = '1.0'; // Alink JSON format - fixed field for the protocol version number.
        jsonMap['id'] = '' + dataView.getInt32(1); // Alink JSON format - ID of the request.
        var params = {};
        params['prop_int16'] = dataView.getInt16(5); // Corresponds to the prop_int16 property of the product.
        params['prop_bool'] = uint8Array[7]; // Corresponds to the prop_bool property of the product.
        params['prop_float'] = dataView.getFloat32(8); // Corresponds to the prop_float property of the product.
        jsonMap['params'] = params; // Alink JSON format - standard params field.
    } else if(fHead == COMMAND_SET_REPLY) {
        jsonMap['version'] = '1.0'; // Alink JSON format - fixed field for the protocol version number.
        jsonMap['id'] = '' + dataView.getInt32(1); // Alink JSON format - ID of the request.
        jsonMap['code'] = ''+ dataView.getUint8(5);
        jsonMap['data'] = {};
    }

    return jsonMap;
}
/*
Example data:
Set properties.
Input parameters ->
    {"method":"thing.service.property.set","id":"12345","version":"1.0","params":{"prop_float":123.452, "prop_int16":333, "prop_bool":1}}
Outputs ->
    0x0100003039014d0142f6e76d

Result returned for reported data.
Input data ->
    {"method":"thing.event.property.post","id":"12345","version":"1.0","code":200,"data":{}}
Outputs ->
    0x0200003039c8
*/
function protocolToRawData(json) {
    var method = json['method'];
    var id = json['id'];
    var version = json['version'];
    var payloadArray = [];
    if (method == ALINK_PROP_SET_METHOD) // Set properties.
    {
        var params = json['params'];
        var prop_float = params['prop_float'];
        var prop_int16 = params['prop_int16'];
        var prop_bool = params['prop_bool'];
        // Concatenate rawData based on the custom protocol format.
        payloadArray = payloadArray.concat(buffer_uint8(COMMAND_SET)); // command field.
        payloadArray = payloadArray.concat(buffer_int32(parseInt(id))); // Alink JSON format 'id'.
        payloadArray = payloadArray.concat(buffer_int16(prop_int16)); // Value of the 'prop_int16' property.
        payloadArray = payloadArray.concat(buffer_uint8(prop_bool)); // Value of the 'prop_bool' property.
        payloadArray = payloadArray.concat(buffer_float32(prop_float)); // Value of the 'prop_float' property.
    } else if (method ==  ALINK_PROP_REPORT_METHOD) { // Result returned for data reported by the device.
        var code = json['code'];
        payloadArray = payloadArray.concat(buffer_uint8(COMMAND_REPORT_REPLY)); // command field.
        payloadArray = payloadArray.concat(buffer_int32(parseInt(id))); // Alink JSON format 'id'.
        payloadArray = payloadArray.concat(buffer_uint8(code));
    } else { // Unknown command. Some commands are not processed.
        var code = json['code'];
        payloadArray = payloadArray.concat(buffer_uint8(COMMAD_UNKOWN)); // command field.
        payloadArray = payloadArray.concat(buffer_int32(parseInt(id))); // Alink JSON format 'id'.
        payloadArray = payloadArray.concat(buffer_uint8(code));
    }
    return payloadArray;
}
// The following are helper functions.
function buffer_uint8(value) {
    var uint8Array = new Uint8Array(1);
    var dv = new DataView(uint8Array.buffer, 0);
    dv.setUint8(0, value);
    return [].slice.call(uint8Array);
}
function buffer_int16(value) {
    var uint8Array = new Uint8Array(2);
    var dv = new DataView(uint8Array.buffer, 0);
    dv.setInt16(0, value);
    return [].slice.call(uint8Array);
}
function buffer_int32(value) {
    var uint8Array = new Uint8Array(4);
    var dv = new DataView(uint8Array.buffer, 0);
    dv.setInt32(0, value);
    return [].slice.call(uint8Array);
}
function buffer_float32(value) {
    var uint8Array = new Uint8Array(4);
    var dv = new DataView(uint8Array.buffer, 0);
    dv.setFloat32(0, value);
    return [].slice.call(uint8Array);
}