天天看点

阿里云物联网平台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)