|
|
@@ -1,133 +1,244 @@
|
|
|
+"""MODBUS-RTU 协议实现(线架/配线架 V5 协议,20261023)。
|
|
|
+
|
|
|
+V5 关键变化(相对 V4):
|
|
|
+ 1. 取消"广播发现 + 自动分配地址"(00 40 / 00 41 / 00 42 / 00 43) 流程;
|
|
|
+ 地址改由现场用"配置卡"写入线架(DTU 可让线架进入配置地址状态)。
|
|
|
+ 2. DTU 定时按固定地址查询线架:
|
|
|
+ 0x80 查询: [add][0x80][12 字节 UID][CRC_L][CRC_H]
|
|
|
+ - 已绑定地址 -> 携带绑定的 UID
|
|
|
+ - 未绑定地址 -> UID 为 12 字节全 0(探测)
|
|
|
+ 0x81 应答: [add][0x81][12 字节 UID][CRC_L][CRC_H](线架自身 UID)
|
|
|
+ 0x82 确认: [add][0x82][12 字节 UID][CRC_L][CRC_H](DTU 确认绑定)
|
|
|
+ 0x83 应答: [add][0x83][12 字节 UID][CRC_L][CRC_H]
|
|
|
+ 3. 读卡 0x03 回归标准 MODBUS(不再在帧内携带 UID):
|
|
|
+ 请求 8B: [add][0x03][0x00][0x02][0x00][0x48][CRC_L][CRC_H]
|
|
|
+ 响应 149B:[add][0x03][0x90][144 数据字节][CRC_L][CRC_H]
|
|
|
+ 每张卡 6 字节(硬件卡号,12 位十六进制);无卡标记 = FF FF FF FF FF FF
|
|
|
+ 4. 支持让线架进入"配置地址状态"(读配置卡设置地址):
|
|
|
+ 发送: AA B7 00 07 80 00 00 FF 00 00 02 64 03
|
|
|
+ 应答: 55 00 00 02 [ANTLIST] [ADDR] [XOR] 03
|
|
|
+ ANTLIST = 读到配置卡的天线号(1~24),ADDR = 配置的地址
|
|
|
+ XOR = 0x55 起到 ADDR 的异或和
|
|
|
+
|
|
|
+注: 硬件通信固定 6 字节卡号;对 MQTT 的 8 字节(16 位) jumper_uid 适配在 app.py
|
|
|
+ 边界完成(前 4 位 DTU 号 + 后 12 位卡号)。
|
|
|
+"""
|
|
|
from typing import Optional
|
|
|
import threading
|
|
|
+import struct
|
|
|
+import logging
|
|
|
|
|
|
+logger = logging.getLogger('serial_mqtt_gateway')
|
|
|
|
|
|
-# ========== 地址配置协议 ==========
|
|
|
|
|
|
-def build_broadcast_query() -> bytes:
|
|
|
- """构建广播查询指令
|
|
|
+# ========== CRC16 (MODBUS) ==========
|
|
|
|
|
|
- DTU定时发送广播指令查询未配置地址的从机
|
|
|
- 格式: 00 40 00 40 00 (无CRC, 固定5字节)
|
|
|
- """
|
|
|
- return bytes([0x00, 0x40, 0x00, 0x40, 0x00])
|
|
|
+def calculate_crc16(data: bytes) -> bytes:
|
|
|
+ """计算Modbus CRC16校验(低字节在前)"""
|
|
|
+ crc = 0xFFFF
|
|
|
+ for byte in data:
|
|
|
+ crc ^= byte
|
|
|
+ for _ in range(8):
|
|
|
+ if crc & 0x0001:
|
|
|
+ crc = (crc >> 1) ^ 0xA001
|
|
|
+ else:
|
|
|
+ crc >>= 1
|
|
|
+ return struct.pack('<H', crc)
|
|
|
|
|
|
|
|
|
-def parse_device_response(data: bytes, fix_crc: bool = True) -> Optional[dict]:
|
|
|
- """解析从机应答
|
|
|
+def verify_crc16(data: bytes) -> bool:
|
|
|
+ """验证Modbus CRC16校验"""
|
|
|
+ if len(data) < 2:
|
|
|
+ return False
|
|
|
+ received_crc = struct.unpack('<H', data[-2:])[0]
|
|
|
+ calculated_crc = struct.unpack('<H', calculate_crc16(data[:-2]))[0]
|
|
|
+ return received_crc == calculated_crc
|
|
|
|
|
|
- 从机应答格式: 00 + 41 + 12个UID + CRC_L + CRC_H
|
|
|
- 例如: 00 41 18 00 40 00 14 00 00 59 59 54 30 56 AE 34
|
|
|
|
|
|
- fix_crc=True: 当 CRC 不通过但帧头 + UID 有效时,重新计算正确 CRC 补帧,
|
|
|
- 而不是直接拒绝。用于兼容部分从机固件 CRC 计算 bug。
|
|
|
- """
|
|
|
- if len(data) < 16:
|
|
|
- return {'error': '数据长度不足', 'raw_data': data.hex()}
|
|
|
+# ========== V5 地址查询 / 确认协议(0x80 / 0x81 / 0x82 / 0x83) ==========
|
|
|
|
|
|
- if data[1] != 0x41:
|
|
|
- return {'error': f"非预期功能码: {data[1]:#x}", 'raw_data': data.hex()}
|
|
|
+ADDRESS_QUERY_FC = 0x80 # DTU -> 线架:地址查询
|
|
|
+ADDRESS_QUERY_RESP_FC = 0x81 # 线架 -> DTU:查询应答(携带自身 UID)
|
|
|
+ADDRESS_CONFIRM_FC = 0x82 # DTU -> 线架:确认绑定
|
|
|
+ADDRESS_CONFIRM_RESP_FC = 0x83 # 线架 -> DTU:确认应答
|
|
|
+ADDRESS_FRAME_LEN = 16 # add(1)+fc(1)+uid(12)+crc(2)
|
|
|
+ZERO_UID = b'\x00' * 12 # 未绑定地址探测用 UID(12 字节全 0)
|
|
|
+UID_BYTES = 12
|
|
|
|
|
|
- uid_bytes = data[2:14]
|
|
|
- uid_hex = uid_bytes.hex()
|
|
|
|
|
|
- # UID 有效性检查(CRC 之前先做,以便 CRC 失败时也能判断是否补帧)
|
|
|
- from collections import Counter
|
|
|
- zero_count = uid_bytes.count(0)
|
|
|
- counts = Counter(uid_bytes)
|
|
|
- most_common_count = counts.most_common(1)[0][1]
|
|
|
+def _uid_bytes(uid) -> bytes:
|
|
|
+ """把 UID 规范化为 12 字节。None -> 全 0;str/bytes 均可。"""
|
|
|
+ if uid is None:
|
|
|
+ return ZERO_UID
|
|
|
+ if isinstance(uid, str):
|
|
|
+ uid = uid.strip().replace(':', '').replace(' ', '').replace('-', '')
|
|
|
+ try:
|
|
|
+ uid = bytes.fromhex(uid)
|
|
|
+ except ValueError:
|
|
|
+ raise ValueError(f"UID 十六进制非法: {uid!r}")
|
|
|
+ if not isinstance(uid, (bytes, bytearray)):
|
|
|
+ raise ValueError(f"UID 类型非法: {type(uid)}")
|
|
|
+ if len(uid) != UID_BYTES:
|
|
|
+ raise ValueError(f"UID长度必须是{UID_BYTES}字节,当前: {len(uid)}")
|
|
|
+ return bytes(uid)
|
|
|
|
|
|
- uid_looks_valid = (zero_count <= 6) and (most_common_count <= 8)
|
|
|
|
|
|
- crc_ok = verify_crc16(data)
|
|
|
+def build_address_query_request(device_address: int, uid=None) -> bytes:
|
|
|
+ """构建 V5 地址查询请求(0x80,16 字节)。
|
|
|
|
|
|
- if not crc_ok and fix_crc and uid_looks_valid:
|
|
|
- # 补帧:重新计算正确 CRC 替换从机发出的错误 CRC
|
|
|
- original_crc = data[14:16]
|
|
|
- corrected_crc = calculate_crc16(data[:14])
|
|
|
- data = data[:14] + corrected_crc
|
|
|
- logger.warning(
|
|
|
- f"广播响应 CRC 错误,已补帧修正: 原CRC={original_crc.hex()} "
|
|
|
- f"→ 正确CRC={corrected_crc.hex()} (数据={data[:14].hex()})"
|
|
|
- )
|
|
|
- elif not crc_ok:
|
|
|
- return {'error': 'CRC校验失败', 'raw_data': data.hex()}
|
|
|
+ 格式: [add][0x80][12 字节 UID][CRC_L][CRC_H]
|
|
|
+ uid=None 表示 12 字节全 0(未绑定地址探测)。
|
|
|
+
|
|
|
+ 文档示例: 01 80 00*12 54 01
|
|
|
+ """
|
|
|
+ data = bytes([device_address, ADDRESS_QUERY_FC]) + _uid_bytes(uid)
|
|
|
+ return data + calculate_crc16(data)
|
|
|
|
|
|
- if not uid_looks_valid:
|
|
|
- if zero_count > 6:
|
|
|
- return {'error': f"UID中零字节过多({zero_count}/12)", 'raw_data': data.hex()}
|
|
|
- else:
|
|
|
- return {'error': f"UID中单字节重复过多({counts.most_common(1)})", 'raw_data': data.hex()}
|
|
|
|
|
|
+def parse_address_query_response(data: bytes) -> dict:
|
|
|
+ """解析 V5 地址查询应答(0x81,16 字节)。
|
|
|
+
|
|
|
+ 格式: [add][0x81][12 字节 UID][CRC_L][CRC_H]
|
|
|
+ 文档示例: 01 81 51 00 12 00 11 00 00 4C 30 31 33 56 D0 D3
|
|
|
+
|
|
|
+ 返回: {'success': True, 'device_address', 'uid': '24位hex'|None, 'raw_data'}
|
|
|
+ UID 全 0 / 全 FF 视为无效(uid=None)。
|
|
|
+ """
|
|
|
+ if not data or len(data) < ADDRESS_FRAME_LEN:
|
|
|
+ return {'error': '数据长度不足',
|
|
|
+ 'raw_data': data.hex() if data else ''}
|
|
|
+
|
|
|
+ frame = data[:ADDRESS_FRAME_LEN]
|
|
|
+ if frame[1] != ADDRESS_QUERY_RESP_FC:
|
|
|
+ return {'error': f"非预期功能码: {frame[1]:#x}", 'raw_data': frame.hex()}
|
|
|
+ if not verify_crc16(frame):
|
|
|
+ return {'error': 'CRC校验失败', 'raw_data': frame.hex()}
|
|
|
+
|
|
|
+ uid = frame[2:14]
|
|
|
+ valid = uid not in (b'\x00' * 12, b'\xff' * 12)
|
|
|
return {
|
|
|
- 'function_code': 0x41,
|
|
|
- 'uid': uid_hex,
|
|
|
- 'uid_readable': ':'.join(f'{b:02x}' for b in uid_bytes),
|
|
|
- 'source_address': data[0],
|
|
|
- 'raw_data': data.hex()
|
|
|
+ 'success': True,
|
|
|
+ 'device_address': frame[0],
|
|
|
+ 'uid': uid.hex() if valid else None,
|
|
|
+ 'raw_data': frame.hex(),
|
|
|
}
|
|
|
|
|
|
|
|
|
-def build_confirm_address(device_address: int, uid: bytes) -> bytes:
|
|
|
- """构建确认地址指令
|
|
|
+def build_address_confirm_request(device_address: int, uid) -> bytes:
|
|
|
+ """构建 V5 地址确认请求(0x82,16 字节)。
|
|
|
|
|
|
- DTU遍历已存储的UID和地址,如果存在匹配的UID则发送确认指令
|
|
|
- 格式: add + 44 + 00 + 12个UID + CRC_L + CRC_H
|
|
|
+ 格式: [add][0x82][12 字节 UID][CRC_L][CRC_H]
|
|
|
+ 文档示例: 01 82 51 00 12 00 11 00 00 4C 30 31 33 56 D5 10
|
|
|
"""
|
|
|
- if len(uid) != 12:
|
|
|
- raise ValueError(f"UID长度必须是12字节,当前: {len(uid)}")
|
|
|
-
|
|
|
- data = bytes([device_address, 0x44, 0x00]) + uid
|
|
|
+ data = bytes([device_address, ADDRESS_CONFIRM_FC]) + _uid_bytes(uid)
|
|
|
return data + calculate_crc16(data)
|
|
|
|
|
|
|
|
|
-def build_assign_address(uid: bytes, address: int) -> bytes:
|
|
|
- """构建分配地址指令
|
|
|
+def parse_address_confirm_response(data: bytes) -> dict:
|
|
|
+ """解析 V5 地址确认应答(0x83,16 字节)。
|
|
|
|
|
|
- 如果DTU中没有该UID的记录,则分配新地址
|
|
|
- 格式: 00 + 42 + 12个UID + add + CRC_L + CRC_H
|
|
|
+ 格式: [add][0x83][12 字节 UID][CRC_L][CRC_H]
|
|
|
+ 文档示例: 01 83 51 00 12 00 11 00 00 4C 30 31 33 56 D7 91
|
|
|
"""
|
|
|
- if len(uid) != 12:
|
|
|
- raise ValueError(f"UID长度必须是12字节,当前: {len(uid)}")
|
|
|
- if address < 1 or address > 247:
|
|
|
- raise ValueError(f"设备地址必须在1-247之间,当前: {address}")
|
|
|
-
|
|
|
- data = bytes([0x00, 0x42]) + uid + bytes([address])
|
|
|
- return data + calculate_crc16(data)
|
|
|
+ if not data or len(data) < ADDRESS_FRAME_LEN:
|
|
|
+ return {'error': '数据长度不足',
|
|
|
+ 'raw_data': data.hex() if data else ''}
|
|
|
+
|
|
|
+ frame = data[:ADDRESS_FRAME_LEN]
|
|
|
+ if frame[1] != ADDRESS_CONFIRM_RESP_FC:
|
|
|
+ return {'error': f"非预期功能码: {frame[1]:#x}", 'raw_data': frame.hex()}
|
|
|
+ if not verify_crc16(frame):
|
|
|
+ return {'error': 'CRC校验失败', 'raw_data': frame.hex()}
|
|
|
+
|
|
|
+ uid = frame[2:14]
|
|
|
+ valid = uid not in (b'\x00' * 12, b'\xff' * 12)
|
|
|
+ return {
|
|
|
+ 'success': True,
|
|
|
+ 'device_address': frame[0],
|
|
|
+ 'uid': uid.hex() if valid else None,
|
|
|
+ 'raw_data': frame.hex(),
|
|
|
+ }
|
|
|
|
|
|
|
|
|
-def parse_address_assignment_response(data: bytes) -> dict:
|
|
|
- """解析地址分配响应
|
|
|
+# ========== V5 配置地址状态(非 MODBUS 帧,用于刷配置卡设置地址) ==========
|
|
|
+
|
|
|
+# 文档帧: aa b7 00 07 80 00 00 ff 00 00 02 64 03
|
|
|
+# 帧头 AA B7 + 7 字节数据 + 0x64(帧内固定校验/参数, 按文档原样发送) + 0x03 结尾
|
|
|
+CONFIG_ADDRESS_ENTER_FRAME = bytes.fromhex('aab70007800000ff0000026403')
|
|
|
+
|
|
|
+# 应答帧: 55 00 00 02 ANTLIST ADDR XOR 03 (8 字节)
|
|
|
+CONFIG_ADDRESS_RESPONSE_LEN = 8
|
|
|
+CONFIG_ADDRESS_HEADER = 0x55
|
|
|
+CONFIG_ADDRESS_TAIL = 0x03
|
|
|
+
|
|
|
+
|
|
|
+def build_config_address_enter_frame() -> bytes:
|
|
|
+ """让线架进入"配置地址状态"(等待刷配置卡)的广播帧。"""
|
|
|
+ return CONFIG_ADDRESS_ENTER_FRAME
|
|
|
+
|
|
|
+
|
|
|
+def _parse_config_address_frame(frame: bytes) -> Optional[dict]:
|
|
|
+ """解析单个 8 字节配置卡应答帧,失败返回 None。"""
|
|
|
+ if len(frame) < CONFIG_ADDRESS_RESPONSE_LEN:
|
|
|
+ return None
|
|
|
+ head = frame[0]
|
|
|
+ ant = frame[4]
|
|
|
+ addr = frame[5]
|
|
|
+ xor = frame[6]
|
|
|
+ tail = frame[7]
|
|
|
+ if head != CONFIG_ADDRESS_HEADER or tail != CONFIG_ADDRESS_TAIL:
|
|
|
+ return None
|
|
|
+ if not (1 <= ant <= 24) or not (0 <= addr <= 247):
|
|
|
+ return None
|
|
|
+ expect = 0
|
|
|
+ for b in frame[:6]: # XOR = 0x55 起直到 ADDR
|
|
|
+ expect ^= b
|
|
|
+ if expect != xor:
|
|
|
+ return None
|
|
|
+ return {
|
|
|
+ 'success': True,
|
|
|
+ 'antenna': ant,
|
|
|
+ 'address': addr,
|
|
|
+ 'raw_data': frame.hex(),
|
|
|
+ }
|
|
|
|
|
|
- 模块应答格式: add + 43 + 00 + CRC_L + CRC_H
|
|
|
- 例如: 01 43 00 11 30
|
|
|
- """
|
|
|
- if len(data) < 5:
|
|
|
- return {'error': '数据长度不足', 'raw_data': data.hex()}
|
|
|
|
|
|
- device_address = data[0]
|
|
|
+def parse_config_address_response(data: bytes) -> dict:
|
|
|
+ """在收到的数据中查找配置卡应答帧。
|
|
|
|
|
|
- if data[1] != 0x43:
|
|
|
- return {'error': f"非预期功能码: {data[1]:#x}", 'raw_data': data.hex()}
|
|
|
+ 格式: 55 00 00 02 [ANTLIST] [ADDR] [XOR] 03
|
|
|
+ ANTLIST: 读到配置卡的天线号(1 开始)
|
|
|
+ ADDR : 配置的地址
|
|
|
+ XOR : 0x55 起到 ADDR 的异或和
|
|
|
|
|
|
- if not verify_crc16(data):
|
|
|
- logger.warning(f"CRC校验失败: {data.hex()}")
|
|
|
+ 返回 {'success': True, 'antenna', 'address', 'raw_data'} 或 {'error': ...}
|
|
|
+ """
|
|
|
+ if not data:
|
|
|
+ return {'error': '无数据', 'raw_data': ''}
|
|
|
+ if len(data) < CONFIG_ADDRESS_RESPONSE_LEN:
|
|
|
+ return {'error': f'数据长度不足 ({len(data)}/{CONFIG_ADDRESS_RESPONSE_LEN})',
|
|
|
+ 'raw_data': data.hex()}
|
|
|
+ for i in range(len(data) - CONFIG_ADDRESS_RESPONSE_LEN + 1):
|
|
|
+ parsed = _parse_config_address_frame(data[i:i + CONFIG_ADDRESS_RESPONSE_LEN])
|
|
|
+ if parsed:
|
|
|
+ return parsed
|
|
|
+ return {'error': '未找到有效的配置卡应答帧', 'raw_data': data.hex()}
|
|
|
|
|
|
- return {
|
|
|
- 'device_address': device_address,
|
|
|
- 'function_code': 0x43,
|
|
|
- 'raw_data': data.hex()
|
|
|
- }
|
|
|
|
|
|
+# ========== 线架绑定表 / 总线互斥 ==========
|
|
|
|
|
|
class AddressConfigProtocol:
|
|
|
- """地址配置协议处理器"""
|
|
|
+ """线架地址↔UID 绑定表 + 总线配置互斥锁。
|
|
|
+
|
|
|
+ V5 起不再提供广播发现/自动分配地址,仅保留绑定表持久化与
|
|
|
+ "配置地址期间占用总线"的互斥锁。
|
|
|
+ """
|
|
|
|
|
|
def __init__(self, serial_port):
|
|
|
self.serial = serial_port
|
|
|
- self.default_timeout = 5.0 # 设备广播响应可能较慢,给足时间
|
|
|
- self.stored_devices = {}
|
|
|
- self.config_lock = threading.RLock() # 地址配置期间占用,避免与轮询冲突
|
|
|
+ self.default_timeout = 5.0
|
|
|
+ self.stored_devices = {} # {uid_hex: address}
|
|
|
+ self.config_lock = threading.RLock()
|
|
|
|
|
|
def add_stored_device(self, uid: str, address: int):
|
|
|
"""添加已存储的设备"""
|
|
|
@@ -137,156 +248,6 @@ class AddressConfigProtocol:
|
|
|
"""获取已存储的设备列表"""
|
|
|
return self.stored_devices.copy()
|
|
|
|
|
|
- def broadcast_query(self, timeout: float = None) -> list:
|
|
|
- """send broadcast query and collect all valid 00 41 responses"""
|
|
|
- import time
|
|
|
-
|
|
|
- with self.config_lock:
|
|
|
- request = build_broadcast_query()
|
|
|
- logger.info(f"send broadcast: {request.hex()}")
|
|
|
-
|
|
|
- timeout = timeout or self.default_timeout
|
|
|
- # 先清空输入缓冲区,避免残留数据干扰
|
|
|
- self.serial.flush_input()
|
|
|
- time.sleep(0.05)
|
|
|
-
|
|
|
- # 发送广播并等待响应;所有串口操作统一走发送队列,
|
|
|
- # 这里不再额外直接读串口,避免在收集窗口内把后续队列命令的响应抢走。
|
|
|
- response = self.serial.send_and_wait(request, timeout=timeout, min_response_bytes=16)
|
|
|
-
|
|
|
- responses = []
|
|
|
- if response and len(response) >= 16:
|
|
|
- logger.info(f"got raw response ({len(response)}B): {response.hex()}")
|
|
|
- # RS485 半双工会回显已发送的数据,导致 response 开头可能有 5 字节回显
|
|
|
- # 在 response 中搜索所有 00 41 标记,尝试从中提取 16 字节帧解析
|
|
|
- for i in range(len(response) - 15 + 1):
|
|
|
- if response[i] == 0x00 and response[i + 1] == 0x41:
|
|
|
- chunk = response[i:i + 16]
|
|
|
- if len(chunk) >= 16:
|
|
|
- parsed = parse_device_response(chunk)
|
|
|
- if "error" not in parsed:
|
|
|
- if not any(p.get('uid') == parsed['uid'] for p in responses):
|
|
|
- responses.append(parsed)
|
|
|
- else:
|
|
|
- logger.info(f"no response or too short: {len(response) if response else 0}B")
|
|
|
-
|
|
|
- logger.info(f"broadcast done, got {len(responses)} valid unique responses")
|
|
|
- return responses
|
|
|
-
|
|
|
- def _next_available_address(self) -> int:
|
|
|
- """从 1~247 中找一个未被 stored_devices 占用的地址"""
|
|
|
- used = set(self.stored_devices.values())
|
|
|
- for addr in range(1, 248):
|
|
|
- if addr not in used:
|
|
|
- return addr
|
|
|
- raise RuntimeError("Modbus 地址 1~247 已全部占用")
|
|
|
-
|
|
|
- def process_responses(self, responses: list) -> list:
|
|
|
- """处理广播查询响应:给每个应答设备分配地址(优先使用已记录地址)"""
|
|
|
- import time
|
|
|
-
|
|
|
- with self.config_lock:
|
|
|
- results = []
|
|
|
-
|
|
|
- for resp in responses:
|
|
|
- if 'error' in resp:
|
|
|
- results.append({'status': 'error', 'message': resp['error']})
|
|
|
- continue
|
|
|
-
|
|
|
- uid = resp['uid']
|
|
|
- src_addr = resp.get('source_address', 0)
|
|
|
- device_address = self.stored_devices.get(uid)
|
|
|
-
|
|
|
- # 优先使用地址表中已保存的地址;没有则分配下一个可用地址
|
|
|
- if device_address:
|
|
|
- new_address = device_address
|
|
|
- logger.info(f"UID={uid} 源地址={src_addr},地址表存在记录,分配已有地址={new_address}")
|
|
|
- else:
|
|
|
- new_address = self._next_available_address()
|
|
|
- logger.info(f"UID={uid} 源地址={src_addr},地址表无记录,分配新地址={new_address}")
|
|
|
-
|
|
|
- request = build_assign_address(bytes.fromhex(uid), new_address)
|
|
|
- logger.info(f"发送分配地址帧: {request.hex()}")
|
|
|
- self.serial.flush_input()
|
|
|
- time.sleep(0.05)
|
|
|
- success, msg = self.serial.send_raw(request)
|
|
|
- if not success:
|
|
|
- logger.error(f"UID={uid} 分配地址帧发送失败: {msg}")
|
|
|
- results.append({
|
|
|
- 'status': 'error',
|
|
|
- 'uid': uid,
|
|
|
- 'message': f"send failed: {msg}"
|
|
|
- })
|
|
|
- continue
|
|
|
-
|
|
|
- # 等待并解析从机的 43 确认响应
|
|
|
- # 用 wait_response 只读等待:不发空数据(避免前端空JSON)、不清空接收缓冲(避免冲掉43)
|
|
|
- time.sleep(0.1)
|
|
|
- ack = self.serial.wait_response(timeout=0.8, min_response_bytes=5)
|
|
|
- ack_parsed = None
|
|
|
- if ack and len(ack) >= 5:
|
|
|
- # 过滤回显/噪声,找到 43 响应帧
|
|
|
- for i in range(len(ack) - 4):
|
|
|
- if ack[i + 1] == 0x43:
|
|
|
- chunk = ack[i:i + 5]
|
|
|
- ack_parsed = parse_address_assignment_response(chunk)
|
|
|
- break
|
|
|
-
|
|
|
- if ack_parsed and 'error' not in ack_parsed:
|
|
|
- logger.info(f"UID={uid} 地址={new_address} 已确认 (响应: {ack_parsed.get('raw_data')})")
|
|
|
- self.stored_devices[uid] = new_address
|
|
|
- results.append({
|
|
|
- 'status': 'assigned',
|
|
|
- 'uid': uid,
|
|
|
- 'address': new_address,
|
|
|
- 'request': request.hex(),
|
|
|
- 'ack': ack_parsed.get('raw_data')
|
|
|
- })
|
|
|
- else:
|
|
|
- # 即使未收到确认也保存地址:部分从机不返回 43,但实际已生效
|
|
|
- logger.warning(f"UID={uid} 地址={new_address} 未收到 43 确认,仍视为已分配")
|
|
|
- self.stored_devices[uid] = new_address
|
|
|
- results.append({
|
|
|
- 'status': 'assigned',
|
|
|
- 'uid': uid,
|
|
|
- 'address': new_address,
|
|
|
- 'request': request.hex(),
|
|
|
- 'ack': ack.hex() if ack else None
|
|
|
- })
|
|
|
-
|
|
|
- return results
|
|
|
-
|
|
|
- def auto_configure(self, timeout: float = None) -> dict:
|
|
|
- """自动配置所有未配置的设备"""
|
|
|
- with self.config_lock:
|
|
|
- logger.info("开始自动配置设备...")
|
|
|
-
|
|
|
- responses = self.broadcast_query(timeout)
|
|
|
-
|
|
|
- if not responses:
|
|
|
- return {
|
|
|
- 'success': True,
|
|
|
- 'message': '未发现任何从机设备',
|
|
|
- 'discovered': 0,
|
|
|
- 'configured': 0,
|
|
|
- 'results': []
|
|
|
- }
|
|
|
-
|
|
|
- results = self.process_responses(responses)
|
|
|
-
|
|
|
- assigned = sum(1 for r in results if r.get('status') == 'assigned')
|
|
|
- errors = sum(1 for r in results if r.get('status') == 'error')
|
|
|
-
|
|
|
- return {
|
|
|
- 'success': errors == 0,
|
|
|
- 'discovered': len(responses),
|
|
|
- 'confirmed': 0,
|
|
|
- 'assigned': assigned,
|
|
|
- 'errors': errors,
|
|
|
- 'results': results,
|
|
|
- 'stored_devices': self.get_stored_devices()
|
|
|
- }
|
|
|
-
|
|
|
def save_config(self, filepath: str) -> bool:
|
|
|
"""保存配置到文件"""
|
|
|
import json
|
|
|
@@ -309,23 +270,23 @@ class AddressConfigProtocol:
|
|
|
logger.error(f"加载配置失败: {e}")
|
|
|
return False
|
|
|
|
|
|
-# ========== Modbus RTU Client ==========
|
|
|
|
|
|
-# ========== V4 批量读卡协议常量 ==========
|
|
|
-# V4: 一次性批量读 24 路卡号;每张卡 6 字节;无卡标记 6×0xFF。
|
|
|
-# 注: 硬件通信固定 6 字节卡号;对 MQTT 的 8 字节(16 位)适配在 app.py 边界完成
|
|
|
-# (前 4 位 DTU 号 + 后 12 位卡号)。
|
|
|
+# ========== V5 批量读卡 / 设置卡号协议常量 ==========
|
|
|
+
|
|
|
CARD_REG_ADDR = 0x0002 # 批量卡号读起始寄存器
|
|
|
CARD_REG_QUANTITY = 0x48 # 72 寄存器 = 144 字节
|
|
|
CARD_DATA_BYTES = 144 # 24 天线 × 6 字节
|
|
|
BYTES_PER_TAG = 6
|
|
|
ANTENNA_COUNT = 24
|
|
|
-NO_TAG_BYTES = b'\xff' * 6 # V4 无卡标记
|
|
|
+NO_TAG_BYTES = b'\xff' * 6 # 无卡标记
|
|
|
NO_TAG_HEX = 'ffffffffffff'
|
|
|
BULK_BYTE_COUNT = 0x90 # 144,Modbus 响应字节计数字段
|
|
|
+BULK_REQUEST_LEN = 8 # addr(1)+fc(1)+start(2)+qty(2)+crc(2)
|
|
|
BULK_RESPONSE_LEN = 149 # addr(1)+fc(1)+bytecount(1)+data(144)+crc(2)
|
|
|
+# 过渡期兼容:V4 旧固件响应尾部还带 12 字节 UID(161 字节)
|
|
|
+LEGACY_UID_RESPONSE_LEN = 161
|
|
|
|
|
|
-# V4 设置卡号协议常量(非标准 MODBUS 0x10)
|
|
|
+# 设置卡号协议常量(非标准 MODBUS 0x10)
|
|
|
# 协议帧: [addr][0x10][0x00][0x03][0x00][0x90][144字节数据][CRC_L][CRC_H]
|
|
|
# 注意: 与标准 MODBUS 0x10 不同,此处省略 byte count 字段,数量字段 0x0090 直接表示字节数(144)
|
|
|
SET_CARD_REG_ADDR = 0x0003 # 设置卡号起始寄存器
|
|
|
@@ -334,59 +295,18 @@ SET_CARD_DATA_BYTES = 144 # 24 路 × 6 字节
|
|
|
SET_CARD_REQUEST_LEN = 152 # addr(1)+fc(1)+start(2)+qty(2)+data(144)+crc(2)
|
|
|
SET_CARD_RESPONSE_LEN = 8 # addr(1)+fc(1)+start(2)+qty(2)+crc(2)
|
|
|
|
|
|
-# 带 UID 读卡协议(地址段轮询 / 线架绑定)
|
|
|
-# 请求 20B: [addr][0x03][0x00][0x02][0x00][0x48][12 字节 UID][CRC_L][CRC_H]
|
|
|
-# UID = 该地址已绑定的线架 UID;未绑定时为 12 字节全 0(uid=None 探测),
|
|
|
-# 未配置线架收到探测帧后采纳该地址并应答自身 UID,DTU 据此绑定"地址↔UID"。
|
|
|
-# 响应 161B: [addr][0x03][0x90][144 字节卡数据][12 字节 UID][CRC_L][CRC_H]
|
|
|
-# UID = 线架自身 UID(探测响应时用于绑定)。
|
|
|
-READ_WITH_UID_REQUEST_LEN = 20
|
|
|
-READ_WITH_UID_RESPONSE_LEN = 161
|
|
|
-ZERO_UID = b'\x00' * 12
|
|
|
-
|
|
|
# 天线地址映射表(天线编号 -> Modbus寄存器地址)
|
|
|
-# V4: 所有天线共享寄存器 0x0002,由 read_all_antenna_cards 一次批量读出
|
|
|
+# 所有天线共享寄存器 0x0002,由 read_all_antenna_cards 一次批量读出
|
|
|
ANTENNA_ADDRESSES = {i: CARD_REG_ADDR for i in range(1, 25)}
|
|
|
|
|
|
-import struct
|
|
|
-import logging
|
|
|
-
|
|
|
-logger = logging.getLogger('serial_mqtt_gateway')
|
|
|
|
|
|
+def build_read_cards_request(device_address: int) -> bytes:
|
|
|
+ """构建 V5 批量读卡请求(标准 MODBUS 0x03,8 字节)。
|
|
|
|
|
|
-def calculate_crc16(data: bytes) -> bytes:
|
|
|
- """计算Modbus CRC16校验"""
|
|
|
- crc = 0xFFFF
|
|
|
- for byte in data:
|
|
|
- crc ^= byte
|
|
|
- for _ in range(8):
|
|
|
- if crc & 0x0001:
|
|
|
- crc = (crc >> 1) ^ 0xA001
|
|
|
- else:
|
|
|
- crc >>= 1
|
|
|
- return struct.pack('<H', crc)
|
|
|
-
|
|
|
-
|
|
|
-def verify_crc16(data: bytes) -> bool:
|
|
|
- """验证Modbus CRC16校验"""
|
|
|
- if len(data) < 2:
|
|
|
- return False
|
|
|
- received_crc = struct.unpack('<H', data[-2:])[0]
|
|
|
- calculated_crc = struct.unpack('<H', calculate_crc16(data[:-2]))[0]
|
|
|
- return received_crc == calculated_crc
|
|
|
-
|
|
|
-
|
|
|
-def build_read_cards_request(device_address: int, uid: Optional[bytes] = None) -> bytes:
|
|
|
- """构建带 UID 的 V4 批量读卡请求(20 字节)。
|
|
|
-
|
|
|
- 格式: [addr][0x03][0x00][0x02][0x00][0x48][12 字节 UID][CRC_L][CRC_H]
|
|
|
- uid=None 表示 12 字节全 0 探测(未绑定地址;未配置线架会采纳该地址)。
|
|
|
+ 格式: [add][0x03][0x00][0x02][0x00][0x48][CRC_L][CRC_H]
|
|
|
+ 文档示例: 01 03 00 02 00 48 E4 3C
|
|
|
"""
|
|
|
- if uid is None:
|
|
|
- uid = ZERO_UID
|
|
|
- if len(uid) != 12:
|
|
|
- raise ValueError(f"UID长度必须是12字节,当前: {len(uid)}")
|
|
|
- data = bytes([device_address, 0x03]) + struct.pack('>HH', CARD_REG_ADDR, CARD_REG_QUANTITY) + bytes(uid)
|
|
|
+ data = bytes([device_address, 0x03]) + struct.pack('>HH', CARD_REG_ADDR, CARD_REG_QUANTITY)
|
|
|
return data + calculate_crc16(data)
|
|
|
|
|
|
|
|
|
@@ -397,7 +317,7 @@ class ModbusRTUClient:
|
|
|
self.serial = serial_port
|
|
|
self.default_timeout = 2.0
|
|
|
self.test_cards = None # 测试注入:非 None 时 read_all_antenna_cards 返回构造数据
|
|
|
- self.test_panel_uids = None # 测试注入:{addr: 'hex24'} 模拟线架自身 UID
|
|
|
+ self.test_panel_uids = None # 测试注入:{addr: 'hex24'} 模拟线架自身 UID(query_address 用)
|
|
|
|
|
|
def _build_request(self, device_address: int, function_code: int, data: bytes = b'') -> bytes:
|
|
|
"""构建Modbus请求帧"""
|
|
|
@@ -428,26 +348,87 @@ class ModbusRTUClient:
|
|
|
"raw_data": response.hex()
|
|
|
}
|
|
|
|
|
|
- def read_all_antenna_cards(self, device_address: int, uid: Optional[bytes] = None, timeout: float = None) -> dict:
|
|
|
- """V4+: 带 UID 的批量读取全部 24 路天线卡号。
|
|
|
+ # ----- V5 地址查询 / 确认 -----
|
|
|
+
|
|
|
+ def query_address(self, device_address: int, uid=None, timeout: float = None) -> dict:
|
|
|
+ """V5 地址查询(0x80)。
|
|
|
+
|
|
|
+ Args:
|
|
|
+ device_address: 要查询的固定地址
|
|
|
+ uid: 已绑定的 UID(str/bytes);None -> 12 字节全 0 探测
|
|
|
+ Returns:
|
|
|
+ {'success': True, 'device_address', 'uid': '24位hex'|None, 'raw_data'}
|
|
|
+ 或 {'error': ...}
|
|
|
+ """
|
|
|
+ if self.test_panel_uids is not None:
|
|
|
+ # 测试注入:按地址返回模拟线架 UID(未列出的地址视为无应答)
|
|
|
+ simulated = self.test_panel_uids.get(device_address)
|
|
|
+ if simulated is None:
|
|
|
+ return {"error": "response timeout or too short", "raw_data": ""}
|
|
|
+ return {
|
|
|
+ "success": True,
|
|
|
+ "device_address": device_address,
|
|
|
+ "uid": str(simulated).lower(),
|
|
|
+ "raw_data": "TEST_INJECTED",
|
|
|
+ }
|
|
|
+
|
|
|
+ timeout = timeout or self.default_timeout
|
|
|
+ if not self.serial.ser:
|
|
|
+ return {"error": "serial not connected"}
|
|
|
+
|
|
|
+ try:
|
|
|
+ request = build_address_query_request(device_address, uid)
|
|
|
+ except ValueError as e:
|
|
|
+ return {"error": str(e)}
|
|
|
+
|
|
|
+ response = self.serial.send_and_wait(
|
|
|
+ request, timeout=timeout, min_response_bytes=ADDRESS_FRAME_LEN
|
|
|
+ )
|
|
|
+ if not response:
|
|
|
+ return {"error": "response timeout or too short", "raw_data": ""}
|
|
|
+ return parse_address_query_response(response)
|
|
|
+
|
|
|
+ def confirm_address(self, device_address: int, uid, timeout: float = None) -> dict:
|
|
|
+ """V5 地址确认(0x82):DTU 确认"地址↔UID"绑定。"""
|
|
|
+ if self.test_panel_uids is not None:
|
|
|
+ return {"success": True, "device_address": device_address,
|
|
|
+ "uid": str(uid).lower() if uid else None, "raw_data": "TEST_INJECTED"}
|
|
|
+
|
|
|
+ timeout = timeout or self.default_timeout
|
|
|
+ if not self.serial.ser:
|
|
|
+ return {"error": "serial not connected"}
|
|
|
+
|
|
|
+ try:
|
|
|
+ request = build_address_confirm_request(device_address, uid)
|
|
|
+ except ValueError as e:
|
|
|
+ return {"error": str(e)}
|
|
|
+
|
|
|
+ response = self.serial.send_and_wait(
|
|
|
+ request, timeout=timeout, min_response_bytes=ADDRESS_FRAME_LEN
|
|
|
+ )
|
|
|
+ if not response:
|
|
|
+ return {"error": "response timeout or too short", "raw_data": ""}
|
|
|
+ return parse_address_confirm_response(response)
|
|
|
+
|
|
|
+ # ----- V5 批量读卡 -----
|
|
|
+
|
|
|
+ def read_all_antenna_cards(self, device_address: int, timeout: float = None) -> dict:
|
|
|
+ """V5: 批量读取全部 24 路天线卡号(标准 MODBUS 0x03)。
|
|
|
|
|
|
寄存器 0x0002,数量 0x48(72 寄存器 = 144 字节)。
|
|
|
- 请求 20B: [addr][0x03][0x00][0x02][0x00][0x48][12 字节 UID][CRC_L][CRC_H]
|
|
|
- uid=None 表示 12 字节全 0 探测(未绑定地址探测/换架接管用)。
|
|
|
- 响应 161B: [addr][0x03][0x90][144 数据字节][12 字节 UID][CRC_L][CRC_H]
|
|
|
- 响应 UID = 线架自身 UID(未绑定/换架时用于绑定)。
|
|
|
+ 请求 8B: [addr][0x03][0x00][0x02][0x00][0x48][CRC_L][CRC_H]
|
|
|
+ 响应 149B:[addr][0x03][0x90][144 数据字节][CRC_L][CRC_H]
|
|
|
每张卡 6 字节(硬件卡号,12 位十六进制);无卡标记 = 6×0xFF。
|
|
|
- MQTT 侧的 8 字节(16 位) jumper_uid 适配在 app.py 边界完成。
|
|
|
|
|
|
- 过渡期兼容: 旧固件 149B 响应仍可解析(panel_uid=None 仅作诊断),不能用于绑定。
|
|
|
+ 过渡期兼容: V4 旧固件 161B 响应(尾部多 12 字节 UID)仍可解析,
|
|
|
+ UID 字段在此层忽略(地址↔UID 绑定走 0x80/0x82 查询确认)。
|
|
|
|
|
|
返回:
|
|
|
{'success': True, 'device_address', 'function_code': 0x03,
|
|
|
'cards': [{'antenna', 'card_str', 'present', 'uid'}, ...24],
|
|
|
- 'panel_uid': '24位hex'|None, 'raw_data'}
|
|
|
+ 'raw_data'}
|
|
|
"""
|
|
|
# 测试注入: test_cards = {addr: {port_id: 'hex12'|None, ...}, ...}
|
|
|
- # test_panel_uids = {addr: 'hex24'}(可选, 模拟线架自身 UID)
|
|
|
if self.test_cards is not None:
|
|
|
panel_map = self.test_cards.get(device_address)
|
|
|
if panel_map is not None:
|
|
|
@@ -472,7 +453,6 @@ class ModbusRTUClient:
|
|
|
"device_address": device_address,
|
|
|
"function_code": 0x03,
|
|
|
"cards": cards,
|
|
|
- "panel_uid": (self.test_panel_uids or {}).get(device_address),
|
|
|
"raw_data": "TEST_INJECTED"
|
|
|
}
|
|
|
|
|
|
@@ -481,14 +461,9 @@ class ModbusRTUClient:
|
|
|
if not self.serial.ser:
|
|
|
return {"error": "serial not connected"}
|
|
|
|
|
|
- try:
|
|
|
- request = build_read_cards_request(device_address, uid)
|
|
|
- except ValueError as e:
|
|
|
- return {"error": str(e)}
|
|
|
-
|
|
|
- # 直调 send_and_wait 并要求完整 161 字节(或旧格式 149 字节)
|
|
|
+ request = build_read_cards_request(device_address)
|
|
|
response = self.serial.send_and_wait(
|
|
|
- request, timeout=timeout, min_response_bytes=READ_WITH_UID_RESPONSE_LEN
|
|
|
+ request, timeout=timeout, min_response_bytes=BULK_RESPONSE_LEN
|
|
|
)
|
|
|
|
|
|
if not response or len(response) < 5:
|
|
|
@@ -500,22 +475,21 @@ class ModbusRTUClient:
|
|
|
return {"error": f"Modbus exception: {response[2]:#x}",
|
|
|
"raw_data": response.hex()}
|
|
|
|
|
|
- panel_uid = None
|
|
|
- if len(response) >= READ_WITH_UID_RESPONSE_LEN:
|
|
|
- frame = response[:READ_WITH_UID_RESPONSE_LEN]
|
|
|
- raw_uid = frame[3 + CARD_DATA_BYTES:3 + CARD_DATA_BYTES + 12]
|
|
|
- panel_uid = raw_uid.hex() if raw_uid != ZERO_UID else None
|
|
|
- elif len(response) >= BULK_RESPONSE_LEN:
|
|
|
- # 过渡期兼容:旧固件 149B 响应(无 UID 字段)
|
|
|
- logger.warning("收到旧格式(149B)批量读卡响应,无 UID 字段,无法用于线架绑定")
|
|
|
+ frame = None
|
|
|
+ if (len(response) >= BULK_RESPONSE_LEN
|
|
|
+ and response[1] == 0x03 and response[2] == BULK_BYTE_COUNT
|
|
|
+ and verify_crc16(response[:BULK_RESPONSE_LEN])):
|
|
|
+ frame = response[:BULK_RESPONSE_LEN]
|
|
|
+ elif len(response) >= LEGACY_UID_RESPONSE_LEN and verify_crc16(
|
|
|
+ response[:LEGACY_UID_RESPONSE_LEN]):
|
|
|
+ # 过渡期兼容:V4 旧固件 161B 响应(无 UID 使用价值,仅解析卡数据)
|
|
|
+ logger.debug("收到旧格式(161B)批量读卡响应,UID 字段已忽略")
|
|
|
frame = response[:BULK_RESPONSE_LEN]
|
|
|
else:
|
|
|
- return {"error": f"response too short ({len(response)}/{READ_WITH_UID_RESPONSE_LEN})",
|
|
|
- "raw_data": response.hex()}
|
|
|
-
|
|
|
- if not verify_crc16(frame):
|
|
|
- logger.warning(f"CRC check failed: {frame.hex()}")
|
|
|
- return {"error": "CRC check failed", "raw_data": frame.hex()}
|
|
|
+ if len(response) < BULK_RESPONSE_LEN:
|
|
|
+ return {"error": f"response too short ({len(response)}/{BULK_RESPONSE_LEN})",
|
|
|
+ "raw_data": response.hex()}
|
|
|
+ return {"error": "CRC check failed", "raw_data": response.hex()}
|
|
|
|
|
|
if frame[1] != 0x03 or frame[2] != BULK_BYTE_COUNT:
|
|
|
return {"error": f"unexpected response: fc={frame[1]:#x} count={frame[2]:#x}",
|
|
|
@@ -539,15 +513,14 @@ class ModbusRTUClient:
|
|
|
"device_address": frame[0],
|
|
|
"function_code": 0x03,
|
|
|
"cards": cards,
|
|
|
- "panel_uid": panel_uid,
|
|
|
"raw_data": frame.hex()
|
|
|
}
|
|
|
|
|
|
def read_antenna_card(self, device_address: int, antenna_num: int, timeout: float = None) -> dict:
|
|
|
- """读取单根天线卡号(V4: 由批量读提取,不再发 V2 逐天线帧)。
|
|
|
+ """读取单根天线卡号(由批量读提取,不再发逐天线帧)。
|
|
|
|
|
|
调用 read_all_antenna_cards 后提取指定天线,返回兼容 schema。
|
|
|
- 无卡时 card_number_str 为空串(V2 是 '0000000000000000')。
|
|
|
+ 无卡时 card_number_str 为空串。
|
|
|
"""
|
|
|
if antenna_num < 1 or antenna_num > ANTENNA_COUNT:
|
|
|
return {"error": f"invalid antenna number: {antenna_num}, must be 1-{ANTENNA_COUNT}"}
|
|
|
@@ -583,7 +556,7 @@ class ModbusRTUClient:
|
|
|
}
|
|
|
|
|
|
def set_card_mapping(self, device_address: int, card_mappings: dict, timeout: float = None) -> dict:
|
|
|
- """V4: 设置24路天线卡号(0x10 写 0x0003,144字节,非标准MODBUS无bytecount)。
|
|
|
+ """设置24路天线卡号(0x10 写 0x0003,144字节,非标准MODBUS无bytecount)。
|
|
|
|
|
|
协议帧(发送): [addr][0x10][0x00][0x03][0x00][0x90][144字节数据][CRC_L][CRC_H]
|
|
|
协议帧(响应): [addr][0x10][0x00][0x03][0x00][0x90][CRC_L][CRC_H]
|