This topic provides a sample script for parsing data from custom topics in Python.

Script Template

SELF_DEFINE_TOPIC_UPDATE_FLAG = '/user/update'  #Custom topic: /user/update
SELF_DEFINE_TOPIC_ERROR_FLAG = '/user/update/error'  #Custom topic: /user/update/error

# Convert 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 list. The list elements must be of the Int type and cannot be empty.
# Output: A jsonObj dictionary. It cannot be empty.    
def transform_payload(topic, rawData):
   jsonObj = {}
   return jsonObj

Example

Note The following script is used only to parse custom topic data. If the Data Format of the product is Custom, you also need to write a script for parsing TSL data. For more information about parsing TSL data, see Example for parsing TSL data.
# coding=utf-8
SELF_DEFINE_TOPIC_UPDATE_FLAG = '/user/update'  #Custom topic: /user/update
SELF_DEFINE_TOPIC_ERROR_FLAG = '/user/update/error'  #Custom topic: /user/update/error

# Sample data
# Custom topic: /user/update reports 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"
#   }
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

# Converts a byte array to an integer type
def bytes_to_int(bytes):
    data = ['%02X' % i for i in bytes]
    return int(''.join(data), 16)