test_modbus_server.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. """Modbus/TCP 从站(``ModbusTcpServer``)测试:先测纯报文路径,再测真 socket 往返。"""
  2. import socket
  3. import time
  4. import unittest
  5. from portcv.plc import ModbusTcpServer, registers
  6. from portcv.plc import modbus_pdu as pdu
  7. from portcv.plc.modbus_pdu import (
  8. FC_READ_HOLDING_REGISTERS,
  9. FC_READ_INPUT_REGISTERS,
  10. FC_WRITE_MULTIPLE_REGISTERS,
  11. FC_WRITE_SINGLE_REGISTER,
  12. )
  13. from portcv.schema import PlcCommand, SceneState, StatusBits, VisionSnapshot
  14. def make_snapshot(heartbeat: int = 7) -> VisionSnapshot:
  15. return VisionSnapshot(
  16. state=int(SceneState.BED),
  17. confidence=912,
  18. flags=int(StatusBits.READY | StatusBits.FRAME_OK | StatusBits.STABLE),
  19. seq=3,
  20. ts_s=1700000000,
  21. heartbeat=heartbeat,
  22. fps_x10=152,
  23. latency_ms=41,
  24. )
  25. def recv_exact(sock: socket.socket, size: int, timeout: float = 3.0) -> bytes:
  26. """读满 ``size`` 字节(服务端可能分片发送)。"""
  27. sock.settimeout(timeout)
  28. chunks = b""
  29. while len(chunks) < size:
  30. piece = sock.recv(size - len(chunks))
  31. if not piece:
  32. break
  33. chunks += piece
  34. return chunks
  35. def recv_frame(sock: socket.socket) -> bytes:
  36. """按 MBAP 长度字段读一个完整帧。"""
  37. header = recv_exact(sock, pdu.MBAP_HEADER_LEN)
  38. if len(header) < pdu.MBAP_HEADER_LEN:
  39. return b""
  40. length = int.from_bytes(header[4:6], "big")
  41. return header + recv_exact(sock, max(0, length - 1))
  42. class ServerProtocolTests(unittest.TestCase):
  43. """直接调用 ``handle_frame``:不占端口,跑得快,覆盖各异常分支。"""
  44. def setUp(self):
  45. self.commands = []
  46. self.server = ModbusTcpServer(
  47. host="127.0.0.1",
  48. port=0,
  49. unit_id=1,
  50. on_command=lambda words, peer: self.commands.append((list(words), peer)),
  51. )
  52. def tearDown(self):
  53. self.server.server_close()
  54. def _request(
  55. self, function: int, address: int = 0, quantity: int = 12, tx: int = 1, unit: int = 1, **kwargs
  56. ):
  57. frame = pdu.build_request(tx, unit, function, address, quantity=quantity, **kwargs)
  58. response = self.server.handle_frame(frame, "test")
  59. if not response:
  60. return b""
  61. return pdu.parse_mbap(response)[4]
  62. def test_snapshot_readback_over_fc4(self):
  63. snapshot = make_snapshot()
  64. self.server.set_snapshot(snapshot)
  65. body = self._request(FC_READ_INPUT_REGISTERS, quantity=12)
  66. self.assertEqual(body[0], FC_READ_INPUT_REGISTERS)
  67. words = pdu.parse_read_response(body)
  68. self.assertEqual(len(words), VisionSnapshot.register_count())
  69. self.assertEqual(registers.decode_snapshot(words), snapshot)
  70. self.assertEqual(self.server.input_registers(), words)
  71. def test_partial_block_read(self):
  72. self.server.set_snapshot(make_snapshot())
  73. words = pdu.parse_read_response(self._request(FC_READ_INPUT_REGISTERS, address=5, quantity=4))
  74. self.assertEqual(words, self.server.input_registers()[5:9])
  75. def test_read_holding_registers(self):
  76. self.server.set_holding_registers([1, 2, 700, 0])
  77. body = self._request(FC_READ_HOLDING_REGISTERS, quantity=4)
  78. self.assertEqual(pdu.parse_read_response(body), [1, 2, 700, 0])
  79. def test_illegal_address_returns_exception_02(self):
  80. body = self._request(FC_READ_INPUT_REGISTERS, address=100, quantity=12)
  81. self.assertEqual(body, bytes([0x84, 0x02]))
  82. self.assertGreaterEqual(self.server.stats["errors"], 1)
  83. def test_illegal_quantity_returns_exception_03(self):
  84. self.assertEqual(self._request(FC_READ_INPUT_REGISTERS, quantity=200), bytes([0x84, 0x03]))
  85. def test_write_single_updates_command_and_notifies(self):
  86. body = self._request(FC_WRITE_SINGLE_REGISTER, single_value=int(registers.CMD_REQUEST))
  87. self.assertEqual(body, bytes([FC_WRITE_SINGLE_REGISTER, 0x00, 0x00, 0x00, 0x01]))
  88. self.assertTrue(self.server.command().is_request())
  89. self.assertEqual(len(self.commands), 1)
  90. self.assertEqual(self.commands[0][1], "test")
  91. self.assertEqual(self.commands[0][0], [1, 0, 0, 0])
  92. def test_write_multiple_sets_all_command_words(self):
  93. body = self._request(
  94. FC_WRITE_MULTIPLE_REGISTERS, values=[int(registers.CMD_RESET), 3, 700, 0]
  95. )
  96. self.assertEqual(body, bytes([0x10, 0x00, 0x00, 0x00, 0x04]))
  97. self.assertEqual(self.server.command(), PlcCommand(cmd=2, preset=3, min_conf=700, reserved=0))
  98. self.assertTrue(self.commands)
  99. def test_write_out_of_range_address_returns_exception_02(self):
  100. body = self._request(FC_WRITE_SINGLE_REGISTER, address=9, single_value=1)
  101. self.assertEqual(body, bytes([0x86, 0x02]))
  102. def test_write_multiple_wrong_byte_count_returns_exception_03(self):
  103. # 手工构造:数量 2 但字节数写成 2(应为 4)
  104. raw = bytes(
  105. [0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x01, 0x10, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00, 0x01]
  106. )
  107. body = pdu.parse_mbap(self.server.handle_frame(raw, "test"))[4]
  108. self.assertEqual(body, bytes([0x90, 0x03]))
  109. def test_write_multiple_short_payload_returns_exception_02(self):
  110. # byte_count 自洽(4)但只给了 1 个字:按 `len(values) < quantity` 判非法
  111. # 地址(0x02),与 C++ `handle_frame` 同口径;且不得把缺失字节补 0 写入。
  112. raw = bytes(
  113. [0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x01, 0x10, 0x00, 0x00, 0x00, 0x02, 0x04, 0x00, 0x01]
  114. )
  115. body = pdu.parse_mbap(self.server.handle_frame(raw, "test"))[4]
  116. self.assertEqual(body, bytes([0x90, 0x02]))
  117. self.assertEqual(self.server.holding_registers(), [0, 0, 0, 0])
  118. def test_unsupported_function_returns_illegal_function(self):
  119. raw = pdu.build_frame(7, 1, b"\x08\x00\x00\x00\x01")
  120. body = pdu.parse_mbap(self.server.handle_frame(raw, "test"))[4]
  121. self.assertEqual(body, bytes([0x88, 0x01]))
  122. def test_short_frame_is_ignored(self):
  123. self.assertEqual(self.server.handle_frame(b"\x01\x02\x03", "test"), b"")
  124. def test_wrong_protocol_id_returns_exception_03(self):
  125. raw = bytes([0x00, 0x01, 0x00, 0x01, 0x00, 0x06, 0x01, 0x04, 0x00, 0x00, 0x00, 0x0C])
  126. body = pdu.parse_mbap(self.server.handle_frame(raw, "test"))[4]
  127. self.assertEqual(body, bytes([0x84, 0x03]))
  128. def test_strict_unit_id_drops_foreign_requests(self):
  129. strict = ModbusTcpServer(host="127.0.0.1", port=0, unit_id=3, allow_unit_any=False)
  130. try:
  131. foreign = pdu.build_request(1, 9, FC_READ_INPUT_REGISTERS, 0, quantity=12)
  132. self.assertEqual(strict.handle_frame(foreign, "x"), b"")
  133. mine = pdu.build_request(2, 3, FC_READ_INPUT_REGISTERS, 0, quantity=12)
  134. self.assertTrue(strict.handle_frame(mine, "x"))
  135. finally:
  136. strict.server_close()
  137. def test_any_unit_id_is_echoed(self):
  138. # allow_unit_any=True(默认)时接受任意站点号,但响应必须回显请求的 unit_id;
  139. # 不能归一化成配置里的 1,否则西门子 MB_CLIENT 会丢弃响应。
  140. frame = pdu.build_request(1, 42, FC_READ_INPUT_REGISTERS, 0, quantity=4)
  141. tx, _proto, _len, unit, body = pdu.parse_mbap(self.server.handle_frame(frame, "test"))
  142. self.assertEqual((tx, unit), (1, 42))
  143. self.assertEqual(len(pdu.parse_read_response(body)), 4)
  144. class ServerSocketTests(unittest.TestCase):
  145. """真 socket 往返:验证线程化服务端 + MBAP 分帧 + 统计。"""
  146. def test_tcp_roundtrip(self):
  147. snapshot = make_snapshot(heartbeat=123)
  148. server = ModbusTcpServer(host="127.0.0.1", port=0, unit_id=1)
  149. server.set_snapshot(snapshot)
  150. server.start()
  151. try:
  152. port = int(server.server_address[1])
  153. with socket.create_connection(("127.0.0.1", port), timeout=3.0) as sock:
  154. sock.sendall(pdu.build_request(0x11, 1, FC_READ_INPUT_REGISTERS, 0, quantity=12))
  155. tx, _proto, _len, unit, body = pdu.parse_mbap(recv_frame(sock))
  156. self.assertEqual((tx, unit), (0x11, 1))
  157. self.assertEqual(registers.decode_snapshot(pdu.parse_read_response(body)), snapshot)
  158. sock.sendall(pdu.build_request(0x12, 1, FC_WRITE_SINGLE_REGISTER, 0, single_value=2))
  159. _tx, _proto, _len, _unit, body = pdu.parse_mbap(recv_frame(sock))
  160. self.assertEqual(body, bytes([0x06, 0x00, 0x00, 0x00, 0x02]))
  161. self.assertTrue(server.command().is_reset())
  162. finally:
  163. server.stop()
  164. deadline = time.time() + 1.0
  165. while server.client_count and time.time() < deadline:
  166. time.sleep(0.02)
  167. self.assertTrue(server.is_stopping())
  168. self.assertGreaterEqual(server.stats["reads"], 1)
  169. self.assertGreaterEqual(server.stats["writes"], 1)
  170. self.assertEqual(server.client_count, 0)
  171. def test_invalid_mbap_length_closes_connection(self):
  172. # length=0(连 unit_id 都没有)与 length=65535(超长)都属非法:
  173. # 服务端必须立刻断连,不能等 30 s 超时(慢速攻击 / 网关错位报文),
  174. # 也不能按 64 KB 去缓冲。与 C++ service_client 的 2..254 同口径。
  175. server = ModbusTcpServer(host="127.0.0.1", port=0, unit_id=1)
  176. server.start()
  177. try:
  178. port = int(server.server_address[1])
  179. for length in (0, 65535):
  180. with socket.create_connection(("127.0.0.1", port), timeout=3.0) as sock:
  181. sock.sendall(
  182. bytes([0x00, 0x01, 0x00, 0x00, (length >> 8) & 0xFF, length & 0xFF, 0x01])
  183. )
  184. sock.settimeout(3.0)
  185. self.assertEqual(sock.recv(1), b"", "非法 length=%d:服务端应断连" % length)
  186. finally:
  187. server.stop()
  188. if __name__ == "__main__":
  189. unittest.main()