Python Link SDK

Updated at:

This topic uses a night light switch example to show how to use the Python Link SDK to simulate a device that connects to IoT Platform over MQTT and publishes data using a custom topic.

Prerequisites

The IoT Platform service has been activated.

Note

You are not charged for activating IoT Platform. You can try the service for free. For more information, see Alibaba Cloud Free Tier for IoT Platform. For information about billing, see Billing overview.

Create a product and a device

  1. Log on to the IoT Platform console and click the card for the target instance.

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

  3. On the Create Product page, enter `Night Light Switch` for Product Name. Select Custom Category for Category. Use the default values for other parameters and click Confirm.

    创建产品

  4. On the page that appears, in the Add Device section, click Add.

  5. On the Devices page, click Add Device.

  6. In the Add Device dialog box, enter a device name, such as `LightSwitch`. Then, click Confirm.

    添加设备

  7. In the Added dialog box, click Copy Device Certificate. Save the device certificate information to your computer for later use. For more information about device certificates, see Device certificates.

Prepare the development environment

This example requires Python 3.6 and the pip 3.6 package installer. For more information about the environment, see Environment requirements and configuration.

  1. Install a Python development environment.

    For more information, see Python.

  2. Optional: Install pip, the package manager for Python.

    For more information, see pip.

  3. Install the required dependencies using one of the following methods.

    • If you have pip installed:

      Run the following commands in any directory.

      pip install aliyun-iot-linkkit
      pip install paho-mqtt==1.6.1
    • If you do not have pip installed:

      Manually download the following open source libraries, extract them to a local directory, then run the python setup.py install command in each extracted directory.

Configure the device-side SDK

  1. Download the demo file to your development environment and extract it.

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

    • Configure the device credentials required to connect your device to IoT Platform.

      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 where the device connects to IoT Platform. For more information, see Regions and zones.

      product_key

      a18wP******

      The device credentials. These are the values from the device certificate that you saved locally when you added the device.

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

      device_name

      LightSwitch

      device_secret

      uwMTmVAMnGGHaAkqmeDY6cHxxB******

      endpoint

      iot-cn-6ja******.mqtt.iothub.aliyuncs.com

      The device connection endpoint.

      On the Instance Details page of the IoT Platform console, click View Development Configurations to obtain the device endpoint.

      For more information, see View instance endpoints.

    • Configure the topic that the device subscribes to for receiving messages from IoT Platform.

              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 that the device has permission to subscribe to. The device uses this topic to receive messages from IoT Platform.

      You can specify lk.to_full_topic("user/get") or /a18wP******/LightSwitch/user/get.

      lk.to_full_topic("user/get") is a function that automatically generates a full topic name. It uses the ProductKey and DeviceName that you configured earlier to return a string that is equivalent to /a18wP******/LightSwitch/user/get.

    • Configure the topic for publishing messages and specify the message content, for example, /a18wP******/LightSwitch/user/update.

              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 content.

      • user/update in the example is the topic suffix. You can change this value to publish messages to a different topic. The device must have permission to publish to the topic.

        On the Product Details page in the IoT Platform console, you can view your custom topics on the Custom Topic tab in the Topic Categories section. For more information, see What is a topic?.

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

        • a18wP****** is the ProductKey of the device.

        • LightSwitch is the DeviceName of the device.

      • {\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}} is the message content to be published to IoT Platform.

        This example uses a custom topic, so you can define a custom message format.

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

Results

  • In the directory that contains the demo executable file, run the following command.

    python mqtt_quick_start.py
    • After the demo starts successfully, the following logs appear in your console, indicating a successful connection 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 running demo, enter 3 to have the simulated device LightSwitch subscribe to the topic /a18wP******/LightSwitch/user/get.

      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 the device subscribes to the topic, you can go back to the IoT Platform console. On the Topic List 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, for example, This is a test message from Alibaba IoT Platform., to simulate sending a message from IoT Platform to the device.

    • In the running demo, enter 5 to have the simulated device LightSwitch publish a message to IoT Platform over the topic /a18wP******/LightSwitch/user/update.

      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 view the device status and operational logs in the IoT Platform console.

    • In the left-side navigation pane, choose Device Management > Devices. Find your device and check its status. If the status is Online, the device is connected to IoT Platform.

    • In the left-side navigation pane, choose Maintenance>Device Log. Select the Night Light Switch product to view logs for device connections, topic subscriptions, and message publications.

      Note

      You can ignore the logs about subscribing to the topic /sys/a18wP******/LightSwitch/thing/deviceinfo/update_reply. This subscription is a default feature of the SDK and does not affect this quickstart.

If an error occurs during debugging, refer to Error codes for devices and follow the instructions to resolve the issue.

Next steps

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

To configure advanced features using the Python Link SDK, see Python Link SDK overview.