由于阿里云物联网套件关于设备认证的文档不够详细,笔者差不多摸索了几天才连接上mqtt。下面是使用python模拟设备接入阿里云的mqtt。
阿里云物联网套件提供两种接入方式:
mqtt客户端域名直连(资源受限设备推荐)
先https发送授权后再连接mqtt(一些特殊增值服务,比如设备级别的引流)
本文主要介绍第一种接入方式,tcp直连,并提供python代码示例。
1、mqttclientid
2、mqttusername
使用<code>&</code>拼接<code><devicename></code>和<code><productkey></code>。
3、mqttpassword
把以下参数按字典键名排序,再把键名都拼接起来(没有分隔符)生成content,然后以devicesecret为盐,对content进行hma_sha1加密,最后二进制转为十六进制字符串表示。
clientid
devicename
productkey
timestamp
假设
clientid = 12345
devicename = device
productkey = pk
timestamp = 789
signmethod = hmacsha1
content拼接结果:<code>clientid12345devicenamedeviceproductkeypktimestamp789</code>
注意:不用拼接signmethod参数。
对content以devicesecret为盐进行hmacsha1加签后,再转为十六进制字符串,最后结果:<code>fafd82a3d602b37fb0fa8b7892f24a477f851a14</code>
注意:不需要base64。
最后总结一下生成的参数:
mqtthost = <code>pk.iot-as-mqtt.cn-shanghai.aliyuncs.com</code>
mqttport = 1883
mqttclientid = <code>12345|securemode=3,signmethod=hmacsha1,timestamp=789|</code>
mqttusername = <code>device&pk</code>
mqttpassword = <code>fafd82a3d602b37fb0fa8b7892f24a477f851a14</code>
参数
描述
产品key。从iot套件控制台获取
设备名称。从iot套件控制台获取
devicesecret
设别密码,从iot套件控制台获取
signmethod
算法类型,hmacmd5或hmacsha1
客户端自表示id,建议mac或sn
当前时间毫秒值,可选
securemode
目前安全模式,可选值有2 (tls直连模式)、3(tcp直连模式)
填写自己的<code>productkey</code>、<code>clientid</code>、<code>devicename</code>、<code>devicesecret</code>。
<a href="https://help.aliyun.com/document_detail/30539.html">阿里云物联网套件 > 设备端接入手册 > 设备基于mqtt接入 > 设备认证</a>
终于知道之前为什么总是连接不上了!!!之前文档对password加密的字段是多了「signmethodhmacsha1」字符串!