Todos los productos
Search
Centro de documentos

IoT Platform:Script de JavaScript de ejemplo

Última actualización: Sep 03, 2026

Este tema proporciona una plantilla de script de JavaScript y un script de ejemplo que puede usar para analizar los datos enviados a temas personalizados.

Plantilla de script

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;
}

Script de ejemplo

Nota

A continuación se muestra un script de ejemplo que analiza solo los mensajes enviados a temas personalizados. Si establece el parámetro

Data Type

del producto en

Custom

, también debe escribir un script para analizar los mensajes de Thing Specification Language (TSL). Para obtener más información, consulte

Submit a TSL model message parsing script

.

Para obtener información sobre los custom data formats, consulte 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;
}