modbus_pdu.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. """Modbus/TCP 报文编解码(纯函数,便于单元测试与命令行探测工具复用)。
  2. 支持的 PDU 功能码
  3. -----------------
  4. * ``0x03`` 读保持寄存器(PLC → 视觉的指令区)
  5. * ``0x04`` 读输入寄存器(视觉 → PLC 的结果区,本项目的核心数据)
  6. * ``0x06`` 写单个保持寄存器
  7. * ``0x10`` 写多个保持寄存器
  8. MBAP 头:``事务号(2) 协议号(2)=0 长度(2) 单元号(1)``。
  9. """
  10. from __future__ import annotations
  11. import struct
  12. from typing import List, Optional, Sequence, Tuple
  13. __all__ = [
  14. "FC_READ_COILS",
  15. "FC_READ_DISCRETE_INPUTS",
  16. "FC_READ_HOLDING_REGISTERS",
  17. "FC_READ_INPUT_REGISTERS",
  18. "FC_WRITE_MULTIPLE_REGISTERS",
  19. "FC_WRITE_SINGLE_COIL",
  20. "FC_WRITE_SINGLE_REGISTER",
  21. "EXCEPTION_CODES",
  22. "MBAP_HEADER_LEN",
  23. "build_exception_response",
  24. "build_request",
  25. "bytes_to_u16s",
  26. "parse_mbap",
  27. "parse_read_response",
  28. "u16s_to_bytes",
  29. ]
  30. MBAP_HEADER_LEN = 7
  31. FC_READ_COILS = 0x01
  32. FC_READ_DISCRETE_INPUTS = 0x02
  33. FC_READ_HOLDING_REGISTERS = 0x03
  34. FC_READ_INPUT_REGISTERS = 0x04
  35. FC_WRITE_SINGLE_COIL = 0x05
  36. FC_WRITE_SINGLE_REGISTER = 0x06
  37. FC_WRITE_MULTIPLE_REGISTERS = 0x10
  38. EXCEPTION_CODES = {
  39. 0x01: "非法功能码",
  40. 0x02: "非法数据地址",
  41. 0x03: "非法数据值",
  42. 0x04: "从站设备故障",
  43. 0x05: "确认(正在处理)",
  44. 0x06: "设备忙",
  45. }
  46. def parse_mbap(data: bytes) -> Tuple[int, int, int, int, bytes]:
  47. """解析 MBAP + PDU,返回 ``(事务号, 协议号, 长度, 单元号, pdu)``。"""
  48. if len(data) < MBAP_HEADER_LEN:
  49. raise ValueError("报文长度不足: %d" % len(data))
  50. tx_id, proto_id, length, unit_id = struct.unpack(">HHHB", data[:MBAP_HEADER_LEN])
  51. pdu = bytes(data[MBAP_HEADER_LEN:])
  52. if len(pdu) != length - 1:
  53. # 允许 PDU 多带字节(部分网关如此),取 length-1
  54. pdu = pdu[: max(0, length - 1)]
  55. return int(tx_id), int(proto_id), int(length), int(unit_id), pdu
  56. def build_frame(tx_id: int, unit_id: int, pdu: bytes) -> bytes:
  57. """MBAP 封装。``length`` 包含单元号 + PDU。"""
  58. header = struct.pack(">HHHB", int(tx_id) & 0xFFFF, 0, len(pdu) + 1, int(unit_id) & 0xFF)
  59. return header + pdu
  60. def build_request(
  61. tx_id: int,
  62. unit_id: int,
  63. function: int,
  64. address: int,
  65. quantity: Optional[int] = None,
  66. values: Optional[Sequence[int]] = None,
  67. single_value: Optional[int] = None,
  68. ) -> bytes:
  69. """构造客户端请求(本项目的探测工具与测试用)。"""
  70. func = int(function)
  71. if func in (FC_READ_HOLDING_REGISTERS, FC_READ_INPUT_REGISTERS, FC_READ_COILS, FC_READ_DISCRETE_INPUTS):
  72. pdu = struct.pack(">BHH", func, int(address) & 0xFFFF, int(quantity or 1) & 0xFFFF)
  73. elif func == FC_WRITE_SINGLE_REGISTER:
  74. pdu = struct.pack(">BHH", func, int(address) & 0xFFFF, int(single_value or 0) & 0xFFFF)
  75. elif func == FC_WRITE_MULTIPLE_REGISTERS:
  76. words = list(values or [])
  77. payload = struct.pack(">HHB", int(address) & 0xFFFF, len(words), len(words) * 2)
  78. pdu = struct.pack(">B", func) + payload + u16s_to_bytes(words)
  79. else:
  80. raise ValueError("未支持的请求功能码: 0x%02X" % func)
  81. return build_frame(tx_id, unit_id, pdu)
  82. def build_exception_response(tx_id: int, unit_id: int, function: int, code: int) -> bytes:
  83. pdu = struct.pack(">BB", (int(function) | 0x80) & 0xFF, int(code) & 0xFF)
  84. return build_frame(tx_id, unit_id, pdu)
  85. def u16s_to_bytes(words: Sequence[int]) -> bytes:
  86. return b"".join(struct.pack(">H", int(w) & 0xFFFF) for w in words)
  87. def bytes_to_u16s(data: bytes) -> List[int]:
  88. return [int(v) for v in struct.unpack(">%dH" % (len(data) // 2), data[: (len(data) // 2) * 2])]
  89. def parse_read_response(pdu: bytes) -> List[int]:
  90. """解析 ``0x03/0x04`` 响应 PDU → 寄存器列表;异常响应当 :class:`RuntimeError` 抛出。"""
  91. if not pdu:
  92. raise ValueError("空 PDU")
  93. func = pdu[0]
  94. if func & 0x80:
  95. code = pdu[1] if len(pdu) > 1 else 0
  96. raise RuntimeError("Modbus 异常响应: 0x%02X %s" % (code, EXCEPTION_CODES.get(code, "未知")))
  97. if func not in (FC_READ_HOLDING_REGISTERS, FC_READ_INPUT_REGISTERS):
  98. raise ValueError("不是读寄存器响应: 0x%02X" % func)
  99. byte_count = pdu[1]
  100. return bytes_to_u16s(pdu[2 : 2 + byte_count])