このページは、お客様の言語ではご利用いただけません。Huawei Cloudは、より多くの言語バージョンを追加するために懸命に取り組んでいます。ご協力ありがとうございました。

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Python Demo Usage Guide

Updated on 2024-12-31 GMT+08:00

Overview

This topic uses Python as an example to describe how to connect a device to the platform over MQTTS or MQTT and how to use platform APIs to report properties and subscribe to a topic for receiving commands.

NOTE:

The code snippets in this document are only examples and are for trial use only. To put them into commercial use, obtain the IoT Device SDKs of the corresponding language for integration by referring to Obtaining Resources.

Prerequisites

Preparations

  • Installing Python
    1. Go to the Python website to download and install a desired version. (The following uses Windows OS as an example to describe how to install Python 3.8.2.)

    2. After the download is complete, run the .exe file to install Python.
    3. Select Add python 3.8 to PATH (if it is not selected, you need to manually configure environment variables), click Customize installation, and install Python as prompted.

    4. Check whether Python is installed.

      Press Win+R, enter cmd, and press Enter to open the CLI. In the CLI, enter python –V and press Enter. If the Python version is displayed, the installation is successful.

  • Installing PyCharm (If you have already installed PyCharm, skip this step.)
    1. Visit the PyCharm website, select a version, and click Download.

      The professional edition is recommended.

    2. Run the .exe file and install PyCharm as prompted.

Importing Sample Code

  1. Download the QuickStart (Python).
  2. Run PyCharm, click Open, and select the sample code downloaded.

  3. Import the sample code.

    Description of the directories:

    • IoT_device_demo: MQTT demo files

      message_sample.py: Demo for devices to send and receive messages

      command_sample.py: Demo for devices to respond to commands delivered by the platform

      properties_sample.py: Demo for devices to report properties

    • IoT_device/client: Used for paho-mqtt encapsulation.

      IoT_client_config.py: client configurations, such as the device ID and secret

      IoT_client.py: MQTT-related function configurations, such as connection, subscription, publish, and response

    • IoT_device/Utils: utility methods, such as those for obtaining the timestamp and encrypting a secret
    • IoT_device/resources: Stores certificates.

      DigiCertGlobalRootCA.crt.pem is used by the device to verify the platform identity when the device connects to the platform. You can download the certificate file using the link provided in Certificates.

    • IoT_device/request: Encapsulates device properties, such as commands, messages, and properties.

  4. (Optional) Install the paho-mqtt library, which is a third-party library that uses the MQTT protocol in Python. If the paho-mqtt library has already been installed, skip this step. You can install paho-mqtt using either of the following methods:

    • Method 1: Use the pip tool to install paho-mqtt in the CLI. (The tool is already provided when installing Python.)

      In the CLI, enter pip install paho-mqtt and press Enter. If the message Successfully installed paho-mqtt is displayed, the installation is successful. If a message is displayed indicating that the pip command is not an internal or external command, check the Python environment variables. See the figure below.

    • Method 2: Install paho-mqtt using PyCharm.
      1. Open PyCharm, choose File > Settings > Project Interpreter, and click the plus icon (+) on the right side to search for paho-mqtt.

      2. Click Install Package in the lower left corner.

Establishing a Connection

To connect a device or gateway to the platform, upload the device information to bind the device or gateway to the platform.

  1. Before establishing a connection, modify the following parameters. The IoTClientConfig class is used to configure client information.
    1
    2
    3
    4
    # Client configurations
    client_cfg = IoTClientConfig(server_ip='iot-mqtts.cn-north-4.myhuaweicloud.com', device_id='5e85a55f60b7b804c51ce15c_py123', secret='******', is_ssl=True)
    # Create a device.
    iot_client = IotClient(client_cfg)
    
    • server_ip indicates the device connection address of the platform. To obtain this address, see Platform Connection Information. (After obtaining the domain name, run the ping Domain name command in the CLI to obtain the corresponding IP address.)
    • device_id and secret are returned after the device is registered.
    • is_ssl: True means to establish an MQTTS connection and False means to establish an MQTT connection.
  2. Call the connect method to initiate a connection.
    iot_client.connect()

    If the connection is successful, the following information is displayed:

     -----------------Connection successful !!!

    If the connection fails, the retreat_reconnection function executes backoff reconnection. The example code is as follows:

    # Backoff reconnection
    def retreat_reconnection(self):
    	print("---- Backoff reconnection")
    	global retryTimes
    	minBackoff = 1
    	maxBackoff = 30
    	defaultBackoff = 1
    	low_bound = (int)(defaultBackoff * 0.8)
    	high_bound = (int)(defaultBackoff * 1.2)
    	random_backoff = random.randint(0, high_bound - low_bound)
    	backoff_with_jitter = math.pow(2.0, retryTimes) * (random_backoff + low_bound)
    	wait_time_until_next_retry = min(minBackoff + backoff_with_jitter, maxBackoff)
    	print("the next retry time is ", wait_time_until_next_retry, " seconds")
    	retryTimes += 1
    	time.sleep(wait_time_until_next_retry)
    	self.connect()
    

Subscribing to a Topic

Only devices that subscribe to a specific topic can receive messages about the topic published by the broker. For details on the preset topics, see Topics.

The message_sample.py file provides functions such as subscribing to topics, unsubscribing from topics, and reporting device messages.

To subscribe to a topic for receiving commands, do as follows:

1
 iot_client.subscribe(r'$oc/devices/' + str(self.__device_id) + r'/sys/commands/#')

If the subscription is successful, information similar to the following is displayed. (topic indicates a custom topic, for example, Topic_1.)

 ------You have subscribed:  topic

Responding to a Command

The command_sample.py file provides the function of responding to commands delivered by the platform. For details about the API, see Platform Delivering a Command.

1
2
3
4
5
# Responding to commands delivered by the platform
def command_callback(request_id, command):
    # If the value of result_code is 0, the command is delivered . If the value is 1, the command fails to be delivered.
    iot_client.respond_command(request_id, result_code=0)
iot_client.set_command_callback(command_callback)

Reporting Properties

Devices can report their properties to the platform. For details about the API, see Device Reporting Properties.

The properties_sample.py file provides the functions of reporting device properties, responding to platform settings, and querying device properties.

In the following code, the device reports properties to the platform every 10 seconds. service_property indicates a device property object. For details, see the services_properties.py file.

1
2
3
4
5
6
7
# Reporting properties periodically
while True:
    # Set properties based on the product model.
    service_property = ServicesProperties()
    service_property.add_service_property(service_id="Battery", property='batteryLevel', value=1)
    iot_client.report_properties(service_properties=service_property.service_property, qos=1)
    time.sleep(10) 

If the reporting is successful, the reported device properties are displayed on the device details page.

Figure 1 Viewing reported data - Battery_batteryLevel
NOTE:

If no latest data is displayed on the device details page, modify the services and properties in the product model to ensure that the reported services and properties are the same as those defined in the product model. Alternatively, go to the product details page and delete all services.

Reporting a Message

Message reporting is the process in which a device reports messages to the platform. The message_sample.py file provides the message reporting function.

1
2
# Sending a message to the platform using the default topic
iot_client.publish_message('raw message: Hello Huawei cloud IoT')

If the message is reported, the following information is displayed:

 Publish success---mid = 1
NOTE:

Synchronous commands require device responses. For details, see Upstream Response Parameters.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback