You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.5 KiB

5 months ago
# -*- coding: utf-8 -*-# -*- coding: utf-8 -*-
# 订阅者
import paho.mqtt.client as mqtt
broker = '121.40.129.71'
# 连接成功回调
def on_connect(client, userdata, flags, rc,properties):
if rc.is_failure:
print(f"连接失败: {rc}. loop_forever()将重新连接")
else:
print(f'连接成功: {rc}')
client.subscribe('host_status/#')
def on_subscribe(client, userdata, mid, reason_code_list, properties): # 订阅回调
if reason_code_list[0].is_failure:
print(f'订阅失败: {reason_code_list[0]}')
else:
print(f'订阅成功: {reason_code_list[0].value}')
def on_unsubscribe(client, userdata, mid, reason_code_list, properties): # 取消订阅回调
if len(reason_code_list) == 0 or not reason_code_list[0].is_failure:
print("取消订阅成功(if SUBACK is received in MQTTv3 it success)")
else:
print(f"取消订阅失败: {reason_code_list[0]}")
client.disconnect() # 断开连接
# 消息接收回调
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
mqtt = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="book_1")
mqtt.on_connect = on_connect
mqtt.on_message = on_message
mqtt.on_subscribe = on_subscribe
mqtt.on_unsubscribe = on_unsubscribe
mqtt.is_connected()
mqtt.user_data_set(["user_data", "book_1"])
mqtt.connect(broker, 48835, 60)
mqtt.loop_forever()
print(f"收到以下消息: {mqtt.user_data_get()}")
# while True:
# rc = mqtt.loop(timeout=1.0)
# print(11)
# if rc != 0:
# mqtt.reconnect()