import paho.mqtt.client as mqtt
import json
import time
import datetime

# MQTT 配置
# BROKER = "100.68.18.111"  # 与发送端相同
BROKER = "band.hxzhxy.cn"  # 与发
PORT = 1883
TOPICs = ["cmd/publicizeBanpai/#","upload/publicizeBanpai/#","common/publicizeBanpai/#"]  # 与发送端相同
CLIENT_ID = "python-mqtt-receiver"


# 收到消息时的回调
def on_message(client, userdata, msg):
    try:
        payload = msg.payload.decode()
        mac = msg.topic.split("/")[2]
        print("\n" + "=" * 50)
        print(f"收到新消息 [QoS: {msg.qos}]")
        print(f"客户端 ID: {mac}")
        print(f"主题: {msg.topic}")
        if "message" in msg.topic:
            
            data = json.loads(json.loads(payload)["data"])
            ip = data["ip"]
            mac = data["mac"]
            print(ip,mac)
        print(f"时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
        print("内容:")
        print(payload)
        if "systeminfo" in msg.topic:
            with open("mqtt_systeminfo.txt", "a+") as f:
                f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write(f"客户端 ID: {mac}\n")
                f.write(f"\n")
    except Exception as e:
        print(f"消息解析错误: {e}")


# 创建客户端
client = mqtt.Client(CLIENT_ID)
client.on_message = on_message

# 连接并订阅
print(f"连接到 MQTT 代理: {BROKER}:{PORT}")
client.connect(BROKER, PORT)
for topic in TOPICs:
    client.subscribe(topic)
print(f"已订阅主题: {TOPICs}")
print("等待消息... (按 Ctrl+C 退出)")

# 保持连接
try:
    client.loop_forever()
except KeyboardInterrupt:
    print("\n断开连接...")
    client.disconnect()
