53 lines
1.8 KiB
Python
53 lines
1.8 KiB
Python
import time
|
||
import struct
|
||
import logging
|
||
|
||
|
||
class Command04:
|
||
def __init__(self):
|
||
self.pile_id = b"\x00\x27\x02\x12\x34\x56\x12\x34" # 示例桩号
|
||
|
||
def build_04h_disconnect(self, pile_id, reason=0x00):
|
||
"""构建04H断开连接帧"""
|
||
frame = bytearray([0x4A, 0x58]) # 帧头: "JX"
|
||
frame.append(0x04) # 命令码: 04H
|
||
frame.extend(pile_id) # 桩号 (8字节)
|
||
frame.append(0x01) # 数据加密方式: 0x01 (不加密)
|
||
frame.extend([0x00, 0x00]) # 数据域长度 (初始为0,后续更新)
|
||
|
||
# 数据域
|
||
data = bytearray()
|
||
current_time = time.localtime()
|
||
data.extend([
|
||
current_time.tm_year - 2000, current_time.tm_mon, current_time.tm_mday,
|
||
current_time.tm_hour, current_time.tm_min, current_time.tm_sec
|
||
]) # 时间标识 (6字节)
|
||
data.append(reason) # 断开原因 (0x00: 正常断开)
|
||
|
||
frame.extend(data)
|
||
struct.pack_into(">H", frame, 12, len(data)) # 更新数据域长度
|
||
|
||
# 校验码
|
||
checksum = 0
|
||
for b in frame[2:-1]:
|
||
checksum ^= b
|
||
frame.append(checksum)
|
||
|
||
return frame
|
||
|
||
def process_04h(self, data):
|
||
"""处理04H断开连接(由接收方调用)"""
|
||
if data and len(data) >= 20 and data[2] == 0x04:
|
||
pile_id = data[3:11]
|
||
reason = data[20]
|
||
logging.info(f"接收到断开请求,桩号: {pile_id.hex().upper()},原因: {reason:02X}")
|
||
return True
|
||
logging.warning("无效的04H数据")
|
||
return False
|
||
|
||
|
||
if __name__ == "__main__":
|
||
logging.basicConfig(level=logging.INFO)
|
||
cmd = Command04()
|
||
frame = cmd.build_04h_disconnect(b"\x00\x27\x02\x12\x34\x56\x12\x34")
|
||
print(f"04H断开帧: {frame.hex().upper()}") |