Tous les produits
Search
Centre de documentation

IoT Platform:Exemple de script JavaScript

Dernière mise à jour :Aug 09, 2026

Cette rubrique propose un modèle de script JavaScript et un exemple de script pour analyser les données envoyées vers des rubriques personnalisées.

Modèle 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;
}

Exemple de script

Remarque

L’exemple de script suivant analyse uniquement les messages envoyés vers des rubriques personnalisées. Si vous définissez le paramètre

Data Type

du produit sur

Custom

, vous devez également écrire un script pour analyser les messages du langage de spécification des objets (TSL). Pour plus d’informations, consultez la rubrique

Soumettre un script d’analyse de message de modèle TSL

.

Pour en savoir plus sur les custom data formats, consultez la rubrique Créer un produit.

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