Paho-MQTT Python example

Updated at:

Use the Paho MQTT library for Python to connect a device to Alibaba Cloud IoT Platform and exchange messages.

Prerequisites

In the IoT Platform console , for the corresponding instance, create a product and a device, and obtain the MQTT access domain name and the device certificate information (ProductKey, DeviceName, and DeviceSecret). For more information, see:

Prepare the development environment

Python 3.6 is recommended.

  • Linux

    Install Python 3.6:

    Important

    Commands run as a regular user. Use `sudo` for operations that require administrative permission.

    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 operating system

    Select the installer for your system:

  • macOS

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

Download the Paho MQTT library for Python

The Eclipse Paho Downloads page lists the Paho project and supported development languages.

Install the Paho-MQTT library for Python:

pip install paho-mqtt==1.6.1
Important

This demo does not support Paho MQTT library version 2.0.0.

Connect to IoT Platform

  • Define a function in MqttSign.py to calculate the MQTT connection parameters. Your device program calls this function.

    Function details:

    • Calculates the MQTT connection parameters mqttUsername, mqttPassword, and mqttClientId.

    • Input parameters:

      Parameter

      Type

      Description

      productKey

      String

      The ProductKey of the product to which the device belongs. Part of the device certificate.

      deviceName

      String

      The device name. Part of the device certificate.

      deviceSecret

      String

      The device secret. Part of the device certificate.

      clientId

      String

      A custom client ID, up to 64 characters. Use the MAC address or SN of your device.

      timeStamp

      String

      The current timestamp in milliseconds. This parameter is optional.

    • Output MQTT connection parameters:

      Parameter

      Type

      Description

      mqttUsername

      String

      The username required for the MQTT connection.

      mqttPassword

      String

      The password required for the MQTT connection.

      mqttClientId

      String

      The MQTT client ID.

  1. Add a program file to connect the device to IoT Platform.

    Write a program that calls MqttSign.py to calculate the MQTT connection parameters and connect the device to IoT Platform.

    Development instructions and code examples:

    • Set 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"
    • Set the MQTT connection information.

      Call calculate_sign_time in MqttSign.py to calculate mqttUsername, mqttPassword, and mqttClientId from clientId, productKey, deviceName, deviceSecret, and timeStamp.

      This example uses TLS direct connection. download the root certificate for TLS configuration.

      # 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
      • For earlier-version public instances, replace the region code (cn-shanghai) in host = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" with the region of your device. Supported regions.

      • For new-version public instances and Enterprise instances, specify the instance ID in host = instanceId + ".mqtt.iothub.aliyuncs.com".

        In the IoT Platform console, go to Instance Overview > your instance > Instance Details to obtain the MQTT endpoint. View instance endpoints.

        Instance overview.

    • Call connect() 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
    • Publish messages to the destination topic.

      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)

      What is a topic?

    • Subscribe to a topic to receive messages from IoT Platform.

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

      Communication methods.

  2. Run the project.

Sample code

Use the sample code to connect the device to IoT Platform.

  1. Download and extract aiot-python-demo.zip. The package contains the following files:

    File

    Description

    MqttSign.py

    Calculates MQTT connection parameters (mqttUsername, mqttPassword, and mqttClientId) through the calculate_sign_time function.

    iot.py

    Handles device connection and communication with IoT Platform.

    root.crt

    Root certificate required for TLS connections to IoT Platform.

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

    • Replace productKey, deviceName, and deviceSecret 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 timeStamp and clientId. Use your device SN or MAC address as the clientId.

      Note

      The device can connect without replacing these values, but production environments require actual device information.

    • Set host to the correct endpoint.

      Step 2 in Connect to IoT Platform describes how to configure the endpoint.

  3. Run the iot.py program file.

    On success, the local logs show:

    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

    In the IoT Platform console, view the device status and logs in your instance.

    • In the left-side navigation pane, choose Device Management > Devices. You can see that the device status is Online.

    • Choose Monitoring & O&M > Log Service. You can view IoT Platform logs and on-premises device logs. For more information, see IoT Platform logs and On-premises device logs.

Error codes

If the device fails to connect over MQTT, check the error code against Troubleshooting.