使用PythonPaho框架开发原生MQTT接口

网友投稿 838 2022-05-29

说明:阅读该文档之前需要对Mqtt有一定的了解,这里不对Mqtt知识作介绍,对Mqtt的了解请自行搜索学习。主要说明一下用一个简单的Demo样例,实现和IoT平台的对接,上报数据,下发命令等

一、注册设备

产品信息中的 协议类型 必须为MQTT

设备管理—>新增真实设备—>选择上面开发好的产品—>接入方式选择 直连

保存设备ID和密钥,利用其构建clientID

进入设备管理界面—>产品模型

如果没有产品模型,可以点击右上角,从产品中心导入或者是本地导入

注意:产品的协议类型必须为MQTT

进入设备管理界面—>设备—>设备注册—>创建

保存设备ID和密钥,利用其构建clientID

注册设备(密码方式)

使用Python版Paho框架开发原生MQTT接口

https://support.huaweicloud.com/api-IoT/iot_06_0005.html

二、IoT平台提供的原生MQTT接口

https://support.huaweicloud.com/api-IoT/iot_06_3002.html

本篇文档基于eclipse的paho框架,该框架网上资料较多,可自行百度搜索学习。

Python

库: paho_mqtt-1.4.0-py3.7.egg-info

(1) 主要是证书的配置,ca_certs就是证书的路径

(2) 其他参数的配置请参考源码:)

Python

# 连接地址每个局点不一样,比如开发中心是:iot-acc-dev.huaweicloud.com host = "xx.xx.xx.xx" port = 8883 # 注册直连设备的时候返回的设备ID deviceId = "9a57a-***-***-816b3e" # 注册直连设备的时候返回的秘钥 DeviceSecret = "cbd*******3abv" ca_certs = '../rootcert.pem' para = get_para.Getpara(deviceId, DeviceSecret) paras = para.get_para() clientId = paras[0] username = paras[1] password = paras[2] mqtt = mqtt.Client(clientId, clean_session=True) def connect():     # callback     mqtt.on_connect = on_connect     mqtt.on_disconnect = on_disconnect     mqtt.on_publish = on_publish     mqtt.on_message = on_message     mqtt.username_pw_set(username, password)     mqtt.tls_set(ca_certs, cert_reqs=ssl.CERT_NONE)     mqtt.connect(host, port, 60)     mqtt.loop_forever()

数据上报就是往平台指定的topic上发布数据

Python

def publish():     pubTopic = "/huawei/v1/devices/" + deviceId + "/data/json"     payload = {         "msgType": "deviceReq",         "data": [             {                 "serviceId": "Storage",                 "serviceData": {                     "storage": "1"                 }             }         ]     }     message = json.dumps(payload)     mqtt.publish(pubTopic, message, 1)

命令接收就是订阅平台指定的topic,平台往该topic发送命令时,设备端就能收到

Python

def subscribe():     subtopic = "/huawei/v1/devices/" + deviceId + "/command/json"     mqtt.subscribe(subtopic)def on_message(client, userdata, msg):     print("\n===== The command is received from the platform ===== \n", msg.payload.decode("utf-8"))     receiveMes= json.loads(msg.payload.decode("utf-8"))     mid = receiveMes['mid']     commandRsp(mid)

应用服务器要需要调用“订阅平台业务数据”API订阅“commandRsp”类型的通知后,才能接收到设备对控制命令的应答;

先订阅topic(/huawei/v1/devices/{deviceId}/command/{codecMode})接收到命令,然后往另外一个topic(/huawei/v1/devices/{deviceId}/data/{codecMode})发数据响应给平台,就视为对这条命令的响应,但是要注意,数据上报和命令响应的topic虽然是相同的,但是他们上报的结构体是有区别的

Python

def commandRsp(mid):     RspTopic = "/huawei/v1/devices/" + deviceId + "/data/json"     payload = {         "msgType": "deviceRsp",         "mid": mid,         "errcode": 0,         "body": {             "result": 0         }     }     message = json.dumps(payload)     mqtt.publish(RspTopic, message, 1)

生成 clientId, username, password

class Getpara():     def __init__(self, deviceId, deviceSecret):         self.DeviceId = deviceId         self.DeviceSecret = deviceSecret    def get_para(self):         ClientId = self.DeviceId         DeviceId = self.DeviceId         DeviceSecret = self.DeviceSecret         timestamp = time.strftime('%Y%m%d%H', time.localtime(time.time()))         # clientID参考API文档拼装         clientId = "".join((ClientId, "_0", "_0", "_", timestamp))         username = DeviceId         deviceSecret = DeviceSecret.encode('utf-8')         password = hmac.new(timestamp.encode('utf-8'), deviceSecret,             digestmod=hashlib.sha256).hexdigest()         return clientId, username, password

附件: 证书.zip 1.08KB 下载次数:8次

IoT IoT MQTT

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:kubernetes学习必备(awesome-kubernetes-notes)
下一篇:360智汇云上线沃通SSL证书及电子签名服务
相关文章