天天看點

阿裡雲物聯網平台MQTT通道的動态注冊(Python)

一、概述

阿裡雲物聯網平台裝置的動态注冊分為一型一密預注冊和一型一密免預注冊,具體說明與限制請參考官方文檔:

https://help.aliyun.com/document_detail/132111.html

二、前提條件

控制台前置操作

産品詳情頁開啟“動态注冊”

阿裡雲物聯網平台MQTT通道的動态注冊(Python)

預注冊:表示需要提前在物聯網平台控制台上添加好裝置。

阿裡雲物聯網平台MQTT通道的動态注冊(Python)

免預注冊:無需在控制台提前添加裝置。

安裝開源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;      

運作結果

阿裡雲物聯網平台MQTT通道的動态注冊(Python)

免預注冊(上海公共執行個體)

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;      
阿裡雲物聯網平台MQTT通道的動态注冊(Python)
阿裡雲物聯網平台MQTT通道的動态注冊(Python)