from hytest import * # 获取当前脚本的绝对路径 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文件的绝对路径 csv_file_path = os.path.join(current_dir, '../../测试数据/MQTT模块/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() print('连接成功') 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") print(config) message = Mqtt.build_message(config, current_time, 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()