一、概述
阿里云物联网平台设备的动态注册分为一型一密预注册和一型一密免预注册,具体说明与限制请参考官方文档:https://help.aliyun.com/document_detail/132111.html
二、前提条件
控制台前置操作
产品详情页开启“动态注册”
预注册:表示需要提前在物联网平台控制台上添加好设备。
免预注册:无需在控制台提前添加设备。
安装开源paho mqtt库
pip install paho-mqtt
下载根证书
目前,动态注册只支持使用TLS建立连接,不支持TCP直连。因此需要下载根证书。
https://aliyun-iot.oss-cn-hangzhou.aliyuncs.com/cert_pub/root.crt
三、代码示例
预注册(上海公共实例)
importhmacfromhashlibimportsha1importpaho.mqtt.clientasmqttdefon_message(client, userdata, msg): print(str(msg.payload)) defon_connect(client, userdata, flags, rc): #物联网平台返回的结果码,0表示动态注册成功,其他错误码参考文档排查:https://help.aliyun.com/document_detail/132111.htmlprint('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+'&'+productKeypassword=hmac.new(productSecret.encode(),content.encode(),sha1).hexdigest() client.username_pw_set(username=username, password=password) client.on_connect=on_connectclient.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() whileTrue: 1;
运行结果
免预注册(上海公共实例)
importhmacfromhashlibimportsha1importpaho.mqtt.clientasmqttdefon_message(client, userdata, msg): print(str(msg.payload)) defon_connect(client, userdata, flags, rc): # 物联网平台返回的结果码,0表示动态注册成功,其他错误码参考文档排查:https://help.aliyun.com/document_detail/132111.htmlprint('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+'&'+productKeypassword=hmac.new(productSecret.encode(),content.encode(),sha1).hexdigest() client.username_pw_set(username=username, password=password) client.on_connect=on_connectclient.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() whileTrue: 1;
运行结果