"""Modbus/TCP 报文编解码(纯函数,便于单元测试与命令行探测工具复用)。 支持的 PDU 功能码 ----------------- * ``0x03`` 读保持寄存器(PLC → 视觉的指令区) * ``0x04`` 读输入寄存器(视觉 → PLC 的结果区,本项目的核心数据) * ``0x06`` 写单个保持寄存器 * ``0x10`` 写多个保持寄存器 MBAP 头:``事务号(2) 协议号(2)=0 长度(2) 单元号(1)``。 """ from __future__ import annotations import struct from typing import List, Optional, Sequence, Tuple __all__ = [ "FC_READ_COILS", "FC_READ_DISCRETE_INPUTS", "FC_READ_HOLDING_REGISTERS", "FC_READ_INPUT_REGISTERS", "FC_WRITE_MULTIPLE_REGISTERS", "FC_WRITE_SINGLE_COIL", "FC_WRITE_SINGLE_REGISTER", "EXCEPTION_CODES", "MBAP_HEADER_LEN", "build_exception_response", "build_request", "bytes_to_u16s", "parse_mbap", "parse_read_response", "u16s_to_bytes", ] MBAP_HEADER_LEN = 7 FC_READ_COILS = 0x01 FC_READ_DISCRETE_INPUTS = 0x02 FC_READ_HOLDING_REGISTERS = 0x03 FC_READ_INPUT_REGISTERS = 0x04 FC_WRITE_SINGLE_COIL = 0x05 FC_WRITE_SINGLE_REGISTER = 0x06 FC_WRITE_MULTIPLE_REGISTERS = 0x10 EXCEPTION_CODES = { 0x01: "非法功能码", 0x02: "非法数据地址", 0x03: "非法数据值", 0x04: "从站设备故障", 0x05: "确认(正在处理)", 0x06: "设备忙", } def parse_mbap(data: bytes) -> Tuple[int, int, int, int, bytes]: """解析 MBAP + PDU,返回 ``(事务号, 协议号, 长度, 单元号, pdu)``。""" if len(data) < MBAP_HEADER_LEN: raise ValueError("报文长度不足: %d" % len(data)) tx_id, proto_id, length, unit_id = struct.unpack(">HHHB", data[:MBAP_HEADER_LEN]) pdu = bytes(data[MBAP_HEADER_LEN:]) if len(pdu) != length - 1: # 允许 PDU 多带字节(部分网关如此),取 length-1 pdu = pdu[: max(0, length - 1)] return int(tx_id), int(proto_id), int(length), int(unit_id), pdu def build_frame(tx_id: int, unit_id: int, pdu: bytes) -> bytes: """MBAP 封装。``length`` 包含单元号 + PDU。""" header = struct.pack(">HHHB", int(tx_id) & 0xFFFF, 0, len(pdu) + 1, int(unit_id) & 0xFF) return header + pdu def build_request( tx_id: int, unit_id: int, function: int, address: int, quantity: Optional[int] = None, values: Optional[Sequence[int]] = None, single_value: Optional[int] = None, ) -> bytes: """构造客户端请求(本项目的探测工具与测试用)。""" func = int(function) if func in (FC_READ_HOLDING_REGISTERS, FC_READ_INPUT_REGISTERS, FC_READ_COILS, FC_READ_DISCRETE_INPUTS): pdu = struct.pack(">BHH", func, int(address) & 0xFFFF, int(quantity or 1) & 0xFFFF) elif func == FC_WRITE_SINGLE_REGISTER: pdu = struct.pack(">BHH", func, int(address) & 0xFFFF, int(single_value or 0) & 0xFFFF) elif func == FC_WRITE_MULTIPLE_REGISTERS: words = list(values or []) payload = struct.pack(">HHB", int(address) & 0xFFFF, len(words), len(words) * 2) pdu = struct.pack(">B", func) + payload + u16s_to_bytes(words) else: raise ValueError("未支持的请求功能码: 0x%02X" % func) return build_frame(tx_id, unit_id, pdu) def build_exception_response(tx_id: int, unit_id: int, function: int, code: int) -> bytes: pdu = struct.pack(">BB", (int(function) | 0x80) & 0xFF, int(code) & 0xFF) return build_frame(tx_id, unit_id, pdu) def u16s_to_bytes(words: Sequence[int]) -> bytes: return b"".join(struct.pack(">H", int(w) & 0xFFFF) for w in words) def bytes_to_u16s(data: bytes) -> List[int]: return [int(v) for v in struct.unpack(">%dH" % (len(data) // 2), data[: (len(data) // 2) * 2])] def parse_read_response(pdu: bytes) -> List[int]: """解析 ``0x03/0x04`` 响应 PDU → 寄存器列表;异常响应当 :class:`RuntimeError` 抛出。""" if not pdu: raise ValueError("空 PDU") func = pdu[0] if func & 0x80: code = pdu[1] if len(pdu) > 1 else 0 raise RuntimeError("Modbus 异常响应: 0x%02X %s" % (code, EXCEPTION_CODES.get(code, "未知"))) if func not in (FC_READ_HOLDING_REGISTERS, FC_READ_INPUT_REGISTERS): raise ValueError("不是读寄存器响应: 0x%02X" % func) byte_count = pdu[1] return bytes_to_u16s(pdu[2 : 2 + byte_count])