python3和MQTT消息
1.MQTT介绍
MQTT是⼀个基于客户端-服务器的消息发布/订阅传输协议MQTT协议是轻量、简单、开放和易于实现的,这些特点使它适⽤范围⾮常⼴泛。在很多情况下,包括受限的环境中,如:机器与机器(M2M)通信和物联⽹(IoT)。其在,通过卫星链路通信传感器、偶尔拨号的医疗设备、智能家居、及⼀些⼩型化设备中已⼴泛使⽤。
2.Mqtt实现⽅式:
3.实现协议需要
实现MQTT协议需要:客户端和服务器端
MQTT协议中有三种⾝份:发布者(Publish)、代理(Broker)(服务器)、订阅者(Subscribe)。其中,消息的发布者和订阅者都是客户端,消息代理是服务器,消息发布者可以同时是订阅者。
MQTT传输的消息分为:主题(Topic)和负载(payload)两部分
Topic,可以理解为消息的类型,订阅者订阅(Subscribe)后,就会收到该主题的消息内容(payload)
payload,可以理解为消息的内容,是指订阅者具体要使⽤的内容
4.具体应⽤
使⽤token调⽤这个接⼝获取mqtt连接信息,使⽤接⼝返回的loadBalance、userId和token连接mqtt,订阅/sys/{userId}/notify这个topic,收到的消息体内容是就是消息下发的内容
5.具体代码
拆解第⼀步:获取mqtt连接信息
def get_md5_passwd(password):
"""
获取密码的md5
"""
my_md5 = hashlib.md5() # 获取⼀个MD5的加密算法对象
my_md5.de("utf-8")) # 得到MD5消息摘要
my_md5_Digest = my_md5.hexdigest() # 以16进制返回消息摘要,32位
return my_md5_Digest
def get_user_token(number='135********', passwd='zhu942100'):
"""
根据账号密码得到token
"""
url = 'ljd/auth/auth/login'
body = {
"channel": "1",
"deviceId": "",
"password": get_md5_passwd(passwd),
"username": number
}
res = requests.post(url=url, json=body, verify=False)
return res.json()['accessToken']
accessToken = get_user_token()
def topicsss():
"""
topic获取⽅式是采⽤tcl+tokenssss 来获取
ljd/project/298/interface/api/13897
"""
url = host + '/v1/auth/service/loadBalance'
header = {
'Content-Type': 'application/json',
'accessToken': accessToken # 7天有效期
}
result = (url=url, verify=False, headers=header)
# print('获取到的balance:{} useid:%s'.format(result.json()['data']['loadBalance']) % (result.json()['data']['userId'])) return result.json()['data']['loadBalance'], result.json()['data']['userId'], accessToken
拆解第⼆步:连接mqtt 并进⾏topic订阅
broker, user, pwd = topicsss()
broker = broker[6:30]
port = 1883
topic = "/sys/5219709/notify"
client_id = '5219709@' + str(random.randint(1, 9999))
def connect_mqtt() -> mqtt_client:
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker! %s" % rc)
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id)
client.username_pw_set(user, pwd)
<_connect = on_connect
# 配置服务器证书验证
client.tls_set(tls_version=ssl.PROTOCOL_TLSv1_2)
client.tls_insecure_set(True)
return client
def subscribe(client: mqtt_client):
def on_message(client, userdata, msg):
mylog = open('D:\push\/recode.log', mode='a', encoding='utf-8')
print(f"Received `{msg.payload.decode()}` from `{pic}` topic", file=mylog) print(f"Received `{msg.payload.decode()}` from `{pic}` topic")
mylog.close()
client.subscribe(topic)
<_message = on_message
def run():
client = connect_mqtt()
client.username_pw_set(user, pwd)
subscribe(client)
client.loop_forever()
if __name__ == '__main__': run()
python新手代码userid
6.下发消息,结果查看
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论