このトピックでは、カスタム Topic データを解析する JavaScript のサンプルスクリプトを示します。

スクリプトテンプレート

var SELF_DEFINE_TOPIC_UPDATE_FLAG = '/user/update'  // Custom topic: /user/update
var SELF_DEFINE_TOPIC_ERROR_FLAG = '/user/update/error'  // Custom topic: /user/update/error
/**
 * Converts data from devices to JSON data. The function is called when devices report data through a custom topic to IoT Platform.
 * Input: A topic string. It is the topic for devices reporting messages.    
 * Input: A rawData byte [] array. It cannot be empty.
 * Output: A jsonObj dictionary. It cannot be empty.
 */
function transformPayload(topic, rawData) {
var jsonObj = {};
return jsonObj;
}

サンプルスクリプト

var SELF_DEFINE_TOPIC_UPDATE_FLAG = '/user/update'  // Custom topic: /user/update
var SELF_DEFINE_TOPIC_ERROR_FLAG = '/user/update/error'  // Custom topic: /user/update/error
/*
  サンプルデータ
  Custom Topic:/user/update for reporting data
Input parameters: topic:/{productKey}/{deviceName}/user/update, and bytes: 0x000000000100320100000000
  Output parameters:
  {
     "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 (int 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;
}