Utilisez le modèle de script Python et l'exemple ci-dessous pour analyser les messages envoyés vers des rubriques personnalisées.
Modèle de script
SELF_DEFINE_TOPIC_UPDATE_FLAG = '/user/update' # The custom topic /user/update.
SELF_DEFINE_TOPIC_ERROR_FLAG = '/user/update/error' # The custom topic /user/update/error.
# Call a function to convert the data of the messages in a custom topic to JSON data when the device submits data to IoT Platform.
# topic: the 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 list of integers that cannot be empty.
# jsonObj: the output parameter. The value is a JSON object that indicates a dictionary.
def transform_payload(topic, rawData):
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.
# coding=UTF-8
SELF_DEFINE_TOPIC_UPDATE_FLAG = '/user/update' # The custom topic /user/update.
SELF_DEFINE_TOPIC_ERROR_FLAG = '/user/update/error' # The custom topic /user/update/error.
# Sample data:
# Custom topic: /user/update, to which data is sent.
# Input:
# topic: /${productKey}/${deviceName}/user/update
# bytes: 0x000000000100320100000000
# Output:
# {
# "prop_float": 0,
# "prop_int16": 50,
# "prop_bool": 1,
# "topic": "/${productKey}/${deviceName}/user/update"
# }
def transform_payload(topic, bytes):
uint8Array = []
for byteValue in bytes:
uint8Array.append(byteValue & 0xff)
jsonMap = {}
if SELF_DEFINE_TOPIC_ERROR_FLAG in topic:
jsonMap['topic'] = topic
jsonMap['errorCode'] = bytes_to_int(uint8Array[0:1])
elif SELF_DEFINE_TOPIC_UPDATE_FLAG in topic:
jsonMap['topic'] = topic
jsonMap['prop_int16'] = bytes_to_int(uint8Array[5:7])
jsonMap['prop_bool'] = bytes_to_int(uint8Array[7: 8])
jsonMap['prop_float'] = bytes_to_int(uint8Array[8:])
return jsonMap
# Convert a byte array into data of the INT type.
def bytes_to_int(bytes):
data = ['%02X' % i for i in bytes]
return int(''.join(data), 16)