import paho.mqtt.client as mqtt
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# MQTT 客户端回调函数
def on_connect(client, userdata, flags, rc):
    logging.info("已连接到MQTT服务器")
    # 订阅多个主题
    topics = ["/androidPanel/", "/uams/android/broadcast", "/material/client/79f18c1a9a3bcfb1/"]
    for t in topics:
        client.subscribe(t)

def on_message(client, userdata, msg):
    logging.info(f"接收到消息: 主题={msg.topic}, 消息体={msg.payload.decode()}")

if __name__ == "__main__":
    # 5.218测试环境 192.168.5.218 1883

    broker_address = "192.168.5.218"
    port = 1883

    # 创建 MQTT 客户端实例
    mqtt_client = mqtt.Client()

    # 设置回调函数
    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message

    try:
        # 连接到 MQTT 服务器
        mqtt_client.connect(broker_address, port)

        # 启动网络循环
        mqtt_client.loop_forever()

    except Exception as e:
        logging.error(f"连接MQTT服务器时发生错误: {e}")

    finally:
        # 断开与 MQTT 服务器的连接
        mqtt_client.disconnect()