Skip to content

Commit 161f431

Browse files
author
ccharlesren
committed
添加PythonSDK中hub/explorer相关英文文档
Tapd: http://tapd.oa.com/IntlPortal_DocAndTranslationMgmt/prong/stories/view/1020397132868193241 Change-Id: I57c7e74f6957b738212cb074643976593a386dc7
1 parent d32ea97 commit 161f431

31 files changed

+2608
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
简体中文 | [English](./README_EN-US.md)
2+
13
# 产品介绍
24

35
本仓库中包含两个产品:腾讯云物联网通信(IoT Hub) 和 腾讯云物联网开发平台(IoT Explorer) ,本仓库提供 Python 接入方式 。

README_EN-US.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
[简体中文](https://github.com/tencentyun/iot-device-python) | English
2+
3+
# Product Overview
4+
5+
This repository contains two products: IoT Hub and IoT Explorer. It provides the Python connection method.
6+
7+
## IoT Hub SDK for Python
8+
9+
Tencent Cloud Internet of Things Hub (IoT Hub) aims to provide a secure, stable, and efficient connection platform that helps developers quickly achieve stable, high-concurrency, and omnidirectional data communications among devices, user applications, and cloud services at low costs. It can implement cross-device interaction, device data reporting, and configuration distribution. Further, by opening up the linkage between device data and Tencent Cloud services based on the rule engine, it allows for the storage, real-time computation, and smart processing and analysis of massive amounts of data with speed and ease. For more information, please see [IoT Hub](https://cloud.tencent.com/document/product/634).
10+
11+
This repository provides the IoT Hub device SDK. You can securely connect Python-enabled devices to IoT Hub by integrating the SDK into them.
12+
13+
* [IoT Hub device SDK for Python](hub/)
14+
15+
16+
## IoT Explorer SDK for Python
17+
18+
Tencent Cloud Internet of Things Explorer (IoT Explorer) provides device manufacturers, solution providers, and application developers in various industries with one-stop device automation services. It offers the capabilities to connect and manage high numbers of devices and develop mini programs and is interconnected with the basic products and AI capabilities of Tencent Cloud, which helps improve the device automation efficiency in traditional industries, reduce the development and OPS costs, and empower the business growth. For more information, please see [IoT Explorer](https://cloud.tencent.com/document/product/1081).
19+
20+
This repository provides the IoT Explorer device SDK. You can securely connect Python-enabled devices to IoT Explorer by connecting their drivers or integrating the SDK into them.
21+
22+
* [IoT Explorer device SDK for Python](explorer/)
23+
24+
25+
## Domain names involved in SDKs
26+
27+
For the domain names involved in the corresponding SDKs of the two products, please see [Domain Names Involved in Device SDKs](https://github.com/tencentyun/iot-device-java/wiki/Device-SDK涉及的域名).

explorer/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
简体中文 | [English](doc/en)
2+
13
* [腾讯云物联网开发平台设备端 IoT Explorer Python-SDK](#腾讯云物联网开发平台设备端-IoT-Explorer-Python-SDK)
24
* [前提条件](#前提条件)
35
* [工程配置](#工程配置)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
* [How to Import](#How-to-Import)
2+
3+
## How to Import
4+
5+
**How to import**
6+
7+
- Install from pip
8+
9+
```
10+
pip install tencent-iot-device
11+
```
12+
13+
14+
- Build from source
15+
16+
```
17+
git clone https://github.com/tencentyun/iot-device-python.git
18+
cd iot-device-python
19+
python setup.py install
20+
```
21+
22+
23+
**SDK for Python source code**
24+
25+
- If you want to develop a project through code integration, you can download the SDK for Python source code from [Github](../).
26+
- If you want to develop a project by importing the source code, you can refer to [Latest release](https://github.com/tencentyun/iot-device-python/releases) for the specific version number.
27+
28+
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
* [API Description](#API-Description)
2+
* [MQTT APIs](#MQTT-APIs)
3+
* [Gateway APIs](#Gateway-APIs)
4+
* [Data template APIs](#Data-template-APIs)
5+
* [Dynamic registration APIs](#Dynamic-registration-APIs)
6+
* [OTA APIs](#OTA-APIs)
7+
* [Log APIs](#Log-APIs)
8+
9+
# API Description
10+
## MQTT APIs
11+
12+
| API | Description |
13+
| :-: | :-: |
14+
| connect | Establishes MQTT connection |
15+
| disconnect | Closes MQTT connection |
16+
| subscribe | Subscribes to MQTT |
17+
| unsubscribe | Unsubscribes from MQTT |
18+
| publish | Publishes message over MQTT |
19+
| registerMqttCallback | Registers MQTT callback function |
20+
| registerUserCallback | Registers user callback function |
21+
| isMqttConnected | Checks whether MQTT is normally connected |
22+
| getConnectState | Gets MQTT connection status |
23+
| setReconnectInterval | Sets MQTT reconnection attempt interval |
24+
| setMessageTimout | Sets message sending timeout period |
25+
| setKeepaliveInterval | Sets MQTT keepalive interval |
26+
27+
## Gateway APIs
28+
| API | Description |
29+
| :-: | :-: |
30+
| gatewayInit | Initializes gateway |
31+
| isSubdevStatusOnline | Determines whether subdevice is online |
32+
| updateSubdevStatus | Updates subdevice's online status |
33+
| gatewaySubdevGetConfigList | Gets subdevice list from configuration file |
34+
| gatewaySubdevOnline | Proxies subdevice connection |
35+
| gatewaySubdevOffline | Proxies subdevice disconnection |
36+
| gatewaySubdevBind | Binds subdevice |
37+
| gatewaySubdevUnbind | Unbinds subdevice |
38+
| gatewaySubdevSubscribe | Proxies subdevice subscription |
39+
40+
## Data template APIs
41+
| API | Description |
42+
| :-: | :-: |
43+
| templateInit | Initializes data template |
44+
| getEventsList | Gets device event list |
45+
| getActionList | Gets device action list |
46+
| getPropertyList | Gets device attribute list |
47+
| templateSetup | Parses data template |
48+
| templateEventPost | Reports event |
49+
| templateJsonConstructReportArray | Constructs JSON structure for reporting |
50+
| templateReportSysInfo | Reports device information |
51+
| templateControlReply | Replies to control message |
52+
| templateActionReply | Replies to action message |
53+
| templateGetStatus | Gets latest device status |
54+
| templateReport | Reports device attribute |
55+
| clearControl | Clears control |
56+
| templateDeinit | Terminates data template |
57+
58+
## Dynamic registration APIs
59+
| API | Description |
60+
| :-: | :-: |
61+
| dynregDevice | Gets the dynamic registration information of device |
62+
63+
## OTA APIs
64+
| API | Description |
65+
| :-: | :-: |
66+
| otaInit | Initializes OTA |
67+
| otaIsFetching | Determines whether the download is in progress |
68+
| otaIsFetchFinished | Determines whether the download is completed |
69+
| otaReportUpgradeSuccess | Reports update success message |
70+
| otaReportUpgradeFail | Reports update failure message |
71+
| otaIoctlNumber | Gets the information of the downloaded firmware in `int` type, such as the size |
72+
| otaIoctlString | Gets the information of the downloaded firmware in `String` type, such as MD5 |
73+
| otaResetMd5 | Resets MD5 information |
74+
| otaMd5Update | Updates MD5 information |
75+
| httpInit | Initializes HTTP |
76+
| otaReportVersion | Reports the information of current firmware version |
77+
| otaDownloadStart | Starts firmware download |
78+
| otaFetchYield | Reads firmware |
79+
80+
## Log APIs
81+
| API | Description |
82+
| :-: | :-: |
83+
| logInit | Initializes log |
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
* [Event Reporting and Multi-Event Reporting](#Event-Reporting-and-Multi-Event-Reporting)
2+
* [Publishing to topic for reporting event](#Publishing-to-topic-for-reporting-event)
3+
* [Publishing to topic for reporting multiple events](#Publishing-to-topic-for-reporting-multiple-events)
4+
5+
# Event Reporting and Multi-Event Reporting
6+
7+
This document describes how a device publishes to topics for event reporting and multi-event reporting.
8+
9+
## Publishing to topic for reporting event
10+
11+
Run [TemplateSample.py](../../explorer/sample/template/example_template.py). After the device is connected successfully, it will initialize the data template, call the `templateEventPost()` API for event reporting, and publish to the event topic:
12+
`$thing/up/event/{ProductID}/{DeviceName}`
13+
14+
Below is the sample code:
15+
```python
16+
# Construct QcloudExplorer
17+
qcloud = QcloudExplorer(device_file="explorer/sample/device_info.json", tls=True)
18+
# Initialize the log
19+
logger = qcloud.logInit(qcloud.LoggerLevel.DEBUG, enable=True)
20+
21+
# Register the MQTT callback
22+
qcloud.registerMqttCallback(on_connect, on_disconnect,
23+
on_message, on_publish,
24+
on_subscribe, on_unsubscribe)
25+
# Get the product ID and device name
26+
product_id = qcloud.getProductID()
27+
device_name = qcloud.getDeviceName()
28+
29+
# Connect to MQTT
30+
qcloud.connect()
31+
32+
# Initialize the data template
33+
qcloud.templateInit(product_id, device_name, on_template_property,
34+
on_template_action, on_template_event, on_template_service)
35+
qcloud.templateSetup(product_id, device_name, "sample/template/template_config.json")
36+
37+
# Construct an event
38+
timestamp = int(round(time.time() * 1000))
39+
event = {
40+
"events": [
41+
{
42+
"eventId": "status_report",
43+
"type": "info",
44+
"timestamp": timestamp,
45+
"params": {
46+
"status":0,
47+
"message":"event test"
48+
}
49+
}
50+
]
51+
}
52+
# Report the event
53+
qcloud.templateEventPost(product_id, device_name, event)
54+
55+
# Disconnect from MQTT
56+
qcloud.disconnect()
57+
```
58+
59+
Observe the output log.
60+
```
61+
2021-07-21 16:59:37,208.208 [log.py:35] - DEBUG - [event post] {'events': [{'eventId': 'status_report', 'type': 'info', 'timestamp': 1626857977209, 'params': {'status': 0, 'message': 'event test'}}]}
62+
2021-07-21 16:59:37,209.209 [client.py:2165] - DEBUG - Sending PUBLISH (d0, q1, r0, m5), 'b'$thing/up/event/xxx/dev1'', ... (182 bytes)
63+
2021-07-21 16:59:37,209.209 [log.py:35] - DEBUG - publish success
64+
2021-07-21 16:59:37,261.261 [client.py:2165] - DEBUG - Received PUBACK (Mid: 5)
65+
2021-07-21 16:59:37,262.262 [log.py:35] - DEBUG - on_publish:mid:5,userdata:None
66+
2021-07-21 16:59:37,286.286 [client.py:2165] - DEBUG - Received PUBLISH (d0, q0, r0, m0), '$thing/down/event/xxx/dev1', ... (85 bytes)
67+
2021-07-21 16:59:37,287.287 [log.py:35] - DEBUG - product_1:on_template_event:payload:{'method': 'events_reply', 'clientToken': 'xxx-0', 'code': 0, 'status': '', 'data': {}},userdata:None
68+
```
69+
The above log represents the process in which the device publishes to the topic for reporting a single event successfully. As can be seen, the device publishes an event successfully and receives the `event_reply` from the cloud. In the information of the device created in the console, you can view the corresponding device event. If the `type` passed in is `info`, the event is of the information type. For more information on how to view device events in the console, please see [Device Debugging](https://cloud.tencent.com/document/product/1081/34741).
70+
71+
## Publishing to topic for reporting multiple events
72+
73+
Run [TemplateSample.py](../../explorer/sample/template/example_template.py). After the device is connected successfully, it will initialize the data template, call the `templateEventPost()` API for event reporting, and publish to the event topic:
74+
`$thing/up/event/{ProductID}/{DeviceName}`
75+
76+
Below is the sample code:
77+
```python
78+
# Construct a JSON message
79+
def report_json_construct_events(event_list):
80+
# deal events and add your real value
81+
status = 1
82+
message = "test"
83+
voltage = 20.0
84+
name = "memory"
85+
error_code = 0
86+
timestamp = int(round(time.time() * 1000))
87+
88+
format_string = '"%s":"%s",'
89+
format_int = '"%s":%d,'
90+
events = []
91+
for event in event_list:
92+
string = '{'
93+
string += format_string % ("eventId", event.event_name)
94+
string += format_string % ("type", event.type)
95+
string += format_int % ("timestamp", timestamp)
96+
string += '"params":{'
97+
for prop in event.events_prop:
98+
if (prop.type == "int" or prop.type == "float"
99+
or prop.type == "bool" or prop.type == "enum"):
100+
if prop.key == "status":
101+
string += format_int % (prop.key, status)
102+
elif prop.key == "voltage":
103+
string += format_int % (prop.key, voltage)
104+
elif prop.key == "error_code":
105+
string += format_int % (prop.key, error_code)
106+
elif prop.type == "string":
107+
if prop.key == "message":
108+
string += format_string % (prop.key, message)
109+
elif prop.key == "name":
110+
string += format_string % (prop.key, name)
111+
112+
string = string[:len(string) - 1]
113+
string += "}}"
114+
events.append(json.loads(string))
115+
116+
json_out = '{"events":%s}' % json.dumps(events)
117+
118+
return json.loads(json_out)
119+
120+
# Construct QcloudExplorer
121+
qcloud = QcloudExplorer(device_file="explorer/sample/device_info.json", tls=True)
122+
# Initialize the log
123+
logger = qcloud.logInit(qcloud.LoggerLevel.DEBUG, enable=True)
124+
125+
# Register the MQTT callback
126+
qcloud.registerMqttCallback(on_connect, on_disconnect,
127+
on_message, on_publish,
128+
on_subscribe, on_unsubscribe)
129+
# Get the product ID and device name
130+
product_id = qcloud.getProductID()
131+
device_name = qcloud.getDeviceName()
132+
133+
# Connect to MQTT
134+
qcloud.connect()
135+
136+
# Initialize the data template
137+
qcloud.templateInit(product_id, device_name, on_template_property,
138+
on_template_action, on_template_event, on_template_service)
139+
qcloud.templateSetup(product_id, device_name, "sample/template/template_config.json")
140+
141+
# Get the event list from the configuration file
142+
event_list = qcloud.getEventsList(product_id, device_name)
143+
# Construct a JSON event structure based on the event list
144+
events = report_json_construct_events(event_list)
145+
# Report the event
146+
qcloud.templateEventPost(product_id, device_name, events)
147+
148+
# Disconnect from MQTT
149+
qcloud.disconnect()
150+
```
151+
152+
Observe the output log.
153+
```
154+
2021-07-21 16:48:28,464.464 [log.py:35] - DEBUG - [event post] {'events': [{'eventId': 'status_report', 'type': 'info', 'timestamp': 1626857308464, 'params': {'status': 1, 'message': 'test'}}, {'eventId': 'low_voltage', 'type': 'alert', 'timestamp': 1626857308464, 'params': {'voltage': 20}}, {'eventId': 'hardware_fault', 'type': 'fault', 'timestamp': 1626857308464, 'params': {'name': 'memory', 'error_code': 0}}]}
155+
2021-07-21 16:48:28,464.464 [client.py:2165] - DEBUG - Sending PUBLISH (d0, q1, r0, m5), 'b'$thing/up/event/xxx/dev1'', ... (409 bytes)
156+
2021-07-21 16:48:28,464.464 [log.py:35] - DEBUG - publish success
157+
2021-07-21 16:48:28,508.508 [client.py:2165] - DEBUG - Received PUBACK (Mid: 5)
158+
2021-07-21 16:48:28,508.508 [log.py:35] - DEBUG - on_publish:mid:5,userdata:None
159+
2021-07-21 16:48:28,538.538 [client.py:2165] - DEBUG - Received PUBLISH (d0, q0, r0, m0), '$thing/down/event/xxx/dev1', ... (85 bytes)
160+
2021-07-21 16:48:28,539.539 [log.py:35] - DEBUG - on_template_event:payload:{'method': 'events_reply', 'clientToken': 'xxx-0', 'code': 0, 'status': '', 'data': {}},userdata:None
161+
```
162+
The above log represents the process in which the device publishes to the topic for reporting multiple events successfully. As can be seen, the device publishes events successfully and receives the `events_reply` from the cloud. In the information of the device created in the console, you can view the corresponding device events. If the `type` passed in is `info`, the event is of the information type; if `alert`, the alarm type; if `fault`, the fault type. For more information on how to view device events in the console, please see [Device Debugging](https://cloud.tencent.com/document/product/1081/34741).
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
* [Dynamic Registration Authentication](#Dynamic-Registration-Authentication)
2+
* [Overview](#Overview)
3+
* [Enabling dynamic registration in console](#Enabling-dynamic-registration-in-console)
4+
* [Running demo for dynamic registration](#Running-demo-for-dynamic-registration)
5+
6+
# Dynamic Registration Authentication
7+
## Overview
8+
This feature assigns a unified key to all devices under the same product, and a device gets a device certificate/key through a registration request for authentication. You can burn the same configuration information for the same batch of devices. For more information on the dynamic registration request, please see [Dynamic Registration API Description](https://cloud.tencent.com/document/product/1081/47612).
9+
10+
If you enable automatic device creation in the console, you don't need to create devices in advance, but you must guarantee that device names are unique under the same product ID, which are generally unique device identifiers (such as MAC address). This method is more flexible. If you disable it in the console, you must create devices in advance and enter the same device names during dynamic registration, which is more secure but less convenient.
11+
12+
## Enabling dynamic registration in console
13+
To use the dynamic registration feature, you need to enable it when creating a product in the console and save the `productSecret` information of the product. The settings in the console are as shown below:
14+
![](https://main.qcloudimg.com/raw/a02f57cbe40f26ead94170396d78253c.jpg)
15+
16+
## Running demo for dynamic registration
17+
Before running the demo, you need to enter the product information obtained in the console in the [device_info.json](../../explorer/sample/device_info.json) file, with the device name to be generated in the `deviceName` field, `YOUR_DEVICE_SECRET` in the `deviceSecret` field, and the `productSecret` information generated during product creation in the console in the `productSecret` field.
18+
19+
You can run [DynregSample.py](../../explorer/sample/dynreg/example_dynreg.py) to call the `dynregDevice()` API for dynamic registration authentication. After the dynamic registration callback gets the key or certificate information of the corresponding device, it will be returned through the returned value of the API. Below is the sample code:
20+
21+
```
22+
from explorer.explorer import QcloudExplorer
23+
24+
qcloud = QcloudExplorer(device_file="explorer/sample/device_info.json", tls=True)
25+
logger = qcloud.logInit(qcloud.LoggerLevel.DEBUG, enable=True)
26+
27+
ret, msg = qcloud.dynregDevice()
28+
if ret == 0:
29+
logger.debug('dynamic register success, psk: {}'.format(msg))
30+
else:
31+
logger.error('dynamic register fail, msg: {}'.format(msg))
32+
```
33+
34+
The following is the log of successful authentication for dynamic device registration.
35+
```
36+
dynamic register test success, psk: xxxxxxx
37+
2021-07-15 15:41:24,838.838 [log.py:35] - DEBUG - LoopThread thread enter
38+
2021-07-15 15:41:24,838.838 [log.py:35] - DEBUG - connect_async...8883
39+
2021-07-15 15:41:25,275.275 [client.py:2165] - DEBUG - Sending CONNECT (u1, p1, wr0, wq0, wf0, c1, k60) client_id=b'xxxxx'
40+
2021-07-15 15:41:25,332.332 [client.py:2165] - DEBUG - Received CONNACK (0, 0)
41+
2021-07-15 15:41:25,332.332 [log.py:35] - DEBUG - on_connect:flags:0,rc:0,userdata:None
42+
2021-07-15 15:41:25,840.840 [client.py:2165] - DEBUG - Sending SUBSCRIBE (d0, m1) [(b'$sys/operation/result/xxxx/xxxx', 0)]
43+
2021-07-15 15:41:25,840.840 [log.py:35] - DEBUG - subscribe success topic:$sys/operation/result/xxx/xxx
44+
2021-07-15 15:41:25,840.840 [log.py:35] - DEBUG - pub topic:$sys/operation/xxx/xxx,payload:{'type': 'get', 'resource': ['time']},qos:0
45+
2021-07-15 15:41:25,841.841 [client.py:2165] - DEBUG - Sending PUBLISH (d0, q0, r0, m2), 'b'$sys/operation/xxx/xxx'', ... (37 bytes)
46+
2021-07-15 15:41:25,841.841 [log.py:35] - DEBUG - publish success
47+
2021-07-15 15:41:25,841.841 [log.py:35] - DEBUG - on_publish:mid:2,userdata:None
48+
2021-07-15 15:41:25,893.893 [client.py:2165] - DEBUG - Received SUBACK
49+
2021-07-15 15:41:25,893.893 [log.py:35] - DEBUG - on_subscribe:mid:0,granted_qos:1,userdata:None
50+
2021-07-15 15:41:25,910.910 [client.py:2165] - DEBUG - Received PUBLISH (d0, q0, r0, m0), '$sys/operation/result/xxx/xxx', ... (82 bytes)
51+
2021-07-15 15:41:26,042.042 [log.py:35] - DEBUG - current time:2021-07-15 15:41:25
52+
2021-07-15 15:41:26,042.042 [log.py:35] - DEBUG - disconnect
53+
2021-07-15 15:41:26,042.042 [client.py:2165] - DEBUG - Sending DISCONNECT
54+
2021-07-15 15:41:26,043.043 [log.py:35] - DEBUG - on_disconnect:rc:0,userdata:None
55+
2021-07-15 15:41:26,043.043 [log.py:35] - DEBUG - LoopThread thread exit
56+
```
57+
As can be seen, the dynamic registration is successful, the device key is obtained, the MQTT is connected successfully, the NTP time is synced, and the `deviceSecret` field is updated in the [device_info.json](../../explorer/sample/device_info.json) configuration file.

0 commit comments

Comments
 (0)