修改驱动启用;两个大块逻辑。
This commit is contained in:
188
ck/device_b.py
188
ck/device_b.py
@@ -1,117 +1,87 @@
|
||||
"""
|
||||
设备B示例 - 接收端
|
||||
模拟第二台设备,接收站点数据(用户名、线路名称、站点编号)并应答
|
||||
"""
|
||||
|
||||
from serial_protocol import SerialProtocol, Command
|
||||
from data_models import StationData, ResponseData
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import subprocess
|
||||
import serial
|
||||
import os
|
||||
|
||||
# 添加项目根目录到Python搜索路径
|
||||
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
||||
|
||||
from globals.driver_utils import DriverManager
|
||||
import globals.driver_utils as driver_utils
|
||||
import actions
|
||||
import check_station
|
||||
from check_station import get_excel_from_url
|
||||
|
||||
PORT = "COM9"
|
||||
BAUD = 115200
|
||||
|
||||
RESPONSE_PAYLOAD = {
|
||||
"1": "xxxx",
|
||||
"2": "xxxx",
|
||||
"3": "xxxx",
|
||||
}
|
||||
|
||||
|
||||
def on_receive(cmd: int, data: bytes):
|
||||
"""接收数据回调函数"""
|
||||
print("\n" + "="*60)
|
||||
print("[设备B] 收到数据")
|
||||
print("="*60)
|
||||
cmd_name = (Command(cmd).name if cmd in Command._value2member_map_
|
||||
else 'UNKNOWN')
|
||||
print(f"命令类型: 0x{cmd:02X} ({cmd_name})")
|
||||
|
||||
# 根据不同命令进行处理
|
||||
if cmd == Command.HEARTBEAT:
|
||||
print(">>> 收到心跳包")
|
||||
# 可以回复ACK
|
||||
device.send_ack()
|
||||
print("<<< 已发送ACK应答\n")
|
||||
|
||||
elif cmd == Command.DATA_RESPONSE:
|
||||
# 尝试解析站点数据
|
||||
station_data = StationData.from_bytes(data)
|
||||
if station_data:
|
||||
print("\n📍 站点数据详情:")
|
||||
print(f" 用户名称: {station_data.username}")
|
||||
print(f" 线路名称: {station_data.line_name}")
|
||||
print(f" 站点编号: 第{station_data.station_no}站")
|
||||
|
||||
# 根据站点编号执行不同逻辑
|
||||
if station_data.station_no == 0:
|
||||
print("\n🚀 站点编号为0,启动 actions.py")
|
||||
# 启动 actions.py
|
||||
|
||||
subprocess.Popen(["python", "actions.py"], cwd="d:\\Projects\\cjgc_data")
|
||||
|
||||
if station_data.station_no > 0:
|
||||
print(f"\n🚀 站点编号为{station_data.station_no},启动 check_station.py")
|
||||
# 启动 check_station.py
|
||||
|
||||
subprocess.Popen(["python", "check_station.py"], cwd="d:\\Projects\\cjgc_data")
|
||||
|
||||
# 创建统一格式的响应字典 {1:"xxx", 2:"xxx", 3:"xxx", ...}
|
||||
response_dict = ResponseData.create_response(station_data)
|
||||
print("\n📤 设备B统一响应格式:")
|
||||
for key, value in response_dict.items():
|
||||
print(f" {key}: \"{value}\"")
|
||||
|
||||
# 发送响应
|
||||
device.send_data(ResponseData.to_bytes(response_dict))
|
||||
print("\n<<< 已发送响应字典\n")
|
||||
else:
|
||||
# 如果不是站点数据,按普通消息处理
|
||||
message = data.decode('utf-8', errors='ignore')
|
||||
print(f">>> 收到普通消息: {message}")
|
||||
device.send_ack()
|
||||
print("<<< 已发送ACK\n")
|
||||
|
||||
elif cmd == Command.CONTROL:
|
||||
if len(data) >= 1:
|
||||
control_code = data[0]
|
||||
params = data[1:]
|
||||
print(f">>> 收到控制命令: 0x{control_code:02X}, "
|
||||
f"参数: {params.hex()}")
|
||||
# 执行控制逻辑...
|
||||
device.send_ack()
|
||||
print("<<< 已发送ACK\n")
|
||||
|
||||
|
||||
# 全局变量,用于在回调中访问
|
||||
device = None
|
||||
|
||||
|
||||
def main():
|
||||
global device
|
||||
|
||||
# 创建串口协议实例
|
||||
# 注意: 设备B应该使用另一个串口,或者通过虚拟串口对连接
|
||||
# Windows: 'COM2', Linux: '/dev/ttyUSB1'
|
||||
device = SerialProtocol(port='COM2', baudrate=115200)
|
||||
|
||||
print("=" * 60)
|
||||
print("设备B - 接收端")
|
||||
print("=" * 60)
|
||||
|
||||
# 打开串口
|
||||
if not device.open():
|
||||
print("❌ 无法打开串口")
|
||||
return
|
||||
|
||||
print(f"✓ 串口已打开: {device.port} @ {device.baudrate}")
|
||||
|
||||
# 启动接收线程
|
||||
device.start_receive(on_receive)
|
||||
print("✓ 接收线程已启动,等待接收数据...")
|
||||
def main() -> int:
|
||||
driver, wait, device_id = DriverManager.get_driver()
|
||||
url = f"https://database.yuxindazhineng.com/team-bucket/69378c5b4f42d83d9504560d/前测点表/20260309/CDWZQ-2标-龙家沟左线大桥-0-11号墩-平原.xlsx"
|
||||
station_data = get_excel_from_url(url)
|
||||
print(station_data)
|
||||
station_quantity = len(station_data) #总站点数量
|
||||
over_station_num = 0 #已完成的站点数量
|
||||
over_station_list = []
|
||||
|
||||
try:
|
||||
# 保持运行
|
||||
while True:
|
||||
time.sleep(1)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("\n\n用户中断")
|
||||
with serial.Serial(PORT, BAUD, timeout=1) as ser:
|
||||
print(f"Opened {PORT} at {BAUD} baud")
|
||||
while True:
|
||||
line = ser.readline().decode("utf-8", errors="ignore").strip()
|
||||
if line:
|
||||
print(f"RX: {line}")
|
||||
# 解析接收到的JSON数据
|
||||
try:
|
||||
data = json.loads(line)
|
||||
|
||||
# 检查station字段
|
||||
if "station" in data:
|
||||
station_value = data["station"]
|
||||
|
||||
# station等于0时启动actions.py
|
||||
if station_value == 0:
|
||||
print("\n🚀 站点编号为0,启动 actions.py")
|
||||
# 启动 actions.py
|
||||
app = actions.DeviceAutomation(driver=driver, wait=wait, device_id=device_id)
|
||||
app.run_automation()
|
||||
# subprocess.Popen(["python", "actions.py"], cwd="d:\\Projects\\cjgc_data")
|
||||
|
||||
# station大于0时启动check_station.py
|
||||
elif station_value > 0 and over_station_num < station_quantity and station_value not in over_station_list:
|
||||
print(f"\n🚀 站点编号为{station_value},启动 check_station.py")
|
||||
# 启动 check_station.py
|
||||
# driver_utils.ensure_appium_server_running()
|
||||
app = check_station.CheckStation(driver, wait, device_id)
|
||||
station = app.main_run()
|
||||
if station:
|
||||
over_station_num += 1
|
||||
over_station_list.append(station_value)
|
||||
# subprocess.Popen(["python", "check_station.py"], cwd="d:\\Projects\\cjgc_data")
|
||||
|
||||
except json.JSONDecodeError:
|
||||
print("Received non-JSON data")
|
||||
reply = (
|
||||
json.dumps(RESPONSE_PAYLOAD, ensure_ascii=False) + "\n"
|
||||
)
|
||||
ser.write(reply.encode("utf-8"))
|
||||
print(f"TX: {reply.strip()}")
|
||||
time.sleep(0.05)
|
||||
except serial.SerialException as exc:
|
||||
print(f"Serial error: {exc}")
|
||||
return 1
|
||||
finally:
|
||||
device.close()
|
||||
print("串口已关闭")
|
||||
if driver:
|
||||
DriverManager.quit_driver(device_id) # 安全退出驱动
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
Reference in New Issue
Block a user