All Products
Search
Document Center

IoT Platform:Python Link SDK

Last Updated:Feb 27, 2024

This topic describes how to use Link SDK for Python to connect a device to IoT Platform over Message Queuing Telemetry Transport (MQTT) and enable messaging.

Prerequisites

IoT Platform is activated.

Background information

You can configure the SDK to connect a simulated device to IoT Platform over MQTT. In this example, a device named LightSwitch is used. The device can submit data to IoT Platform by using custom topics.

For more information, see IoT Platform.

Create a product and a device

  1. Log on to the IoT Platform console. Then, click the card of the public instance.

  2. In the left-side navigation pane, choose Devices > Products. On the Products page, click Create Product.

  3. On the Create Product page, set the Product Name parameter to NightLightSwitch and the Category parameter to Custom Category. Use the default values for other parameters. Then, click OK.

    创建产品

  4. On the Create Product page, click Add in the Add Device section.

  5. On the Devices page, click Add Device.

  6. In the Add Device dialog box, enter a device name. Example: LightSwitch. Then, click OK.

    添加设备

  7. In the The devices have been added. dialog box, click Copy Device Certificate. Then, save the device certificate information to an on-premises server. For more information, see Device certificates.

Prepare the development environment

In this example, Python 3.6 is used as a development environment and PIP 3.6 is used as a development tool. For more information, see Project configurations.

  1. Install a Python development environment.

    For more information, see Python.

  2. Optional. Install the pip tool that is used to manage Python packages.

    For more information, see pip.

  3. Install the dependencies that are required to run sample code.

    • The pip tool is installed

      Go to a directory and run the following command:

      pip install aliyun-iot-linkkit
      pip install paho-mqtt==1.6.1
    • The pip tool is not installed

      Download the following open source libraries to your server, decompress the packages, and then run the python setup.py install command in each decompressed directory.

Configure the SDK

  1. Download a demo package from Demo file to the development environment and decompress the package.

  2. Open the ./mqtt_quick_start.py file and configure the following parameters.

    • Configure the parameters that are used to specify device connection information. This way, you can connect the device to IoT Platform. The following table describes the parameters. Sample code:

      lk = linkkit.LinkKit(
          host_name="cn-shanghai",
          product_key="a18wP******",
          device_name="LightSwitch",
          device_secret="uwMTmVAMnGGHaAkqmeDY6cHxxB******")
      # lk.config_mqtt(endpoint="iot-cn-6ja******.mqtt.iothub.aliyuncs.com")

      Parameter

      Example

      Description

      host_name

      cn-shanghai

      The ID of the region in which the device is connected to IoT Platform. For more information, see Regions and zones.

      product_key

      a18wP******

      The device certificate information. The device certificate is saved on your on-premises server after the device is created.

      You can view the device certificate on the Device Details page in the IoT Platform console. For more information, see Obtain device verification information.

      device_name

      LightSwitch

      device_secret

      uwMTmVAMnGGHaAkqmeDY6cHxxB******

    • Specify a topic to receive messages from IoT Platform. Example:

              elif msg == "3":
                  rc, mid = lk.subscribe_topic(lk.to_full_topic("user/get"))
                  if rc == 0:
                      print("subscribe topic success:%r, mid:%r" % (rc, mid))
                  else:
                      print("subscribe topic fail:%d" % rc)

      Parameter

      Example

      Description

      subscribe_topic

      lk.to_full_topic("user/get")

      The topic on which the device has the Subscribe permission. The device can receive messages from IoT Platform by using this topic.

      Example: lk.to_full_topic("user/get") or /a18wP******/LightSwitch/user/get.

      lk.to_full_topic("user/get") is a function that can be called to automatically generate a topic. The function obtains the values of the parameters that you configured, such as product_key and device_name and returns a string based on the values. The string is equivalent to /a18wP******/LightSwitch/user/get.

    • Specify a topic that can be used by the device to send messages. Example: /a18wP******/LightSwitch/user/update. Then, specify content for a message that you want to send. Example:

              elif msg == "5":
                  rc, mid = lk.publish_topic(lk.to_full_topic("user/update"), "{\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}}")
                  if rc == 0:
                      print("publish topic success:%r, mid:%r" % (rc, mid))
                  else:
                      print("publish topic fail:%d" % rc)

      Parameter

      Example

      Description

      publish_topic

      lk.to_full_topic("user/update"), "{\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}}"

      The destination topic and the message that you want to send. Use the specified conditions in the preceding formula.

      • The user/get section in the example is the suffix of the topic. You can send messages to a topic by specifying this section. The device must have the Publish permission on the topic.

        You can view custom topics in the IoT Platform console. On the Product Details page, click the Topic Categories tab. On this tab, click Topic Category. For more information, see Topics.

        In this example, the destination topic is /a18wP******/LightSwitch/user/update.

        • a1oGs****** indicates the ProductKey of the product to which the device belongs.

        • LightSwitch indicates the DeviceName of the device.

      • {\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}} indicates the content of the message that you want to submit to IoT Platform.

        In this example, a custom topic is used. You can specify custom message formats.

  3. After you configure the parameters, save the file.

Result

  • Go to the directory in which the executable sample code file resides, and run the following command:

    python mqtt_quick_start.py
    • After the sample code is executed, the following log data appears. The log data indicates that the LightSwitch device is connected to IoT Platform.

      2021-05-07 15:27:10,725-6508-14504 - linkkit:linkkit:info - INFO - config_mqtt enter
      2021-05-07 15:27:10,725-6508-14504 - linkkit:linkkit:debug - DEBUG - connect_async
      2021-05-07 15:27:10,727-6508-4408 - linkkit:linkkit:debug - DEBUG - LoopThread thread enter
      2021-05-07 15:27:10,727-6508-4408 - linkkit:linkkit:debug - DEBUG - enter
      2021-05-07 15:27:10,727-6508-4408 - linkkit:linkkit:info - INFO - start connect
      2021-05-07 15:27:10,729-6508-4408 - linkkit:linkkit:debug - DEBUG - current working directory:D:\******
      2021-05-07 15:27:10,799-6508-4408 - Paho:client:_easy_log - DEBUG - Sending CONNECT (u1, p1, wr0, wq0, wf0, c1, k60) client_id=b'a18wP******&LightSwitch|securemode=2,signmethod=hmacsha1,ext=1,lan=Python,_v=1.2.0,sii=Eth|03ACDEFF0032|Eth|03ACDEFF0031,timestamp=1620372430|'
      2021-05-07 15:27:10,831-6508-4408 - Paho:client:_easy_log - DEBUG - Received CONNACK (0, 0)
      2021-05-07 15:27:10,831-6508-4408 - linkkit:linkkit:info - INFO - __on_internal_connect
    • In the sample code, enter 3 to subscribe to the /a18wP******/LightSwitch/user/get topic.

      2021-05-07 16:03:52,423-25352-26452 - Paho:client:_easy_log - DEBUG - Sending SUBSCRIBE (d0, m2) [(b'/a18wP******/LightSwitch/user/get', 1)]
      subscribe topic success:0, mid:2
      2021-05-07 16:03:52,440-25352-24916 - Paho:client:_easy_log - DEBUG - Received SUBACK
      2021-05-07 16:03:52,440-25352-24916 - linkkit:linkkit:debug - DEBUG - post_message :'on_subscribe'
      2021-05-07 16:03:52,440-25352-24916 - linkkit:linkkit:debug - DEBUG - post_message success
      2021-05-07 16:03:52,441-25352-25544 - linkkit:linkkit:debug - DEBUG - thread runnable pop cmd:'on_subscribe'
      2021-05-07 16:03:52,441-25352-25544 - linkkit:linkkit:debug - DEBUG - __on_internal_subscribe mid:2  granted_qos:1
      on_subscribe_topic mid:2, granted_qos:1

      After you subscribe to a topic, you can return to IoT Platform. On the Topics tab of the Device Details page, find the topic and click Publish Notification in the Actions column. In the Publish Notification dialog box, enter a message, such as This is a test message from Alibaba IoT Platform.. Then, send the message from IoT Platform to the device.

      image..png

    • In the sample code, enter 5 to send a message to IoT Platform by using the /a18wP******/LightSwitch/user/update topic.

      2021-05-07 16:06:23,786-30364-20372 - Paho:client:_easy_log - DEBUG - Sending PUBLISH (d0, q1, r0, m3), 'b'/a18wP******/LightSwitch/user/update'', ... (53 bytes)
      publish topic success:0, mid:3
      2021-05-07 16:06:23,799-30364-27344 - Paho:client:_easy_log - DEBUG - Received PUBACK (Mid: 3)
      2021-05-07 16:06:23,799-30364-27344 - linkkit:linkkit:debug - DEBUG - post_message :'on_publish'
      2021-05-07 16:06:23,806-30364-27344 - linkkit:linkkit:debug - DEBUG - post_message success
      2021-05-07 16:06:23,806-30364-11596 - linkkit:linkkit:debug - DEBUG - thread runnable pop cmd:'on_publish'
      2021-05-07 16:06:23,808-30364-11596 - linkkit:linkkit:debug - DEBUG - __on_internal_publish message:3
      on_publish_topic mid:3
  • You can log on to the IoT Platform console to view the device status and operation logs.

    • In the left-side navigation pane, choose Devices > Devices. Then, find the device and view the status. If the value in the State/Enabled column is Online, the device is connected to IoT Platform.

    • In the left-side navigation pane, choose Maintenance > Device Log. Select the LightSwitch product to view the logs of the device that are generated when the device goes online, subscribes to the topic, and submits data to IoT Platform.

      Note

      You can ignore the log data of the /sys/a18wP******/LightSwitch/thing/deviceinfo/update_reply topic. By default, this topic is subscribed when you configure the SDK.

If an error occurs during debugging, fix the error as prompted. For more information, see Error codes for devices.

What to do next

After the device is connected to IoT Platform, you can manage and monitor the device. For more information about the features of IoT Platform, see Features.

For more information about how to configure advanced features by using Link SDK for Python, see Project configurations.