83 lines
2.4 KiB
Python
83 lines
2.4 KiB
Python
"""
|
|
数据模型定义
|
|
定义设备间传输的数据结构
|
|
"""
|
|
|
|
import json
|
|
from typing import Optional, Dict, Any
|
|
from dataclasses import dataclass, asdict
|
|
|
|
|
|
@dataclass
|
|
class StationData:
|
|
"""站点数据模型"""
|
|
username: str # 用户名
|
|
line_name: str # 线路名称
|
|
station_no: int # 第几站
|
|
|
|
def to_bytes(self) -> bytes:
|
|
"""转换为字节数据"""
|
|
data_dict = asdict(self)
|
|
json_str = json.dumps(data_dict, ensure_ascii=False)
|
|
return json_str.encode('utf-8')
|
|
|
|
@staticmethod
|
|
def from_bytes(data: bytes) -> Optional['StationData']:
|
|
"""从字节数据解析"""
|
|
try:
|
|
json_str = data.decode('utf-8')
|
|
data_dict = json.loads(json_str)
|
|
return StationData(
|
|
username=data_dict['username'],
|
|
line_name=data_dict['line_name'],
|
|
station_no=data_dict['station_no']
|
|
)
|
|
except Exception as e:
|
|
print(f"解析数据失败: {e}")
|
|
return None
|
|
|
|
def __str__(self):
|
|
"""字符串表示"""
|
|
return (f"用户: {self.username}, "
|
|
f"线路: {self.line_name}, "
|
|
f"站点: 第{self.station_no}站")
|
|
|
|
|
|
class ResponseData:
|
|
"""设备B统一响应数据格式 {1:"xxxx", 2:"xxxx", 3:"xxxx", ...}"""
|
|
|
|
@staticmethod
|
|
def create_response(station_data: StationData) -> Dict[int, str]:
|
|
"""
|
|
根据站点数据创建响应字典
|
|
|
|
Args:
|
|
station_data: 接收到的站点数据
|
|
|
|
Returns:
|
|
格式化的响应字典 {1: "用户名", 2: "线路名", 3: "站点号", ...}
|
|
"""
|
|
return {
|
|
1: station_data.username,
|
|
2: station_data.line_name,
|
|
3: str(station_data.station_no),
|
|
4: "已接收",
|
|
5: "设备B确认"
|
|
}
|
|
|
|
@staticmethod
|
|
def to_bytes(response_dict: Dict[int, str]) -> bytes:
|
|
"""将响应字典转换为字节数据"""
|
|
json_str = json.dumps(response_dict, ensure_ascii=False)
|
|
return json_str.encode('utf-8')
|
|
|
|
@staticmethod
|
|
def from_bytes(data: bytes) -> Optional[Dict[int, Any]]:
|
|
"""从字节数据解析响应字典"""
|
|
try:
|
|
json_str = data.decode('utf-8')
|
|
return json.loads(json_str)
|
|
except Exception as e:
|
|
print(f"解析响应数据失败: {e}")
|
|
return None
|