一、概述
阿裡雲物聯網平台裝置的動态注冊分為一型一密預注冊和一型一密免預注冊,具體說明與限制請參考官方文檔:
https://help.aliyun.com/document_detail/132111.html二、前提條件
控制台前置操作
産品詳情頁開啟“動态注冊”
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5iN4MDZjdzMzMjMwQzN4QmYkNGZ0QTN4cjN5QGZjRTOl9CX5d2bs92Yl1iclB3bsVmdlR2LcNWaw9CXt92Yu4GZjlGbh5yYjV3Lc9CX6MHc0RHaiojIsJye.png)
預注冊:表示需要提前在物聯網平台控制台上添加好裝置。
免預注冊:無需在控制台提前添加裝置。
安裝開源paho mqtt庫
pip install paho-mqtt
下載下傳根證書
目前,動态注冊隻支援使用TLS建立連接配接,不支援TCP直連。是以需要下載下傳根證書。
https://aliyun-iot.oss-cn-hangzhou.aliyuncs.com/cert_pub/root.crt三、代碼示例
預注冊(上海公共執行個體)
import hmac
from hashlib import sha1
import paho.mqtt.client as mqtt
def on_message(client, userdata, msg):
print(str(msg.payload))
def on_connect(client, userdata, flags, rc):
#物聯網平台傳回的結果碼,0表示動态注冊成功,其他錯誤碼參考文檔排查:https://help.aliyun.com/document_detail/132111.html
print('rc:'+str(rc))
client = mqtt.Client(client_id='12345|securemode=2,authType=register,random=123,signmethod=hmacsha1|')
productKey = '***'
productSecret = '***'
deviceName = 'register_device'
content = 'deviceName' + deviceName + 'productKey' + productKey + 'random' + '123'
username = deviceName + '&' + productKey
password = hmac.new(productSecret.encode(),content.encode(),sha1).hexdigest()
client.username_pw_set(username=username, password=password)
client.on_connect = on_connect
client.on_message = on_message
#設定TLS連接配接證書路徑
client.tls_set('root.crt')
client.connect(host="${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com", port=1883)
client.loop_start()
while True:
1;
運作結果
免預注冊(上海公共執行個體)
import hmac
from hashlib import sha1
import paho.mqtt.client as mqtt
def on_message(client, userdata, msg):
print(str(msg.payload))
def on_connect(client, userdata, flags, rc):
# 物聯網平台傳回的結果碼,0表示動态注冊成功,其他錯誤碼參考文檔排查:https://help.aliyun.com/document_detail/132111.html
print('rc:' + str(rc))
client = mqtt.Client(client_id='12345|securemode=-2,authType=regnwl,random=123,signmethod=hmacsha1|')
productKey = '***'
productSecret = '***'
deviceName = 'regnwl_device'
content = 'deviceName' + deviceName + 'productKey' + productKey + 'random' + '123'
username = deviceName + '&' + productKey
password = hmac.new(productSecret.encode(),content.encode(),sha1).hexdigest()
client.username_pw_set(username=username, password=password)
client.on_connect = on_connect
client.on_message = on_message
#設定TLS連接配接證書路徑
client.tls_set('root.crt')
client.connect(host="${productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com", port=1883)
client.loop_start()
while True:
1;