DeviceIdMapper scripts

deviceid_codec.js script

This is a sample script for parsing the device ID from the free format topic.

devices/dht114044500000012/messages/events/ is the sample topic used for the below script. Since the device ID is located at the first index of the string (var deviceId = text.split('/')[1];), you can do a split on the backslash to parse the device ID from the topic.

var utils = Java.type('com.nokia.transformation.script.model.TransformUtil');

function DeviceIdCodec() {

    this.parse = function (decodeCtx) {
		var bytes = decodeCtx.getTopic();

        var text = bytes2String(bytes);
        console.log("input to decoder", text);
				        
		var deviceId = text.split('/')[1];

        return formDeviceIdMapping(decodeCtx, deviceId);
    }

}

var codec = new DeviceIdCodec();

(codec);

deviceid_util.js

To avoid complexity, scripts are separated into core codec functions and helper/utility functions as two separate script files. When a codec function script is executed, the associated utility script is preloaded. Below is an example of a utility script.

var utils = Java.type('com.nokia.transformation.script.model.TransformUtil');

// utility functions

function bytes2String(bytes, offset=0) {
    if (offset < 0) { 
		offset=0; 
	}
    var result = "";
    for (var i = offset; i < bytes.length; i++) {
        result += String.fromCharCode(bytes[i]);
    }
    return result;
}

function formDeviceIdMapping(decodeCtx, deviceId) {    
    console.log('sending deviceId mapping response: ' + deviceId);
    return utils.createStringResponse(deviceId);
}