All Products
Search
Document Center

IoT Platform:Convert the data format of a TSL model

Last Updated:Apr 25, 2023

After you create a device, you must define a Thing Specification Language (TSL) model for the product. This way, you can use the TSL model to communicate with the AEP platform of China Telecom. The data format of a TSL model of Alibaba Cloud is different from the data format of a TSL model of the AEP platform of China Telecom. You must convert the data format in the IoT Platform console. In this example, a Python script is used to convert the data format.

Procedure

  1. Go to the Instance Details page of the Exclusive instance in the IoT Platform console. In the left-side navigation pane, choose Devices > Devices. On the Devices page, click View in the Actions column of the 15008261001 gateway device. On the Device Details page, click Device Log. On the Device Log tab, click View.

  2. On the Cloud run log tab, click View in the Actions column of a message that is sent from the device to IoT Platform.

  3. Select Hex from the Content drop-down list, click Copy and save the content to an on-premises server. This way, you can use a data parsing script to verify the content.

  4. In the left-side navigation pane, choose Devices > Products. On the Products page, click the name of the NBProduct1 product. On the product details page, click Message Analysis. On the Message Analysis tab, select Python 2.7 from the Script Language drop-down list. In the Edit Script section, delete the original code and then copy and paste the code of the following script to the section.

    The script applies only to this example. You can modify the script based on your TSL model. For more information, see Submit a script to parse TSL data.

    # -*- coding: UTF-8 -*-
    # The following template is provided based on an Alink product. You can write a script based on the template.
    
    # Convert the data that is sent by a device to a custom topic to JSON data when the device submits data to IoT Platform.
    * topic: an input parameter that specifies the topic to which the device sends messages. The value is a string.
    # rawData: an input parameter. The value is a list of integers that cannot be empty.
    # jsonObj: an output parameter. The value is a JSON object that indicates a dictionary.
    def transform_payload(topic, rawData):
       jsonObj = {}
       return jsonObj
    
    import json
    import common_util
    
    ALINK_PROP_REPORT_METHOD = 'thing.event.property.post'
    COMMAND_REPORT = 0x00 # Submit properties. 
    COMMAND_SET = 0x01 # Configure properties. 
    COMMAND_REPORT_REPLY = 0x02 # Return the result of data submission. 
    COMMAND_SET_REPLY = 0x03 # Return the result of property configuration. 
    COMMAD_UNKOWN = 0xff # Unknown commands. 
    ALINK_PROP_SET_METHOD = 'thing.service.property.set' # The topic for IoT Platform to send a property setting command to devices. 
    ALINK_PROP_SET_REPLY_METHOD = 'thing.service.property.set' # The topic for devices to submit the property setting results to IoT Platform. 
    SELF_DEFINE_TOPIC_UPDATE_FLAG = '/user/update' # Define the following custom topic: /user/update. 
    SELF_DEFINE_TOPIC_ERROR_FLAG = '/user/update/error' # Define the following custom topic: /user/update/error. 
    
    # Convert custom data of a device to Alink data when the device submits data to IoT Platform.
    # rawData: an input parameter. The value is a list of integers that cannot be empty.
    # jsonObj: an output parameter. The value is a JSON object that indicates a dictionary and cannot be empty.
    def raw_data_to_protocol(rawData):
        output = []
        for iters in rawData:
            output.append(chr(iters))
    
        inStr = ''.join(output)
    
        try:
            json_object = json.loads(inStr)
            # matched_out = json_object['notifyType']
            deviceId = json_object['deviceId']
            water_consumption = json_object['payload']
            running_data = water_consumption['water_consumption']
            # gatewayId = json_object['gatewayId']
            # service = json_object['service']
            # data_object = service['data']
            # imei = data_object['IMEI']
            # MeasureValue = json_object['MeasureValue']
            # Temperature = json_object['Temperature']
            # BatteryVoltage = data_object['BatteryVoltage']
        except ValueError, e:
            MeasureValue = 'err'
            # imei = 'err'
    
        jsonMap = {}
        jsonMap['method'] = ALINK_PROP_REPORT_METHOD
        jsonMap['version'] = '1.0'
        jsonMap['id'] = '123'
        params = {}
        # params['IMEI'] = imei
        params['deviceId'] = deviceId
        params['water_consumption']= running_data
        # params['gatewayId'] = gatewayId
        # params['MeasureValue'] = MeasureValue
        # params['BatteryVoltage'] = BatteryVoltage
        # params['Temperature'] = Temperature
        jsonMap['params'] = params
        return jsonMap
    
    # Convert an 8-bit integer to a byte array. 
    def int_8_to_byte(value):
        t_value = '%02X' % value
        if len(t_value) % 2 != 0:
            t_value += '0'
    
        return hex_string_to_byte_array(t_value)
    
        # Convert a 32-bit integer to a byte array. 
    def int_32_to_byte(value):
        t_value = '%08X' % value
        if len(t_value) % 2 != 0:
            t_value += '0'
    
        return hex_string_to_byte_array(t_value)
    
    
    # Convert a 16-bit integer to a byte array. 
    def int_16_to_byte(value):
        t_value = '%04X' % value
        if len(t_value) % 2 != 0:
            t_value += '0'
    
        return hex_string_to_byte_array(t_value)
    
    
    # Convert a hexadecimal string to a byte array. 
    def hex_string_to_byte_array(str_value):
        if len(str_value) % 2 != 0:
            return None
    
        cycle = len(str_value) / 2
    
        pos = 0
        result = []
        for i in range(0, cycle, 1):
            temp_str_value = str_value[pos:pos + 2]
            temp_int_value = int(temp_str_value, base=16)
    
            result.append(temp_int_value)
            pos += 2
        return result
    
    
    # Converts Alink data to a data format that can be recognized by the device before the data is sent to the device from IoT Platform.
    # jsonData: an input parameter. The value is a JSON object that indicates a dictionary and cannot be left empty.
    # rawData: an output parameter. The value is an array of integers within a value range of [0,255]. Array elements cannot be empty.
    def protocol_to_raw_data(myjson):
        payload_array = []
        in_params = myjson.get("params")
        test = in_params.get('test', None)
        method = myjson.get('method')
        print(method);
    
        if method == ALINK_PROP_SET_METHOD:
            params = myjson.get('params')
    
            params = {}
            params['test'] = test
    
            content= {}
            content['params']=params
            content['serviceIdentifier'] = 'test'
    
            mystr = json.dumps(content)
    
            for ch in mystr:
                    print(ch)
                    payload_array = payload_array + int_8_to_byte(ord(ch))
    
        elif method == ALINK_PROP_REPORT_METHOD:
            code = json.get('code', None)
            payload_array = payload_array + int_8_to_byte(COMMAND_REPORT_REPLY)
            payload_array = payload_array + int_32_to_byte(int(id))
            payload_array = payload_array + int_8_to_byte(code)
        else:
            code = json.get('code')
            payload_array = payload_array + int_8_to_byte(COMMAD_UNKOWN)
            payload_array = payload_array + int_32_to_byte(int(id))
            payload_array = payload_array + int_8_to_byte(code)
    
        return payload_array
  5. On the Input Simulation tab, select Upstreamed Device Data from the Simulation Type, paste the content that you saved in Step 3 to the editor, and then click Run.

  6. After you validate the script, click Submit to submit the script to IoT Platform.

  7. Go to the AEP platform of China Telecom. On the AEP-Online Debugging page of the nbdevice device, submit the data of water usage.

  8. Go to the Instance Details page of the Exclusive instance in the IoT Platform console. In the left-side navigation pane, choose Devices > Devices. On the Devices page, click View in the Actions column of the 15008261001 device.

    On the device details page, choose TSL Data > Status. The Status tab displays the converted data whose format complies with the data format of a TSL model of IoT Platform.

What to do next

Test downstream communication between IoT Platform and the AEP platform of China Telecom