TSL model communication

Updated at:
Copy as MD

A Thing Specification Language (TSL) model is a data model that Alibaba Cloud IoT Platform uses to define a product. You can use the Python Link SDK to enable TSL model communication between a device and IoT Platform, which includes reporting properties and events, and invoking services.

Prerequisites

Background information

A Thing Specification Language (TSL) model is a data model that maps a physical device to the Alibaba Cloud IoT Platform. On the product page in the IoT Platform console, click the Function Definition tab, and then click TSL Model to view or export the TSL model file in JSON format.

TSL model: Standard data format (Alink JSON)

Initialization

In the thing_alink.py file, you can initialize the object in the __init__ function.

    def __init__(self):
        self.__linkkit = linkkit.LinkKit(
            host_name="cn-shanghai",
            product_key="a18wP******",
            device_name="LightSwitch",
            device_secret="uwMTmVAMnGGHaAkqmeDY6cHxxB******")

Configure the TSL model file

Download the TSL model file from the console and integrate it into your application project. This ensures that the corresponding topics can correctly send and receive messages.

self.__linkkit.thing_setup("tsl.json")        
Note
  • The tsl.json file uses the UTF-8 format by default. If you modify the file, you must save it in UTF-8 format.

  • You must apply this configuration before the device connects to the cloud.

The on_thing_enable function notifies you when the TSL model features are active. You can then report properties, report events, and respond to services.

     self.__linkkit.on_thing_enable = self.on_thing_enable

     def on_thing_enable(self, userdata):
        print("on_thing_enable")       

When TSL model features are not active, the on_thing_disable function notifies you. You cannot report properties, report events, or respond to services.

    self.__linkkit.on_thing_disable = self.on_thing_disable

    def on_thing_disable(self, userdata):
        print("on_thing_disable")    
Important

Use the APIs for reporting properties, reporting events, setting properties, and responding to services after the device is authenticated and connected.

Report properties

Important

In Python Link SDK versions 1.0.0 to 1.2.11, if you call the following API to send messages after the device disconnects from IoT Platform, an exception is thrown. You must handle this exception. In versions 1.2.12 and later, the API returns a non-zero error value instead of throwing an exception if the execution fails.

Use thing_post_property to report properties. The input parameters are the property names and their values.

    prop_data = {
        "abs_speed": 11,
        "power_stage": 10
    }
    self.__linkkit.thing_post_property(prop_data)          

The server-side processes the reported properties and sends a response. The SDK notifies you through on_thing_prop_post.

    self.__linkkit.on_thing_prop_post = self.on_thing_prop_post

    def on_thing_prop_post(self, request_id, code, data, message,userdata):
        print("on_thing_prop_post request id:%s, code:%d, data:%s message:%s" %
              (request_id, code, str(data), message))           

If the thing_post_property function returns rc=0, the request was successfully written to the send buffer. Other rc values indicate that the write operation failed. The on_thing_prop_post callback indicates that a response was received from the cloud. If the code value is 200, the parsing was successful. Other code values indicate a parsing failure. The failure information is available in message.

Report events

Important

In Python Link SDK versions 1.0.0 to 1.2.11, if you call the following API to send messages after the device disconnects from IoT Platform, an exception is thrown. You must handle this exception. In versions 1.2.12 and later, the API returns a non-zero error value instead of throwing an exception if the execution fails.

Use thing_trigger_event to report an event. The input parameters are the event identifier and the object that corresponds to the event defined in the TSL model.

    event_data = {
        "power": 10,
        "power_style": 1
    }
    self.__linkkit.thing_trigger_event(("power_state", event_data))            

After the server-side processes the reported event, it sends a response. The SDK notifies you through on_thing_event_post.

    self.__linkkit.on_thing_event_post = self.on_thing_event_post

    def on_thing_event_post(self, event, request_id, code, data, message, userdata):
        print("on_thing_event_post event:%s,request id:%s, code:%d, data:%s, message:%s" %
              (event, request_id, code, str(data), message))
        pass           

Set properties

After the server-side sends a message to set properties, the SDK notifies you through the on_thing_prop_changed callback function. The `params` parameter in the callback function is a JSON object that contains the property names and values. You must process the received properties.

    self.__linkkit.on_thing_prop_changed = self.on_thing_prop_changed

    def on_thing_prop_changed(self, params, userdata):
        print("on_thing_prop_changed params:" + str(params))     
Note

The SDK does not automatically report property changes. To report the changes to the cloud, you must call thing_post_property().

Service Response (Asynchronous)

After the server-side sends a service invocation message, the SDK notifies you through the on_thing_call_service callback function.

All services use the on_thing_call_service callback for notifications. You can use the identifier to distinguish between different services.

    self.__linkkit.on_thing_call_service = self.on_thing_call_service

    def on_thing_call_service(self, identifier, request_id, params, userdata):
        print("on_thing_call_service identifier:%s, request id:%s, params:%s" %
              (identifier, request_id, params))
        self.__call_service_request_id = request_id
        pass          

identifier corresponds to the service identifier in the TSL model. request_id is an ID that distinguishes each invocation. params contains the service invocation parameters.

The device sends a response to the service.

self.__linkkit.thing_answer_service(identifier, request_id, code, params)            

identifier is the service identifier from the TSL model. request_id is the request_id passed in on_thing_call_service. code is the return code. A value of 200 indicates that the local processing was successful. params is a dictionary that corresponds to the service response parameters in the TSL model.

TSL model: Custom format

Initialization

The Python Link SDK lets you transmit data in a custom format instead of the TSL model format.

In the thing_custom.py file, you can initialize the object in the __init__ function.

    def __init__(self):
        self.__linkkit = linkkit.LinkKit(
            host_name="cn-shanghai",
            product_key="a18wP******",
            device_name="LightSwitch",
            device_secret="uwMTmVAMnGGHaAkqmeDY6cHxxB******")

Configure the TSL model file

First, set the TSL model file parameter to an empty value.

self.__linkkit.thing_setup()           

Report data

Important

In Python Link SDK versions 1.0.0 to 1.2.11, if you call the following API to send messages after the device disconnects from IoT Platform, an exception is thrown. You must handle this exception. In versions 1.2.12 and later, the API returns a non-zero error value instead of throwing an exception if the execution fails.

To send data from a device to the cloud, use the thing_raw_post_data function to send data in a custom format to the server-side.

    def protocolToRawData(self, params):
        # command set
        payload_bytes = b'\x00'
        # id
        payload_bytes += b'\x00'
        payload_bytes += b'\x00'
        payload_bytes += b'\x00'
        payload_bytes += b'\x01'
        # prop_int16 big-endian
        prop_int16 = params["prop_int16"]
        payload_bytes += bytes([prop_int16 // 256])
        payload_bytes += bytes([prop_int16 % 256])
        return payload_bytes

    params = {
        "prop_int16": 11
        }
    payload = self.protocolToRawData(params)
    print("payload:%r" % payload.hex())
    self.__linkkit.thing_raw_post_data(payload)       

After the server-side receives the custom format data, it sends a response. The SDK notifies you through the on_thing_raw_data_post callback function.

self.__linkkit.on_thing_raw_data_post = self.on_thing_raw_data_post

def on_thing_raw_data_post(self, payload, userdata):
        print("on_thing_raw_data_post: %s" % str(payload))         

Receive mobile terminated messages

When the server-side sends data to the device, the SDK notifies you through the on_thing_raw_data_arrived callback function.

self.__linkkit.on_thing_raw_data_arrived = self.on_thing_raw_data_arrived

def on_thing_raw_data_arrived(self, payload, userdata):
        print("on_thing_raw_data_arrived:%r" % payload)
        print("prop data:%r" % self.rawDataToProtocol(payload))