导入相关包
import paho.mqtt.client as mqtt
import time
import hashlib
import hmac
import json
import serial
import re
一. 发布Topic
- 定义报文
PUB_TOPIC = "/sys/" + options['productKey'] + "/" + options[
'deviceName'] + "/thing/event/property/post"
options是一个自定义的字典,包含productKey,deviceName等数据,键值自定义
options = {
'productKey': 'XXX',
'deviceName': 'XXX',
'deviceSecret': 'XXXX',
'regionId': 'cn-shanghai'
}
2.使用publish方法发布
client.publish(PUB_TOPIC, payload=str(payload_json), qos=1)
client: 是连接服务端后回调client
def Connect_server():
timestamp = str(int(time.time()))
CLIENT_ID = "paho.py|securemode=3,signmethod=hmacsha1,timestamp=" + timestamp + "|"
CONTENT_STR_FORMAT = "clientIdpaho.pydeviceName" + options[
'deviceName'] + "productKey" + options[
'productKey'] + "timestamp" + timestamp
# set username/password.
USER_NAME = options['deviceName'] + "&" + options['productKey']
PWD = hmacsha1(options['deviceSecret'], CONTENT_STR_FORMAT)
client = mqtt.Client(client_id=CLIENT_ID, clean_session=False)
client.username_pw_set(USER_NAME, PWD)
return client
payload_json: 是任意数据类型的数据(String,tuple,number,dict,list)
payload:为推送的内容,将payload_json转换字符串类型
这样就可以完成报文的发布,并且由服务端订阅后即可收到客户端推送的消息。
二.订阅报文
- 定义一个字符串常量,指明要订阅的报文
SUB_TOPIC = "/sys/" + options['productKey'] + "/" + options[
'deviceName'] + "/thing/event/property/set"
这是一个属性设置的报文,订阅该报文后,服务端属性设置的操作,客户端可以收到属性设置的指令内容
- 订阅报文——subscribe方法
client.subscribe(SUB_TOPIC, 1)
实参1: 代表服务等级为1
这样就完成了报文的订阅了