Files
cjgc_data/ck/device_b.py
2026-03-12 17:03:56 +08:00

118 lines
3.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
设备B示例 - 接收端
模拟第二台设备,接收站点数据(用户名、线路名称、站点编号)并应答
"""
from serial_protocol import SerialProtocol, Command
from data_models import StationData, ResponseData
import time
import subprocess
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("✓ 接收线程已启动,等待接收数据...")
try:
# 保持运行
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\n\n用户中断")
finally:
device.close()
print("串口已关闭")
if __name__ == '__main__':
main()