This article describes how to use the SDK for Python 2.7 to connect a client with IoT Platform and receive messages from IoT Platform.

Development environment

Python 2.7 is used in this example.

Download the SDK for Python

We recommend that you use the Apache Qpid Proton 0.29.0 library. This library encapsulates the Python API. To download the library and view the instructions, see Qpid Proton 0.29.0.

Install Proton. For more information about how to install Proton, see Installing Qpid Proton.

After you complete the installation, run the following Python command to check whether the SSL library is available:

import proton;print('%s' % 'SSL present' if proton.SSL.present() else 'SSL NOT AVAILABLE')

Sample code

# encoding=utf-8
import sys
import logging
import time
from proton.handlers import MessagingHandler
from proton.reactor import Container
import hashlib
import hmac
import base64

reload(sys)
sys.setdefaultencoding('utf-8')
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
console_handler = logging.StreamHandler(sys.stdout)


def current_time_millis():
    return str(int(round(time.time() * 1000)))


def do_sign(secret, sign_content):
    m = hmac.new(secret, sign_content, digestmod=hashlib.sha1)
    return base64.b64encode(m.digest())


class AmqpClient(MessagingHandler):
    def __init__(self):
        super(AmqpClient, self).__init__()

    def on_start(self, event):
        # The endpoint. For more information, see the "Connect an AMQP client to IoT Platform" topic. 
        url = "amqps://${YourHost}:5671"
        accessKey = "${YourAccessKeyID}"
        accessSecret = "${YourAccessKeySecret}"
        consumerGroupId = "${YourConsumerGroupId}"
        clientId = "${YourClientId}"
         # iotInstanceId: the ID of the instance. 
        iotInstanceId = "${YourIotInstanceId}"
         # The signature algorithm. Valid values: hmacmd5, hmacsha1, and hmacsha256. 
        signMethod = "hmacsha1"
        timestamp = current_time_millis()
        # The structure of the userName parameter. For more information, see the "Connect an AMQP client to IoT Platform" topic. 
        userName = clientId + "|authMode=aksign" + ",signMethod=" + signMethod \
                        + ",timestamp=" + timestamp + ",authId=" + accessKey \
                        + ",iotInstanceId=" + iotInstanceId + ",consumerGroupId=" + consumerGroupId + "|"
        signContent = "authId=" + accessKey + "&timestamp=" + timestamp
        # Calculate a signature. For more information about how to specify the password parameter, see the "Connect an AMQP client to IoT Platform" topic. 
        passWord = do_sign(accessSecret.encode("utf-8"), signContent.encode("utf-8"))
        conn = event.container.connect(url, user=userName, password=passWord, heartbeat=60)
        self.receiver = event.container.create_receiver(conn)

    # When the connection is established, the following function is called: 
    def on_connection_opened(self, event):
        logger.info("Connection established, remoteUrl: %s", event.connection.hostname)

    # When the connection is ended, the following function is called: 
    def on_connection_closed(self, event):
        logger.info("Connection closed: %s", self)

    #  If the remote server ends the connection due to an error, the following function is called: 
    def on_connection_error(self, event):
        logger.info("Connection error")

    # If an AMQP connection error occurs, such as an authentication error or a socket error, the following function is called: 
    def on_transport_error(self, event):
        if event.transport.condition:
            if event.transport.condition.info:
                logger.error("%s: %s: %s" % (
                    event.transport.condition.name, event.transport.condition.description,
                    event.transport.condition.info))
            else:
                logger.error("%s: %s" % (event.transport.condition.name, event.transport.condition.description))
        else:
            logging.error("Unspecified transport error")

    # When a message is received, the following function is called: 
    def on_message(self, event):
        message = event.message
        content = message.body.decode('utf-8')
        topic = message.properties.get("topic")
        message_id = message.properties.get("messageId")
        print("receive message: message_id=%s, topic=%s, content=%s" % (message_id, topic, content))
        event.receiver.flow(1)


Container(AmqpClient()).run()

You can specify the parameters in the preceding code based on the parameter descriptions in the following table. For more information, see Connect an AMQP client to IoT Platform.

Parameter Example Descripition
url amqps://iot-***.amqp.iothub.aliyuncs.com:5671 The endpoint that the AMQP client uses to connect with IoT Platform. Format: "amqps://${YourHost}:5671".

${YourHost} format: ${uid}.iot-amqp.${YourRegionId}.aliyuncs.com.

  • ${uid}: Replace this variable with the ID of your Alibaba Cloud account. You can log on to the IoT Platform console, and move the pointer over the profile picture to view the account ID.
  • ${YourRegionId}: Replace this variable with the ID of the region where your IoT Platform device resides. For more information about region IDs, see Regions and zones.
accessKey LTAI4GFGQvKuqHJhFa****** Log on to the IoT Platform console, move the pointer over the profile picture, and then click AccessKey Management to obtain the AccessKey ID and AccessKey secret.
Note If you use a RAM user, you must attach the AliyunIOTFullAccess permission policy to the user. This policy allows the user to manage IoT Platform resources. Otherwise, the connection with IoT Platform fails. For more information about how to authorize a RAM user, see RAM user access.
accessSecret iMS8ZhCDdfJbCMeA005sieKe******
consumerGroupId VWhGZ2QnP7kxWpeSSjt****** The ID of the consumer group.

Log on to the IoT Platform console. Choose Rules > Server-side Subscription > Consumer Groups and view the ID of the required consumer group.

iotInstanceId "" The ID of the instance. In this example, enter an empty string ("").
clientId 12345 The ID of the client. We recommend that you use a unique identifier, such as the UUID, MAC address, or IP address of the client. The client ID must be 1 to 64 characters in length.

Log on to the IoT Platform console. Choose Rules > Server-side Subscription > Consumer Groups, and click View next to the required consumer group. The Consumer Group Details page shows this parameter. This parameter allows you to identify clients.

Sample results

  • After you run the code, the following log data may be returned. The data indicates that the AMQP client is connected to IoT Platform and can receive messages. Success
    Parameter Example Descripition
    message_id 1324198300680719360 The ID of the message.
    topic /***********/******/thing/event/property/post The topic that is used to submit device properties.
    content null The content of the message.
  • After you run the code, the following log data may be returned. The data indicates that the AMQP client is not connected to IoT Platform.

    You can check the code or network environment based on logs, solve the problem, and then run the code again.

    Failure