毫米波雷达.py 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
import sys
import os
# 获取当前脚本的绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
# 构建预定系统的绝对路径
预定系统_path = os.path.abspath(os.path.join(current_dir, '..','..','..'))
# 添加路径
sys.path.append(预定系统_path)
# 导入模块
try:
    from 预定系统.Base.Mqtt_Send import *
except ModuleNotFoundError as e:
    print(f"ModuleNotFoundError: {e}")
    print("尝试使用绝对路径导入")
    from 预定系统.Base.Mqtt_Send import *

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

# 构建CSV文件的绝对路径
21 22
# csv_file_path = os.path.join(current_dir, '../../测试数据/MQTT模块/MQTT毫米波上报数据.csv')
csv_file_path = os.path.join(current_dir, '../../测试数据/MQTT模块/MQTT毫米波调试.csv')
23 24 25 26 27

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

28 29 30 31
    broker_address = "192.168.1.131"
    port = 1881
    num_repeats = 2000  # 重复执行的次数
    interval_between_repeats = 1  # 每次重复之间的间隔时间(秒)
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

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

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

        for repeat in range(num_repeats):
            logging.info(f"开始第 {repeat + 1} 次上报")

            # 遍历配置文件中的每一行数据
            for config in configs:
                # 构建消息内容
                topic = config["topic"]
                current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                message = Mqtt.build_message(config, current_time, topic)

50
                logging.info(message)
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
                # 发送消息
                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()