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

Prerequisites

The ID of the consumer group that has subscribed to the messages of a topic is obtained.

Prepare the development environment

In this example, Python 2.7 is used.

Download the SDK

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 install Proton, 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 Connect an AMQP client to IoT Platform. 
        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 Connect an AMQP client to IoT Platform. 
        userName = clientId + "|authMode=aksign" + ",signMethod=" + signMethod \
                        + ",timestamp=" + timestamp + ",authId=" + accessKey \
                        + ",iotInstanceId=" + iotInstanceId + ",consumerGroupId=" + consumerGroupId + "|"
        signContent = "authId=" + accessKey + "&timestamp=" + timestamp
        # The structure of the signature and password parameters. For more information, see Connect an AMQP client to IoT Platform. 
        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)

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

    # If 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")

    # If 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 configure 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 Description
url amqps://198426864******.iot-amqp.cn-shanghai.aliyuncs.com:5671 The endpoint that the AMQP client uses to connect to IoT Platform. Format: "amqps://${YourHost}:5671".

For more information about the endpoints that you can specify for the ${YourHost} variable, see View the endpoint of an instance.

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 RAM user. This policy allows the RAM 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.

To view the ID of the consumer group, perform the following steps: Log on to the IoT Platform console and click the card of the instance that you want to manange. Choose Rules Engine > Server-side Subscription > Consumer Groups. The ID is displayed on the Consumer Groups tab.

iotInstanceId "" The ID of the instance. You can view the ID of the instance on the Overview page in the IoT Platform console.
  • If you have an ID value, you must specify the ID for this parameter.
  • If no Overview or ID is generated for your instance, specify an empty string (iotInstanceId = "") for the parameter.
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 and click the card of the instance that you want to manage. Choose Rules Engine > Server-side Subscription > Consumer Groups. Find the consumer group that you want to manage and click View in the Actions column. The ID of each client is displayed on the Consumer Group Details page. You can use client IDs to efficiently identify clients.

Sample results

  • If the output that is similar to the following log information appears, the AMQP client is connected to IoT Platform and can receive messages. Success
    Parameter Example Description
    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.
  • If the output that is similar to the following log information appears, the AMQP client fails to connect to IoT Platform.

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

    Failed

References

For more information about the error codes that are related to server-side subscription, see Error codes that are related to messages.