import logging
from hytest import *
from 预定系统.Base.Mqtt_Send import *
from 预定系统.Base.base import *

# 获取当前脚本所在的目录
current_dir = os.path.dirname(os.path.abspath(__file__))

# 构建CSV文件的绝对路径
csv_file_path = os.path.join(current_dir, '../../测试数据/MQTT模块/富创项目_会议推送.csv')

if __name__ == "__main__":
    # 读取配置文件
    configs = Mqtt.read_config_from_csv(csv_file_path)

    broker_address = "192.168.5.218"
    port = 1883
    num_repeats = 100  # 重复执行的次数
    interval_between_repeats = 0.2  # 每次重复之间的间隔时间（秒）

    # 创建 MQTT 客户端实例
    mqtt_client = Mqtt(broker_address, port)

    try:
        # 连接到 MQTT 服务器
        mqtt_client.connect()
        logging.info("已连接到MQTT服务器")

        # 遍历配置文件中的每一行数据
        for config in configs:
            # 构建消息内容-
            # 构建消息内容
            topic = config["topic"]
            logging.info(config)
            message = Mqtt.build_message(config, "00:00", topic)

            # 发送消息
            mqtt_client.publish(topic, message)

            # 每次发送之间可以设置一个间隔时间
            time.sleep(interval_between_repeats)

        # 每次重复之间设置一个间隔时间
        time.sleep(interval_between_repeats)

    except Exception as e:
        logging.error(f"发送消息时发生错误: {e}")

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