All Products
Search
Document Center

IoT Platform:Connect a client to IoT Platform by using the SDK for Python 2.7

Last Updated:Oct 22, 2023

This topic describes how to use the SDK for Python 2.7 to connect an Advanced Message Queuing Protocol (AMQP) client to Alibaba Cloud IoT Platform and receive messages from IoT Platform by using the server-side subscription feature.

Prerequisites

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

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, visit Qpid Proton 0.29.0.

Install Qpid Proton. For more information, see Installing Qpid Proton.

After you install Qpid 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
import os

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"
        # If you hard-code the AccessKey pair in the project code, the AccessKey pair may be disclosed if the project code is leaked. In this case, the resources within your account become insecure. The following sample code provides an example on how to obtain the AccessKey pair from environment variables. This example is for reference only.
        accessKey = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        accessSecret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        consumerGroupId = "${YourConsumerGroupId}"
        clientId = "${YourClientId}"
        # iotInstanceId: The ID of the IoT Platform 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 construct the password, 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)

    # 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 closed, the following function is called: 
    def on_connection_closed(self, event):
        logger.info("Connection closed: %s", self)

    # If the remote server closes 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 description in the following table. For more information about other parameters, see Connect an AMQP client to IoT Platform.

Important

Make sure that you specify valid parameter values. Otherwise, the AMQP client fails to connect to IoT Platform.

Parameter

Description

url

The endpoint that the AMQP client uses to connect to IoT Platform. Format: "amqps://${YourHost}:5671".

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

accessKey

Log on to the IoT Platform console, move the pointer over the profile picture in the upper-right corner, and then click AccessKey Management to obtain the AccessKey ID and AccessKey secret.

Note

If you use a Resource Access Management (RAM) user, you must attach the AliyunIOTFullAccess policy to the RAM user. This policy allows the RAM user to manage IoT Platform resources. Otherwise, the connection to IoT Platform fails. For more information, see Access IoT Platform as a RAM user.

accessSecret

consumerGroupId

The ID of the consumer group of the IoT Platform instance.

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 manage. In the left-side navigation pane, choose Message Forwarding > Server-side Subscription. The ID of the consumer group is displayed on the Consumer Groups tab.

iotInstanceId

The ID of the IoT Platform instance. You can view the instance ID on the Overview tab in the IoT Platform console.

  • If the instance ID is displayed, you must set this parameter to the instance ID.

  • If the Overview tab is not displayed or your instance does not have an ID, leave this parameter empty in the format of iotInstanceId = "".

clientId

The ID of the client. You must specify a custom ID. The ID must be 1 to 64 characters in length. We recommend that you use a unique identifier as the client ID, such as the UUID, MAC address, or IP address of the server on which the client runs.

After the AMQP client is connected to IoT Platform and started, perform the following steps to view the details of the client: Log on to the IoT Platform console and click the card of the instance that you want to manage. In the left-side navigation pane, choose Message Forwarding > Server-side Subscription. On the Consumer Groups tab, 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 Status tab. You can use client IDs to identify clients with ease.

Sample results

  • If information similar to the following output is displayed, the AMQP client is connected to IoT Platform and can receive messages.成功

    Parameter

    Example

    Description

    message_id

    2**************7

    The ID of the message.

    topic

    /***********/******/thing/event/property/post

    The topic that is used to submit device properties.

    content

    {"deviceType":"CustomCategory","iotId":"qPi***","requestId":"161***","checkFailedData":{},"productKey":"g4***","gmtCreate":1613635594038,"deviceName":"de***","items":{"Temperature":{"value":24,"time":1613635594036},"Humidity":{"value":26,"time":1613635594036}}}

    The content of the message.

  • If information similar to the following output is displayed, the AMQP client fails to connect to IoT Platform.

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

    失败

References

For more information about the error codes that are related to the server-side subscription feature, see the Error codes that are related to messages section of the "IoT Platform logs" topic.