Python Mqtt5
import paho.mqtt.client as mqtt from datetime import datetime import threading import time # MQTT Broker设置 BROKER_HOST = "emqx.x.cn" BROKER_PORT = 1883 TOPIC_TO_SUBSCRIBE = "/9110000/#" # MQTT 客户端ID和认证信息 CLIENT_ID = "backend-1234" USERNAME = "hwplat" PASSWORD = "12" # 消息接收及存储 MESSAGE_LOG_FILE = "mqtt_messages-send.log" def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") # 订阅指定主题 client.subscribe(TOPIC_TO_SUBSCRIBE,0) else: print("Failed to connect, return code %d" % rc) def on_message(client, userdata, msg): timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') message_info = f"<-: {timestamp} {msg.payload.decode()}\n" print(message_info) # 将消息写入文件 with open(MESSAGE_LOG_FILE, 'a') as file: file.write(message_info) #print(f"Message received and written to file: {message_info.strip()}") # 创建MQTT客户端实例client_id="", clean_session=True, userdata=None, client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION1,client_id=CLIENT_ID) #client = mqtt.Client(client_id=CLIENT_ID, clean_session=True) #client.protocol_version = mqtt.MQTTv5 # 设置用户名和密码 client.username_pw_set(USERNAME, PASSWORD) # 设置回调函数 client.on_connect = on_connect client.on_message = on_message # 连接到MQTT Broker client.connect(BROKER_HOST, BROKER_PORT) PUBLISH_TOPIC = "/9110000/app/msg/sub" PUBLISH_PAYLOAD = "{\"appno\":\"1\",\"cmd\":\"req_tcp_data\",\"data\":{\"command\":\"QueryVersion\",\"module\":\"basic\"},\"msgid\":\"\"}" def publish_timer(): i=10 while True: i=i+1 timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') nnn=PUBLISH_PAYLOAD + str(i) client.publish(PUBLISH_TOPIC, nnn,1) print(f"->: {timestamp} {nnn}") time.sleep(1) # 等待1秒后再次发送 # 创建并启动定时发送消息的线程 publish_thread = threading.Thread(target=publish_timer) publish_thread.daemon = True # 设置为守护线程,主线程结束时该线程也会结束 publish_thread.start() # 开始消息循环 client.loop_forever()