All Products
Search
Document Center

IoT Platform:Use the Paho MQTT library for Python to connect a device to IoT Platform

Last Updated:Feb 19, 2024

This topic describes how to use the Paho MQTT library for Python to connect a device to IoT Platform and enable messaging.

Prerequisites

A product and a device are created in an instance in the IoT Platform console. The device certificate and an MQTT endpoint are obtained. The device certificate information includes the ProductKey, DeviceName, and DeviceSecret. For more information, see the following topics:

Prepare a development environment

We recommend that you use Python 3.6.

  • Linux

    Run the following commands to install Python:

    Important

    In this topic, the permissions of a common user are used to perform all operations. If you want to perform specific operations that require administrator permissions, run the sudo command.

    sudo add-apt-repository ppa:deadsnakes/ppa 
    sudo apt-get update 
    sudo apt-get install python3.6 
    wget https://bootstrap.pypa.io/get-pip.py 
    sudo python3.6 get-pip.py 
    python3.6 -m pip install --upgrade pip setuptools wheel 
    sudo apt-get install python3.6-venv
  • Windows

    Install one of the following packages based on your operating system:

  • macOS

    Download the python-3.6.7-macosx10.9.pkg package.

Download the Paho MQTT library for Python

For more information about the Paho project and the supported programming languages, see Eclipse Paho Downloads.

Run the following command to install the Paho MQTT library for Python. For more information, see Paho-MQTT.

pip install paho-mqtt==1.6.1
Important

This Demo does not support the Paho MQTT library of Version 2.0.0.

Connect a device to IoT Platform

  • The MqttSign.py file defines a function that is called to obtain the MQTT connection parameters. You must call the function to connect your device to IoT Platform.

    Functions:

    • This function is used to obtain the following MQTT connection parameters: username, password, and mqttClientId.

    • Input parameters:

      Parameter

      Type

      Description

      productKey

      String

      The ProductKey of the product to which the device belongs. This parameter is used to identify the device in IoT Platform.

      deviceName

      String

      The DeviceName of the device. This parameter is used to identify the device in IoT Platform.

      deviceSecret

      String

      The DeviceSecret of the device. This parameter is used to identify the device in IoT Platform.

      clientId

      String

      The ClientID of the device. To efficiently identify a device, we recommend that you use the MAC address or serial number (SN) of the device as a ClientID.

      timeStamp

      String

      The timestamp that indicates the current time in milliseconds. This parameter is optional.

    • Output parameters:

      Parameter

      Type

      Description

      mqttUsername

      String

      The username that is used to establish the MQTT connection.

      mqttPassword

      String

      The password that is used to establish the MQTT connection.

      mqttClientId

      String

      The ID of the MQTT client.

  1. Add a program file that can connect a device to IoT Platform.

    To obtain MQTT connection parameters, you must write a program to call the function in the MqttSign.py file.

    This section provides the development instructions and sample code.

    • Specify the device information.

      # set the device info, include product key, device name, and device secret
      productKey = "a1LhUsK***"
      deviceName = "python***"
      deviceSecret = "bdd043d193782d11***"
      
      # set timestamp, clientid, subscribe topic and publish topic
      timeStamp = str((int(round(time.time() * 1000))))
      clientId = "192.168.****"
      subTopic = "/" + productKey + "/" + deviceName + "/user/get"
      pubTopic = "/" + productKey + "/" + deviceName + "/user/update"
    • Specify the MQTT connection information.

      Call the calculate_sign_time function in the MqttSign.py file. This function returns the mqttUsername, mqttPassword, and mqttClientId parameters based on the values of the following input parameters: deviceSecret, timeStamp, clientId, productKey, and deviceName.

      In this example, a Transport Layer Security (TLS)-based TCP connection is established. You must download a root certificate to configure the connection parameters.

      # set host, port
      host = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com"
      # instanceId = "***"
      # host = instanceId + ".mqtt.iothub.aliyuncs.com"
      port = 1883
      
      # set tls crt, keepalive
      tls_crt = "root.crt"
      keepAlive = 300
      
      # calculate the login auth info, and set it into the connection options
      m = AuthIfo()
      m.calculate_sign_time(productKey, deviceName, deviceSecret, clientId, timeStamp)
      client = mqtt.Client(m.mqttClientId)
      client.username_pw_set(username=m.mqttUsername, password=m.mqttPassword)
      client.tls_set(tls_crt)
      Note
      • If you use a public instance of the old version, replace cn-shanghai in host = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" with the ID of the region where the device resides. For more information about the formats of region IDs, see Supported regions.

      • If you use a public instance of the new version or an Enterprise Edition instance, replace instanceId in host = instanceId + ".mqtt.iothub.aliyuncs.com" with the ID of the instance.

        To obtain the MQTT endpoint, perform the following steps: Log on to the IoT Platform console. On the Overview page, click the card of the instance that you want to manage. The MQTT endpoint is displayed on the Instance Details page. For more information, see View the endpoint of an instance.

        For more information about IoT Platform instances, see Overview.

    • Call the Connect() function to connect the device to IoT Platform.

      def on_connect(client, userdata, flags, rc):
          if rc == 0:
              print("connect success!")
          else:
              print("connect failed...  error code is:" + str(rc))
      
      def connect_mqtt():
          client.on_connect = on_connect
          client.connect(host, port, keepAlive)
          return client
    • Call the Publish() function to publish messages. You must specify a topic to which messages are published and the payloads of the messages.

      def publish_message():
          # publish 5 messages to pubTopic("/a1LhUsK****/python***/user/update")
          for i in range(5):
              message = "ABC" + str(i)
              client.publish(pubTopic, message)
              print("publish msg:" + str(i))
              time.sleep(2)

      For more information about topics, see What is a topic?

    • Call the Subscribe() function to subscribe to the topic and receive messages from IoT Platform.

      def subscribe_topic():
          # subscribe to subTopic("/a1LhUsK****/python***/user/get") and request messages to be delivered
          client.subscribe(subTopic)

      For more information about the communication methods among devices, servers, and IoT Platform, see Overview.

  2. Run the project.

Sample code

Run the sample code-compiled program to connect the device to IoT Platform.

  1. Download the package that includes the sample code from the link and decompress the package to the aiot-python-demo directory. The following table describes the files that are included in the directory.

    Certificate file

    Description

    MqttSign.py

    This file contains the code that is used to obtain the connection parameters that are required to connect a device to IoT Platform over MQTT. When you run the file, the calculate_sign_time function is called to obtain the values of the mqttUsername, mqttPassword, and mqttClientId parameters.

    iot.py

    This file contains the logic code that is used to connect a device to IoT Platform and enable communication.

    root.crt

    The root certificate of IoT Platform. This certificate is required to connect devices to IoT Platform.

  2. In the iot.py file, replace the device information with your device information.

    • Replace the values of the productKey, deviceName, and deviceSecret parameters with your device certificate information.

      # set the device info, include product key, device name, and device secret
      productKey = "a1LhUsK***"
      deviceName = "python***"
      deviceSecret = "bdd043d193782d11***"
    • Optional. Replace the values of the timeStamp and clientId parameters. You can replace the value of the clientId parameter with the MAC address or SN of your device.

      Note

      If you do not replace the values, you can still connect the device to IoT Platform. In actual scenarios, we recommend that you replace the values of the parameters with actual values.

    • Replace .iot-as-mqtt.cn-shanghai.aliyuncs.com in host = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" with the actual MQTT endpoint.

      For more information, see Step 2 in the "Connect a device to IoT Platform" section of this topic.

  3. Run the iot.py file.

    After you run the file, the following local logs are generated:

    Connect aliyun IoT Cloud Sucess
    subscribe topic: /a1LhUsK***/python***/user/get
    publish msg: 0
    publish msg: ABC0
    publish msg: 1
    publish msg: ABC1
    publish msg: 2
    publish msg: ABC2
    publish msg: 3
    publish msg: ABC3
    publish msg: 4
    publish msg: ABC4

    Log on to the IoT Platform console. You can view the status and logs of the device on the instance.

    • Choose Devices > Devices. The Devices page shows that the device is in Online state.

    • Choose Maintenance > Device Log. Then, click the Cloud run log or Device local log tab to view logs. For more information, see IoT Platform logs and Local device logs.

Error codes

If a device fails to be connected to IoT Platform over MQTT, you can troubleshoot the issue based on the error code. For more information, see Troubleshooting.