Files
VDES_Backend/报文模拟解析/地检设备模拟/vdes_message_unpack.py

78 lines
2.7 KiB
Python
Raw Normal View History

2026-07-13 15:37:05 +08:00
import struct
class VdesMessageUnpack:
"""VDES消息解包工具类"""
def __init__(self):
self.message_frames = []
self.current_message = b''
self.is_receiving = False
self.is_unpacked = False #是否解析到结束帧
self.MMSI: int
def unpack_tcp_packet(self, packet_data):
"""解包TCP协议报文"""
# 检查帧头
if packet_data[:4] != b'####':
raise ValueError("无效的报文帧头")
# 解析报文类型和长度
packet_type = struct.unpack('>I', packet_data[4:8])[0]
packet_length = struct.unpack('>I', packet_data[8:12])[0]
packet_content = packet_data[12:]
# 处理不同类型的帧
if packet_type == 10: # 消息帧
# print(f"消息帧内容: {packet_content.hex()}")
frame_type, message = self._process_message_frame(packet_content)
else:
print(f"忽略未知报文类型: {packet_type}")
return None, None
return frame_type, message
def _process_message_frame(self, content):
"""处理消息帧内容"""
# 解析帧类型(1字节)
frame_type = struct.unpack('>B', content[:1])[0]
# print(f"帧类型: {frame_type}")
if frame_type == 0: # 起始帧
self.is_receiving = True
self.current_message = b''
# 解析目标MMSI和优先级
target_mmsi = struct.unpack('>I', content[1:5])[0]
priority = struct.unpack('>B', content[5:6])[0]
self.MMSI = target_mmsi
# print(f"开始接收消息目标MMSI: {target_mmsi}, 优先级: {priority}")
elif frame_type == 1: # 中间帧
if self.is_receiving:
self.current_message = content[1:]
# print(f"接收中间帧,{self.current_message}")
elif frame_type == 2: # 结束帧
if self.is_receiving:
self.current_message = b''
# self.message_frames.append(self.current_message)
self.is_receiving = False
# print(f"消息接收完成,总长度: {len(self.current_message)}字节")
else:
print(f"忽略未知帧类型: {frame_type}")
return frame_type, self.current_message
def get_unpack_statu(self):
"""获取解包状态"""
return self.is_receiving
def get_message_frames(self):
"""获取解包后的消息帧列表"""
return self.message_frames
def get_mmsi(self):
"""获取解包后的消息帧列表"""
return self.MMSI