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.

63 lines
2.0 KiB

5 months ago
import time
import paho.mqtt.client as mqtt
broker = '121.40.129.71'
def on_publish(client, userdata, mid, reason_code, properties):
# reason_code and properties will only be present in MQTTv5. It's always unset in MQTTv3
print(f"mid: {mid}, reason_code: {reason_code}, properties: {properties}") # mid: 消息ID, reason_code: 返回码, properties: 属性
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/#')
# unacked_publish = set()
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="book_1")
mqttc.on_publish = on_publish
mqttc.on_connect = on_connect
# mqttc.user_data_set(unacked_publish)
mqttc.connect(broker, 48835, 60)
# mqttc.loop_start()
while True:
if not mqttc.is_connected():
print("连接断开,重新连接")
mqttc.connect(broker, 48835, 60,)
keys = input("输入任意键发送消息输入q退出")
if keys == 'q':
break
mqttc.loop(timeout=1.0)
# Our application produce some messages
msg_info = mqttc.publish("tts/1", keys, qos=1)
# unacked_publish.add(msg_info.mid)
# msg_info2 = mqttc.publish("host_status", "my message2", qos=1)
# unacked_publish.add(msg_info2.mid)
# # Wait for all message to be published
# while len(unacked_publish):
# time.sleep
# Our application produce some messages
# msg_info = mqttc.publish("host_status", "my message", qos=1)
# # unacked_publish.add(msg_info.mid)
#
# msg_info2 = mqttc.publish("host_status", "my message2", qos=1)
# # unacked_publish.add(msg_info2.mid)
# # Wait for all message to be published
# while len(unacked_publish):
# time.sleep(0.1)
# Due to race-condition described above, the following way to wait for all publish is safer
# msg_info.wait_for_publish()
# msg_info2.wait_for_publish()
#
mqttc.disconnect()
mqttc.loop_stop()