| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227 |
- """Modbus/TCP 从站(``ModbusTcpServer``)测试:先测纯报文路径,再测真 socket 往返。"""
- import socket
- import time
- import unittest
- from portcv.plc import ModbusTcpServer, registers
- from portcv.plc import modbus_pdu as pdu
- from portcv.plc.modbus_pdu import (
- FC_READ_HOLDING_REGISTERS,
- FC_READ_INPUT_REGISTERS,
- FC_WRITE_MULTIPLE_REGISTERS,
- FC_WRITE_SINGLE_REGISTER,
- )
- from portcv.schema import PlcCommand, SceneState, StatusBits, VisionSnapshot
- def make_snapshot(heartbeat: int = 7) -> VisionSnapshot:
- return VisionSnapshot(
- state=int(SceneState.BED),
- confidence=912,
- flags=int(StatusBits.READY | StatusBits.FRAME_OK | StatusBits.STABLE),
- seq=3,
- ts_s=1700000000,
- heartbeat=heartbeat,
- fps_x10=152,
- latency_ms=41,
- )
- def recv_exact(sock: socket.socket, size: int, timeout: float = 3.0) -> bytes:
- """读满 ``size`` 字节(服务端可能分片发送)。"""
- sock.settimeout(timeout)
- chunks = b""
- while len(chunks) < size:
- piece = sock.recv(size - len(chunks))
- if not piece:
- break
- chunks += piece
- return chunks
- def recv_frame(sock: socket.socket) -> bytes:
- """按 MBAP 长度字段读一个完整帧。"""
- header = recv_exact(sock, pdu.MBAP_HEADER_LEN)
- if len(header) < pdu.MBAP_HEADER_LEN:
- return b""
- length = int.from_bytes(header[4:6], "big")
- return header + recv_exact(sock, max(0, length - 1))
- class ServerProtocolTests(unittest.TestCase):
- """直接调用 ``handle_frame``:不占端口,跑得快,覆盖各异常分支。"""
- def setUp(self):
- self.commands = []
- self.server = ModbusTcpServer(
- host="127.0.0.1",
- port=0,
- unit_id=1,
- on_command=lambda words, peer: self.commands.append((list(words), peer)),
- )
- def tearDown(self):
- self.server.server_close()
- def _request(
- self, function: int, address: int = 0, quantity: int = 12, tx: int = 1, unit: int = 1, **kwargs
- ):
- frame = pdu.build_request(tx, unit, function, address, quantity=quantity, **kwargs)
- response = self.server.handle_frame(frame, "test")
- if not response:
- return b""
- return pdu.parse_mbap(response)[4]
- def test_snapshot_readback_over_fc4(self):
- snapshot = make_snapshot()
- self.server.set_snapshot(snapshot)
- body = self._request(FC_READ_INPUT_REGISTERS, quantity=12)
- self.assertEqual(body[0], FC_READ_INPUT_REGISTERS)
- words = pdu.parse_read_response(body)
- self.assertEqual(len(words), VisionSnapshot.register_count())
- self.assertEqual(registers.decode_snapshot(words), snapshot)
- self.assertEqual(self.server.input_registers(), words)
- def test_partial_block_read(self):
- self.server.set_snapshot(make_snapshot())
- words = pdu.parse_read_response(self._request(FC_READ_INPUT_REGISTERS, address=5, quantity=4))
- self.assertEqual(words, self.server.input_registers()[5:9])
- def test_read_holding_registers(self):
- self.server.set_holding_registers([1, 2, 700, 0])
- body = self._request(FC_READ_HOLDING_REGISTERS, quantity=4)
- self.assertEqual(pdu.parse_read_response(body), [1, 2, 700, 0])
- def test_illegal_address_returns_exception_02(self):
- body = self._request(FC_READ_INPUT_REGISTERS, address=100, quantity=12)
- self.assertEqual(body, bytes([0x84, 0x02]))
- self.assertGreaterEqual(self.server.stats["errors"], 1)
- def test_illegal_quantity_returns_exception_03(self):
- self.assertEqual(self._request(FC_READ_INPUT_REGISTERS, quantity=200), bytes([0x84, 0x03]))
- def test_write_single_updates_command_and_notifies(self):
- body = self._request(FC_WRITE_SINGLE_REGISTER, single_value=int(registers.CMD_REQUEST))
- self.assertEqual(body, bytes([FC_WRITE_SINGLE_REGISTER, 0x00, 0x00, 0x00, 0x01]))
- self.assertTrue(self.server.command().is_request())
- self.assertEqual(len(self.commands), 1)
- self.assertEqual(self.commands[0][1], "test")
- self.assertEqual(self.commands[0][0], [1, 0, 0, 0])
- def test_write_multiple_sets_all_command_words(self):
- body = self._request(
- FC_WRITE_MULTIPLE_REGISTERS, values=[int(registers.CMD_RESET), 3, 700, 0]
- )
- self.assertEqual(body, bytes([0x10, 0x00, 0x00, 0x00, 0x04]))
- self.assertEqual(self.server.command(), PlcCommand(cmd=2, preset=3, min_conf=700, reserved=0))
- self.assertTrue(self.commands)
- def test_write_out_of_range_address_returns_exception_02(self):
- body = self._request(FC_WRITE_SINGLE_REGISTER, address=9, single_value=1)
- self.assertEqual(body, bytes([0x86, 0x02]))
- def test_write_multiple_wrong_byte_count_returns_exception_03(self):
- # 手工构造:数量 2 但字节数写成 2(应为 4)
- raw = bytes(
- [0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x01, 0x10, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00, 0x01]
- )
- body = pdu.parse_mbap(self.server.handle_frame(raw, "test"))[4]
- self.assertEqual(body, bytes([0x90, 0x03]))
- def test_write_multiple_short_payload_returns_exception_02(self):
- # byte_count 自洽(4)但只给了 1 个字:按 `len(values) < quantity` 判非法
- # 地址(0x02),与 C++ `handle_frame` 同口径;且不得把缺失字节补 0 写入。
- raw = bytes(
- [0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x01, 0x10, 0x00, 0x00, 0x00, 0x02, 0x04, 0x00, 0x01]
- )
- body = pdu.parse_mbap(self.server.handle_frame(raw, "test"))[4]
- self.assertEqual(body, bytes([0x90, 0x02]))
- self.assertEqual(self.server.holding_registers(), [0, 0, 0, 0])
- def test_unsupported_function_returns_illegal_function(self):
- raw = pdu.build_frame(7, 1, b"\x08\x00\x00\x00\x01")
- body = pdu.parse_mbap(self.server.handle_frame(raw, "test"))[4]
- self.assertEqual(body, bytes([0x88, 0x01]))
- def test_short_frame_is_ignored(self):
- self.assertEqual(self.server.handle_frame(b"\x01\x02\x03", "test"), b"")
- def test_wrong_protocol_id_returns_exception_03(self):
- raw = bytes([0x00, 0x01, 0x00, 0x01, 0x00, 0x06, 0x01, 0x04, 0x00, 0x00, 0x00, 0x0C])
- body = pdu.parse_mbap(self.server.handle_frame(raw, "test"))[4]
- self.assertEqual(body, bytes([0x84, 0x03]))
- def test_strict_unit_id_drops_foreign_requests(self):
- strict = ModbusTcpServer(host="127.0.0.1", port=0, unit_id=3, allow_unit_any=False)
- try:
- foreign = pdu.build_request(1, 9, FC_READ_INPUT_REGISTERS, 0, quantity=12)
- self.assertEqual(strict.handle_frame(foreign, "x"), b"")
- mine = pdu.build_request(2, 3, FC_READ_INPUT_REGISTERS, 0, quantity=12)
- self.assertTrue(strict.handle_frame(mine, "x"))
- finally:
- strict.server_close()
- def test_any_unit_id_is_echoed(self):
- # allow_unit_any=True(默认)时接受任意站点号,但响应必须回显请求的 unit_id;
- # 不能归一化成配置里的 1,否则西门子 MB_CLIENT 会丢弃响应。
- frame = pdu.build_request(1, 42, FC_READ_INPUT_REGISTERS, 0, quantity=4)
- tx, _proto, _len, unit, body = pdu.parse_mbap(self.server.handle_frame(frame, "test"))
- self.assertEqual((tx, unit), (1, 42))
- self.assertEqual(len(pdu.parse_read_response(body)), 4)
- class ServerSocketTests(unittest.TestCase):
- """真 socket 往返:验证线程化服务端 + MBAP 分帧 + 统计。"""
- def test_tcp_roundtrip(self):
- snapshot = make_snapshot(heartbeat=123)
- server = ModbusTcpServer(host="127.0.0.1", port=0, unit_id=1)
- server.set_snapshot(snapshot)
- server.start()
- try:
- port = int(server.server_address[1])
- with socket.create_connection(("127.0.0.1", port), timeout=3.0) as sock:
- sock.sendall(pdu.build_request(0x11, 1, FC_READ_INPUT_REGISTERS, 0, quantity=12))
- tx, _proto, _len, unit, body = pdu.parse_mbap(recv_frame(sock))
- self.assertEqual((tx, unit), (0x11, 1))
- self.assertEqual(registers.decode_snapshot(pdu.parse_read_response(body)), snapshot)
- sock.sendall(pdu.build_request(0x12, 1, FC_WRITE_SINGLE_REGISTER, 0, single_value=2))
- _tx, _proto, _len, _unit, body = pdu.parse_mbap(recv_frame(sock))
- self.assertEqual(body, bytes([0x06, 0x00, 0x00, 0x00, 0x02]))
- self.assertTrue(server.command().is_reset())
- finally:
- server.stop()
- deadline = time.time() + 1.0
- while server.client_count and time.time() < deadline:
- time.sleep(0.02)
- self.assertTrue(server.is_stopping())
- self.assertGreaterEqual(server.stats["reads"], 1)
- self.assertGreaterEqual(server.stats["writes"], 1)
- self.assertEqual(server.client_count, 0)
- def test_invalid_mbap_length_closes_connection(self):
- # length=0(连 unit_id 都没有)与 length=65535(超长)都属非法:
- # 服务端必须立刻断连,不能等 30 s 超时(慢速攻击 / 网关错位报文),
- # 也不能按 64 KB 去缓冲。与 C++ service_client 的 2..254 同口径。
- server = ModbusTcpServer(host="127.0.0.1", port=0, unit_id=1)
- server.start()
- try:
- port = int(server.server_address[1])
- for length in (0, 65535):
- with socket.create_connection(("127.0.0.1", port), timeout=3.0) as sock:
- sock.sendall(
- bytes([0x00, 0x01, 0x00, 0x00, (length >> 8) & 0xFF, length & 0xFF, 0x01])
- )
- sock.settimeout(3.0)
- self.assertEqual(sock.recv(1), b"", "非法 length=%d:服务端应断连" % length)
- finally:
- server.stop()
- if __name__ == "__main__":
- unittest.main()
|