## ## SL2-100 UDP Forwarder ## 监控 CSV 文件,将新行通过 UDP 发送到目标端口 ## ## 用法: python udp_forwarder.py [csv文件路径] [目标IP] [目标端口] ## 示例: python udp_forwarder.py d:/sl2-100.csv 127.0.0.1 12345 ## 默认: python udp_forwarder.py d:/sl2-100.csv 127.0.0.1 12345 ## import socket import sys import os import time def main(): # 默认参数 csv_file = "d:/sl2-100.csv" target_host = "192.168.1.155" target_port = 41234 # 命令行参数解析 if len(sys.argv) >= 2: csv_file = sys.argv[1] if len(sys.argv) >= 3: target_host = sys.argv[2] if len(sys.argv) >= 4: target_port = int(sys.argv[3]) print(f"[UDP Forwarder] 启动") print(f" CSV 文件: {csv_file}") print(f" UDP 目标: {target_host}:{target_port}") print(f" 等待 CSV 文件生成...") # 创建 UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 等待 CSV 文件出现 while not os.path.exists(csv_file): time.sleep(0.1) print(f" CSV 文件已发现,开始监控...") # 读取文件初始大小(跳过表头) file_size = os.path.getsize(csv_file) with open(csv_file, 'r', encoding='gbk') as f: header = f.readline() # 跳过 "x坐标,y坐标" 表头 file_size = os.path.getsize(csv_file) print(f" 已跳过表头: {header.strip()}") # 轮询文件变化 while True: try: current_size = os.path.getsize(csv_file) if current_size < file_size: # 文件被截断了(重新开始),重新定位 print(f" 检测到文件被重置,重新开始跟踪") file_size = current_size with open(csv_file, 'r', encoding='gbk') as f: f.readline() # 跳过表头 file_size = os.path.getsize(csv_file) if current_size > file_size: # 有新数据写入 with open(csv_file, 'r', encoding='gbk') as f: f.seek(file_size) new_lines = f.read() file_size = current_size # 逐行发送 for line in new_lines.strip().split('\n'): line = line.strip()+',0' if line: data = (line + '\n').encode('utf-8') sock.sendto(data, (target_host, target_port)) print(f" UDP -> {target_host}:{target_port}: {line}") time.sleep(0.01) # 10ms 轮询间隔 except FileNotFoundError: print(f" CSV 文件丢失,等待重新创建...") while not os.path.exists(csv_file): time.sleep(0.5) file_size = 0 print(f" CSV 文件重新出现,继续监控...") except KeyboardInterrupt: print(f"\n[UDP Forwarder] 已停止") break except Exception as e: print(f" 错误: {e}") time.sleep(0.5) sock.close() if __name__ == '__main__': main()