From 1c3d58914dbc66e86455576b2cc2ed7a1645c110 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Fri, 16 Oct 2026 17:57:59 +0200 Subject: [PATCH 01/12] PDU classes refactored. --- examples/client_async_calls.py | 12 +- examples/client_calls.py | 12 +- examples/custom_msg.py | 109 --- examples/server_hook.py | 4 +- pymodbus/__init__.py | 10 +- pymodbus/client/base.py | 22 +- pymodbus/client/mixin.py | 119 ++- pymodbus/client/serial.py | 6 +- pymodbus/client/tcp.py | 6 +- pymodbus/client/tls.py | 6 +- pymodbus/client/udp.py | 6 +- pymodbus/constants.py | 19 +- pymodbus/framer/ascii.py | 15 +- pymodbus/framer/base.py | 17 +- pymodbus/framer/rtu.py | 22 +- pymodbus/framer/socket.py | 7 +- pymodbus/pdu/__init__.py | 42 +- pymodbus/pdu/bit_message.py | 301 ------- pymodbus/pdu/data_message.py | 592 ++++++++++++++ pymodbus/pdu/decoders.py | 105 --- pymodbus/pdu/device.py | 339 +++++--- pymodbus/pdu/diag_message.py | 690 +++++++--------- pymodbus/pdu/events.py | 210 ----- pymodbus/pdu/exceptionresponse.py | 56 -- pymodbus/pdu/file_message.py | 340 -------- pymodbus/pdu/mei_message.py | 210 ----- pymodbus/pdu/other_message.py | 594 +++++++++----- pymodbus/pdu/pdu.py | 296 +++++-- pymodbus/pdu/register_message.py | 510 ------------ pymodbus/pdu/utils.py | 54 -- pymodbus/server/base.py | 16 +- pymodbus/server/requesthandler.py | 29 +- pymodbus/server/server.py | 27 +- pymodbus/server/simulator/http_server.py | 7 +- pymodbus/transaction/transaction.py | 44 +- test/client/test_client.py | 97 ++- test/conftest.py | 26 - test/examples/test_examples.py | 10 +- test/framer/conftest.py | 26 - test/framer/generator.py | 51 -- test/framer/test_extras.py | 23 +- test/framer/test_framer.py | 241 +++--- test/pdu/conftest.py | 547 +++++++++++++ test/pdu/test_bit.py | 340 -------- test/pdu/test_decoders.py | 192 ----- test/pdu/test_device.py | 82 +- test/pdu/test_diag_messages.py | 224 ----- test/pdu/test_events.py | 70 -- test/pdu/test_file_message.py | 261 ------ test/pdu/test_mei_messages.py | 209 ----- test/pdu/test_other_messages.py | 185 ----- test/pdu/test_pdu.py | 997 ++++++++++------------- test/pdu/test_pdu_extras.py | 543 ++++++++++++ test/pdu/test_register_read_messages.py | 373 --------- test/pdu/test_register_write_messages.py | 249 ------ test/server/test_base.py | 12 +- test/server/test_requesthandler.py | 30 +- test/server/test_server_asyncio.py | 21 +- test/transaction/test_transaction.py | 160 ++-- 59 files changed, 3819 insertions(+), 6004 deletions(-) delete mode 100644 pymodbus/pdu/bit_message.py create mode 100644 pymodbus/pdu/data_message.py delete mode 100644 pymodbus/pdu/decoders.py delete mode 100644 pymodbus/pdu/events.py delete mode 100644 pymodbus/pdu/exceptionresponse.py delete mode 100644 pymodbus/pdu/file_message.py delete mode 100644 pymodbus/pdu/mei_message.py delete mode 100644 pymodbus/pdu/register_message.py delete mode 100644 pymodbus/pdu/utils.py delete mode 100644 test/framer/conftest.py delete mode 100755 test/framer/generator.py create mode 100644 test/pdu/conftest.py delete mode 100644 test/pdu/test_bit.py delete mode 100644 test/pdu/test_decoders.py delete mode 100644 test/pdu/test_diag_messages.py delete mode 100644 test/pdu/test_events.py delete mode 100644 test/pdu/test_file_message.py delete mode 100644 test/pdu/test_mei_messages.py delete mode 100644 test/pdu/test_other_messages.py create mode 100644 test/pdu/test_pdu_extras.py delete mode 100644 test/pdu/test_register_read_messages.py delete mode 100644 test/pdu/test_register_write_messages.py diff --git a/examples/client_async_calls.py b/examples/client_async_calls.py index 2b6c4a6d9d..9a2f8b4a4b 100755 --- a/examples/client_async_calls.py +++ b/examples/client_async_calls.py @@ -11,16 +11,8 @@ All available modbus calls are present. If you are performing a request that is not available in the client -mixin, you have to perform the request like this instead:: - - from pymodbus.pdu.diag_message import ClearCountersRequest - from pymodbus.pdu.diag_message import ClearCountersResponse - - request = ClearCountersRequest() - response = client.execute(request) - if isinstance(response, ClearCountersResponse): - ... do something with the response - +mixin, you can use client.execute directly, but the easiest way it to add +a custom PDU class. This example uses client_async.py and client_sync.py to handle connection, and have the same options. diff --git a/examples/client_calls.py b/examples/client_calls.py index d0ff92ff79..a7f23b9663 100755 --- a/examples/client_calls.py +++ b/examples/client_calls.py @@ -11,16 +11,8 @@ All available modbus calls are present. If you are performing a request that is not available in the client -mixin, you have to perform the request like this instead:: - - from pymodbus.pdu.diag_message import ClearCountersRequest - from pymodbus.pdu.diag_message import ClearCountersResponse - - request = ClearCountersRequest() - response = client.execute(request) - if isinstance(response, ClearCountersResponse): - ... do something with the response - +mixin, you can use client.execute directly, but the easiest way it to add +a custom PDU class. This example uses client_async.py and client_sync.py to handle connection, and have the same options. diff --git a/examples/custom_msg.py b/examples/custom_msg.py index 59cdd327db..d6ac4e9f2b 100755 --- a/examples/custom_msg.py +++ b/examples/custom_msg.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# pylint: disable=missing-type-doc """Pymodbus Synchronous Client Examples. The following is an example of how to use the synchronous modbus client @@ -12,14 +11,9 @@ """ import asyncio -import struct from pymodbus import FramerType from pymodbus.client import AsyncModbusTcpClient as ModbusClient -from pymodbus.datastore import ModbusServerContext -from pymodbus.exceptions import ModbusIOException -from pymodbus.pdu import ModbusPDU -from pymodbus.pdu.bit_message import ReadCoilsRequest from pymodbus.server import ServerAsyncStop, StartAsyncTcpServer from pymodbus.simulator import DataType, SimData, SimDevice @@ -35,92 +29,6 @@ # --------------------------------------------------------------------------- # -class CustomModbusResponse(ModbusPDU): - """Custom modbus response.""" - - function_code = 55 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 - - def __init__(self, values: list[int] | None = None, device_id=1, transaction=0): - """Initialize.""" - super().__init__(dev_id=device_id, transaction_id=transaction) - self.values: list[int] = values or [] - - def x_encode(self): - """Encode response pdu. - - :returns: The encoded packet message - """ - res = struct.pack(">B", len(self.values) * 2) - for register in self.values: # pragma: no cover - res += struct.pack(">H", register) - return res - - def x_decode(self, data): # pragma: no cover - """Decode response pdu. - - :param data: The packet data to decode - """ - byte_count = int(data[0]) - self.values = [] - for i in range(1, byte_count + 1, 2): - self.values.append(struct.unpack(">H", data[i : i + 2])[0]) - - -class CustomRequest(ModbusPDU): - """Custom modbus request.""" - - function_code = 55 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 - - def __init__(self, address=None, device_id=1, transaction=0): - """Initialize.""" - super().__init__(dev_id=device_id, transaction_id=transaction) - self.address = address - self.count = 2 - - def x_encode(self): - """Encode.""" - return struct.pack(">HH", self.address, self.count) - - def x_decode(self, data): - """Decode.""" - self.address, self.count = struct.unpack(">HH", data) - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context, device_id - return CustomModbusResponse() - - -# --------------------------------------------------------------------------- # -# This could also have been defined as -# --------------------------------------------------------------------------- # - - -class Read16CoilsRequest(ReadCoilsRequest): - """Read 16 coils in one request.""" - - def __init__(self, address, device_id=1, transaction=0): - """Initialize a new instance. - - :param address: The address to start reading from - """ - super().__init__( - address=address, count=16, dev_id=device_id, transaction_id=transaction - ) - - # --------------------------------------------------------------------------- # # execute the request with your client # --------------------------------------------------------------------------- # @@ -137,7 +45,6 @@ async def main(host="localhost", port=5020): 0, SimData(0, datatype=DataType.REGISTERS, values=[17] * 100) ), address=(host, port), - custom_pdu=[CustomRequest], ) ) await asyncio.sleep(0.1) @@ -145,22 +52,6 @@ async def main(host="localhost", port=5020): await client.connect() # add new modbus function code. - assert CustomModbusResponse.x_calculateRtuFrameSize(b"\x00\x00\x07\x00") == 12 - client.register(CustomModbusResponse) - device_id = 1 - assert CustomRequest.x_calculateRtuFrameSize(b"") == 8 - request1 = CustomRequest(32, device_id=device_id) - try: - result = await client.execute(False, request1) - except ModbusIOException: # pragma: no cover - print("Server do not support CustomRequest.") - else: - print(result) # pragma: no cover - - # inherited request - request2 = Read16CoilsRequest(32, device_id) - result = await client.execute(False, request2) - print(result) await ServerAsyncStop() task.cancel() await task diff --git a/examples/server_hook.py b/examples/server_hook.py index 6449e90f38..d198e03a92 100755 --- a/examples/server_hook.py +++ b/examples/server_hook.py @@ -12,7 +12,7 @@ import sys from pymodbus import FramerType, pymodbus_apply_logging_config -from pymodbus.pdu import ModbusPDU +from pymodbus.pdu import ModbusPdu from pymodbus.server import ModbusTcpServer from pymodbus.simulator import DataType, SimData, SimDevice @@ -41,7 +41,7 @@ def trace_packet(self, sending: bool, data: bytes) -> bytes: return data - def trace_pdu(self, sending: bool, pdu: ModbusPDU) -> ModbusPDU: + def trace_pdu(self, sending: bool, pdu: ModbusPdu) -> ModbusPdu: """Do dummy trace.""" txt = "REQUEST pdu" if sending else "RESPONSE pdu" print(f"---> {txt}: {pdu}") diff --git a/pymodbus/__init__.py b/pymodbus/__init__.py index b2480f7f7a..043e0e5b31 100644 --- a/pymodbus/__init__.py +++ b/pymodbus/__init__.py @@ -4,21 +4,23 @@ """ __all__ = [ - "ExceptionResponse", "FramerType", "Log", "ModbusDeviceIdentification", "ModbusException", + "ModbusIOException", + "ModbusPdu", + "StoreGet", + "StoreSet", "__version__", "__version_full__", "pymodbus_apply_logging_config", ] -from .exceptions import ModbusException +from .exceptions import ModbusException, ModbusIOException from .framer import FramerType from .logging import Log, pymodbus_apply_logging_config -from .pdu import ExceptionResponse -from .pdu.device import ModbusDeviceIdentification +from .pdu import ModbusDeviceIdentification, ModbusPdu, StoreGet, StoreSet __version__ = "4.0.0dev17" diff --git a/pymodbus/client/base.py b/pymodbus/client/base.py index 90e6b3c3dd..4481b6cd40 100644 --- a/pymodbus/client/base.py +++ b/pymodbus/client/base.py @@ -11,7 +11,7 @@ from ..exceptions import ConnectionException from ..framer import FRAMER_NAME_TO_CLASS, FramerBase, FramerType from ..logging import Log -from ..pdu import DecodePDU, ModbusPDU +from ..pdu import DecodePDU, ModbusPdu from ..transaction import TransactionManager from ..transport import CommParams from .mixin import ModbusClientMixin @@ -48,7 +48,7 @@ def stop(self) -> None: self.loop.close() -class ModbusBaseClient(ModbusClientMixin[Awaitable[ModbusPDU]]): +class ModbusBaseClient(ModbusClientMixin[Awaitable[ModbusPdu]]): """**ModbusBaseClient**. :mod:`ModbusBaseClient` is normally not referenced outside :mod:`pymodbus`. @@ -60,7 +60,7 @@ def __init__( retries: int, comm_params: CommParams, trace_packet: Callable[[bool, bytes], bytes] | None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None, trace_connect: Callable[[bool], None] | None, ) -> None: """Initialize a client instance. @@ -95,7 +95,7 @@ async def connect(self) -> bool: rc = await self.ctx.connect() return rc - def register(self, custom_response_class: type[ModbusPDU]) -> None: + def register(self, custom_response_class: type[ModbusPdu]) -> None: """Register a custom response class with the decoder (call **sync**). :param custom_response_class: (optional) Modbus response class. @@ -104,13 +104,13 @@ def register(self, custom_response_class: type[ModbusPDU]) -> None: Use register() to add non-standard responses (like e.g. a login prompt) and have them interpreted automatically. """ - self.ctx.framer.decoder.register(custom_response_class) + DecodePDU.add_pdu(custom_response_class) def close(self) -> None: """Close connection.""" self.ctx.close() - def execute(self, no_response_expected: bool, request: ModbusPDU): + def execute(self, no_response_expected: bool, request: ModbusPdu): """Execute request and get response (call **sync/async**). :meta private: @@ -154,7 +154,7 @@ def __str__(self): return f"{self.__class__.__name__} {self.ctx.comm_params.host}:{self.ctx.comm_params.port}" -class ModbusBaseSyncClient(ModbusClientMixin[ModbusPDU]): +class ModbusBaseSyncClient(ModbusClientMixin[ModbusPdu]): """**ModbusBaseClient**. :mod:`ModbusBaseClient` is normally not referenced outside :mod:`pymodbus`. @@ -166,7 +166,7 @@ def __init__( retries: int, comm_params: CommParams, trace_packet: Callable[[bool, bytes], bytes] | None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None, trace_connect: Callable[[bool], None] | None, ) -> None: """Initialize a client instance. @@ -203,7 +203,7 @@ def __init__( # ----------------------------------------------------------------------- # # Client external interface # ----------------------------------------------------------------------- # - def register(self, custom_response_class: type[ModbusPDU]) -> None: + def register(self, custom_response_class: type[ModbusPdu]) -> None: """Register a custom response class with the decoder. :param custom_response_class: (optional) Modbus response class. @@ -212,9 +212,9 @@ def register(self, custom_response_class: type[ModbusPDU]) -> None: Use register() to add non-standard responses (like e.g. a login prompt) and have them interpreted automatically. """ - self.framer.decoder.register(custom_response_class) + DecodePDU.add_pdu(custom_response_class) - def execute(self, no_response_expected: bool, request: ModbusPDU) -> ModbusPDU: + def execute(self, no_response_expected: bool, request: ModbusPdu) -> ModbusPdu: """Execute request and get response (call **sync/async**). :param no_response_expected: The client will not expect a response to the request diff --git a/pymodbus/client/mixin.py b/pymodbus/client/mixin.py index 09600b1cf9..733290cf17 100644 --- a/pymodbus/client/mixin.py +++ b/pymodbus/client/mixin.py @@ -7,16 +7,11 @@ from collections.abc import Sequence from typing import Generic, Literal, TypeVar, cast -from ..constants import ModbusStatus from ..exceptions import ModbusException -from ..pdu import bit_message as pdu_bit +from ..pdu import ModbusPdu, pack_bitstring, unpack_bitstring +from ..pdu import data_message as pdu_data from ..pdu import diag_message as pdu_diag -from ..pdu import file_message as pdu_file_msg -from ..pdu import mei_message as pdu_mei -from ..pdu import other_message as pdu_other_msg -from ..pdu import register_message as pdu_reg -from ..pdu.pdu import ModbusPDU -from ..pdu.utils import pack_bitstring, unpack_bitstring +from ..pdu import other_message as pdu_other T = TypeVar("T", covariant=False) @@ -51,7 +46,7 @@ class ModbusClientMixin(Generic[T]): # pylint: disable=too-many-public-methods def __init__(self): """Initialize.""" - def execute(self, no_response_expected: bool, request: ModbusPDU) -> T: + def execute(self, no_response_expected: bool, request: ModbusPdu) -> T: """Execute request.""" _ = no_response_expected, request return cast(T, None) @@ -78,7 +73,7 @@ def read_coils( """ return self.execute( no_response_expected, - pdu_bit.ReadCoilsRequest(address=address, count=count, dev_id=device_id), + pdu_data.PDUreadCoils(True, device_id, address=address, count=count), ) def read_discrete_inputs( @@ -101,8 +96,8 @@ def read_discrete_inputs( Discrete Inputs are addressed as 0-N (Note some device manuals uses 1-N, assuming 1==0). """ - pdu = pdu_bit.ReadDiscreteInputsRequest( - address=address, count=count, dev_id=device_id + pdu = pdu_data.PDUreadDiscreteInputs( + True, device_id, address=address, count=count ) return self.execute(no_response_expected, pdu) @@ -131,8 +126,8 @@ def read_holding_registers( """ return self.execute( no_response_expected, - pdu_reg.ReadHoldingRegistersRequest( - address=address, count=count, dev_id=device_id + pdu_data.PDUreadHoldingRegisters( + True, device_id, address=address, count=count ), ) @@ -161,8 +156,8 @@ def read_input_registers( """ return self.execute( no_response_expected, - pdu_reg.ReadInputRegistersRequest( - address=address, count=count, dev_id=device_id + pdu_data.PDUreadInputRegisters( + True, device_id, address=address, count=count ), ) @@ -186,8 +181,8 @@ def write_coil( Coils are addressed as 0-N (Note some device manuals uses 1-N, assuming 1==0). """ - pdu = pdu_bit.WriteSingleCoilRequest( - address=address, bits=[value], dev_id=device_id + pdu = pdu_data.PDUwriteSingleCoil( + True, device_id, address=address, bits=[value] ) return self.execute(no_response_expected, pdu) @@ -216,8 +211,8 @@ def write_register( """ return self.execute( no_response_expected, - pdu_reg.WriteSingleRegisterRequest( - address=address, registers=[value], dev_id=device_id + pdu_data.PDUwriteSingleRegister( + True, device_id, address=address, registers=[value] ), ) @@ -238,7 +233,7 @@ def read_exception_status( """ return self.execute( no_response_expected, - pdu_other_msg.ReadExceptionStatusRequest(dev_id=device_id), + pdu_other.PDUreadExceptionStatus(True, device_id), ) def diag_query_data( @@ -256,7 +251,8 @@ def diag_query_data( request. """ return self.execute( - no_response_expected, pdu_diag.ReturnQueryDataRequest(msg, dev_id=device_id) + no_response_expected, + pdu_diag.PDUreturnQueryData(True, device_id, message=msg), ) def diag_restart_communication( @@ -275,10 +271,10 @@ def diag_restart_communication( the only one that brings the port out of Listen Only Mode. If the port is not currently in Listen Only Mode, a normal response is returned. """ - msg = ModbusStatus.ON if toggle else ModbusStatus.OFF + msg = b"\xff\x00" if toggle else b"\x00\x00" return self.execute( no_response_expected, - pdu_diag.RestartCommunicationsOptionRequest(message=msg, dev_id=device_id), + pdu_diag.PDUrestartCommunicationsOption(True, device_id, message=msg), ) def diag_read_diagnostic_register( @@ -294,7 +290,7 @@ def diag_read_diagnostic_register( """ return self.execute( no_response_expected, - pdu_diag.ReturnDiagnosticRegisterRequest(dev_id=device_id), + pdu_diag.PDUreturnDiagnosticRegister(True, device_id), ) def diag_change_ascii_input_delimeter( @@ -318,9 +314,7 @@ def diag_change_ascii_input_delimeter( """ return self.execute( no_response_expected, - pdu_diag.ChangeAsciiInputDelimiterRequest( - message=delimiter, dev_id=device_id - ), + pdu_diag.PDUchangeAsciiInputDelimiter(True, device_id, message=delimiter), ) def diag_force_listen_only( @@ -339,7 +333,7 @@ def diag_force_listen_only( addressed remote device. No response is returned. """ return self.execute( - no_response_expected, pdu_diag.ForceListenOnlyModeRequest(dev_id=device_id) + no_response_expected, pdu_diag.PDUforceListenOnlyMode(True, device_id) ) def diag_clear_counters( @@ -354,7 +348,7 @@ def diag_clear_counters( Clear ll counters and the diagnostic register. Also, counters are cleared upon power-up """ return self.execute( - no_response_expected, pdu_diag.ClearCountersRequest(dev_id=device_id) + no_response_expected, pdu_diag.PDUclearCounters(True, device_id) ) def diag_read_bus_message_count( @@ -372,7 +366,7 @@ def diag_read_bus_message_count( """ return self.execute( no_response_expected, - pdu_diag.ReturnBusMessageCountRequest(dev_id=device_id), + pdu_diag.PDUreturnBusMessageCount(True, device_id), ) def diag_read_bus_comm_error_count( @@ -390,7 +384,7 @@ def diag_read_bus_comm_error_count( """ return self.execute( no_response_expected, - pdu_diag.ReturnBusCommunicationErrorCountRequest(dev_id=device_id), + pdu_diag.PDUreturnBusCommunicationErrorCount(True, device_id), ) def diag_read_bus_exception_error_count( @@ -408,7 +402,7 @@ def diag_read_bus_exception_error_count( """ return self.execute( no_response_expected, - pdu_diag.ReturnBusExceptionErrorCountRequest(dev_id=device_id), + pdu_diag.PDUreturnBusExceptionErrorCount(True, device_id), ) def diag_read_device_message_count( @@ -426,7 +420,7 @@ def diag_read_device_message_count( """ return self.execute( no_response_expected, - pdu_diag.ReturnDeviceMessageCountRequest(dev_id=device_id), + pdu_diag.PDUreturnDeviceMessageCount(True, device_id), ) def diag_read_device_no_response_count( @@ -444,7 +438,7 @@ def diag_read_device_no_response_count( """ return self.execute( no_response_expected, - pdu_diag.ReturnDeviceNoResponseCountRequest(dev_id=device_id), + pdu_diag.PDUreturnDeviceNoResponseCount(True, device_id), ) def diag_read_device_nak_count( @@ -462,7 +456,7 @@ def diag_read_device_nak_count( Exception responses are described and listed in section 7 . """ return self.execute( - no_response_expected, pdu_diag.ReturnDeviceNAKCountRequest(dev_id=device_id) + no_response_expected, pdu_diag.PDUreturnDeviceNAKCount(True, device_id) ) def diag_read_device_busy_count( @@ -480,7 +474,7 @@ def diag_read_device_busy_count( """ return self.execute( no_response_expected, - pdu_diag.ReturnDeviceBusyCountRequest(dev_id=device_id), + pdu_diag.PDUreturnDeviceBusyCount(True, device_id), ) def diag_read_bus_char_overrun_count( @@ -500,7 +494,7 @@ def diag_read_bus_char_overrun_count( """ return self.execute( no_response_expected, - pdu_diag.ReturnDeviceBusCharacterOverrunCountRequest(dev_id=device_id), + pdu_diag.PDUreturnDeviceBusCharacterOverrunCount(True, device_id), ) def diag_read_iop_overrun_count( @@ -518,7 +512,7 @@ def diag_read_iop_overrun_count( """ return self.execute( no_response_expected, - pdu_diag.ReturnIopOverrunCountRequest(dev_id=device_id), + pdu_diag.PDUreturnIopOverrunCount(True, device_id), ) def diag_clear_overrun_counter( @@ -534,7 +528,7 @@ def diag_clear_overrun_counter( specification mentions is, so it is ignored. """ return self.execute( - no_response_expected, pdu_diag.ClearOverrunCountRequest(dev_id=device_id) + no_response_expected, pdu_diag.PDUclearOverrunCount(True, device_id) ) def diag_getclear_modbus_response( @@ -557,7 +551,7 @@ def diag_getclear_modbus_response( """ return self.execute( no_response_expected, - pdu_diag.GetClearModbusPlusRequest(message=data, dev_id=device_id), + pdu_diag.PDUgetClearModbusPlus(True, device_id, message=data), ) def diag_get_comm_event_counter( @@ -584,7 +578,7 @@ def diag_get_comm_event_counter( """ return self.execute( no_response_expected, - pdu_other_msg.GetCommEventCounterRequest(dev_id=device_id), + pdu_other.PDUgetCommEventCounter(True, device_id), ) def diag_get_comm_event_log( @@ -615,7 +609,7 @@ def diag_get_comm_event_log( flushes the oldest byte from the field. """ return self.execute( - no_response_expected, pdu_other_msg.GetCommEventLogRequest(dev_id=device_id) + no_response_expected, pdu_other.PDUgetCommEventLog(True, device_id) ) def write_coils( @@ -638,8 +632,8 @@ def write_coils( Coils are addressed as 0-N (Note some device manuals uses 1-N, assuming 1==0). """ - pdu = pdu_bit.WriteMultipleCoilsRequest( - address=address, bits=values, dev_id=device_id + pdu = pdu_data.PDUwriteMultipleCoils( + True, device_id, address=address, bits=values ) return self.execute(no_response_expected, pdu) @@ -664,8 +658,8 @@ def write_registers( """ return self.execute( no_response_expected, - pdu_reg.WriteMultipleRegistersRequest( - address=address, registers=values, dev_id=device_id + pdu_data.PDUwriteMultipleRegisters( + True, device_id, address=address, registers=values ), ) @@ -682,12 +676,12 @@ def report_device_id( and other information specific to a remote device. """ return self.execute( - no_response_expected, pdu_other_msg.ReportDeviceIdRequest(dev_id=device_id) + no_response_expected, pdu_other.PDUreportDeviceId(True, device_id) ) def read_file_record( self, - records: list[pdu_file_msg.FileRecord], + records: list[pdu_other.FileRecord], *, device_id: int = 1, no_response_expected: bool = False, @@ -721,12 +715,12 @@ def read_file_record( """ return self.execute( no_response_expected, - pdu_file_msg.ReadFileRecordRequest(records, dev_id=device_id), + pdu_other.PDUreadFileRecord(True, device_id, records=records), ) def write_file_record( self, - records: list[pdu_file_msg.FileRecord], + records: list[pdu_other.FileRecord], *, device_id: int = 1, no_response_expected: bool = False, @@ -745,7 +739,7 @@ def write_file_record( """ return self.execute( no_response_expected, - pdu_file_msg.WriteFileRecordRequest(records=records, dev_id=device_id), + pdu_other.PDUwriteFileRecord(True, device_id, records=records), ) def mask_write_register( @@ -773,8 +767,8 @@ def mask_write_register( """ return self.execute( no_response_expected, - pdu_reg.MaskWriteRegisterRequest( - address=address, and_mask=and_mask, or_mask=or_mask, dev_id=device_id + pdu_data.PDUmaskWriteRegister( + True, device_id, address=address, and_mask=and_mask, or_mask=or_mask ), ) @@ -814,12 +808,13 @@ def readwrite_registers( write_address = address return self.execute( no_response_expected, - pdu_reg.ReadWriteMultipleRegistersRequest( - read_address=read_address, - read_count=read_count, + pdu_data.PDUreadWriteMultipleRegisters( + True, + device_id, + address=read_address, + count=read_count, write_address=write_address, - write_registers=values, - dev_id=device_id, + registers=values, ), ) @@ -849,7 +844,7 @@ def read_fifo_queue( """ return self.execute( no_response_expected, - pdu_file_msg.ReadFifoQueueRequest(address, dev_id=device_id), + pdu_other.PDUreadFifoQueue(True, device_id, address=address), ) # code 0x2B sub 0x0D: CANopen General Reference Request and Response, NOT IMPLEMENTED @@ -880,8 +875,8 @@ def read_device_information( """ return self.execute( no_response_expected, - pdu_mei.ReadDeviceInformationRequest( - read_code, object_id, dev_id=device_id + pdu_diag.PDUreadDeviceInformation( + True, device_id, read_code=read_code, object_id=object_id ), ) diff --git a/pymodbus/client/serial.py b/pymodbus/client/serial.py index 3038b20781..7666796c70 100644 --- a/pymodbus/client/serial.py +++ b/pymodbus/client/serial.py @@ -11,7 +11,7 @@ from ..exceptions import ConnectionException from ..framer import FramerType from ..logging import Log -from ..pdu import ModbusPDU +from ..pdu import ModbusPdu from ..transport import CommParams, CommType from .base import ModbusBaseClient, ModbusBaseSyncClient @@ -82,7 +82,7 @@ def __init__( timeout: float = 3, retries: int = 3, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, ) -> None: """Initialize Asyncio Modbus Serial Client.""" @@ -174,7 +174,7 @@ def __init__( timeout: float = 3, retries: int = 3, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, ) -> None: """Initialize Modbus Serial Client.""" diff --git a/pymodbus/client/tcp.py b/pymodbus/client/tcp.py index d58727438e..ef5ba93f87 100644 --- a/pymodbus/client/tcp.py +++ b/pymodbus/client/tcp.py @@ -12,7 +12,7 @@ from ..exceptions import ConnectionException from ..framer import FramerType from ..logging import Log -from ..pdu import ModbusPDU +from ..pdu import ModbusPdu from ..transport import CommParams, CommType from .base import ModbusBaseClient, ModbusBaseSyncClient @@ -73,7 +73,7 @@ def __init__( timeout: float = 3, retries: int = 3, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, ) -> None: """Initialize Asyncio Modbus TCP Client.""" @@ -152,7 +152,7 @@ def __init__( timeout: float = 3, retries: int = 3, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, ) -> None: """Initialize Modbus TCP Client.""" diff --git a/pymodbus/client/tls.py b/pymodbus/client/tls.py index 0dd5634017..f772621535 100644 --- a/pymodbus/client/tls.py +++ b/pymodbus/client/tls.py @@ -8,7 +8,7 @@ from ..framer import FramerType from ..logging import Log -from ..pdu import ModbusPDU +from ..pdu import ModbusPdu from ..transport import CommParams, CommType from .tcp import AsyncModbusTcpClient, ModbusTcpClient @@ -71,7 +71,7 @@ def __init__( timeout: float = 3, retries: int = 3, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, ): """Initialize Asyncio Modbus TLS Client.""" @@ -155,7 +155,7 @@ def __init__( timeout: float = 3, retries: int = 3, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, ): """Initialize Modbus TLS Client.""" diff --git a/pymodbus/client/udp.py b/pymodbus/client/udp.py index 52b8d0823e..ee957256be 100644 --- a/pymodbus/client/udp.py +++ b/pymodbus/client/udp.py @@ -9,7 +9,7 @@ from ..exceptions import ConnectionException from ..framer import FramerType from ..logging import Log -from ..pdu import ModbusPDU +from ..pdu import ModbusPdu from ..transport import CommParams, CommType from .base import ModbusBaseClient, ModbusBaseSyncClient @@ -73,7 +73,7 @@ def __init__( timeout: float = 3, retries: int = 3, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, ) -> None: """Initialize Asyncio Modbus UDP Client.""" @@ -152,7 +152,7 @@ def __init__( timeout: float = 3, retries: int = 3, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, ) -> None: """Initialize Modbus UDP Client.""" diff --git a/pymodbus/constants.py b/pymodbus/constants.py index 27e1c55247..fdff428980 100644 --- a/pymodbus/constants.py +++ b/pymodbus/constants.py @@ -10,6 +10,7 @@ INTERNAL_ERROR = "Pymodbus internal error" +MAX_TRANSACTION_ID = 65535 class ModbusStatus(enum.IntEnum): @@ -55,22 +56,8 @@ class ExcCodes(enum.IntEnum): GATEWAY_NO_RESPONSE = 0x0B -class ModbusPlusOperation(enum.IntEnum): - """Represents the type of modbus plus request. - - .. attribute:: GET_STATISTICS - - Operation requesting that the current modbus plus statistics - be returned in the response. - - .. attribute:: CLEAR_STATISTICS - - Operation requesting that the current modbus plus statistics - be cleared and not returned in the response. - """ - - GET_STATISTICS = 0x0003 - CLEAR_STATISTICS = 0x0004 +GET_STATISTICS = b"\x00\x03" +CLEAR_STATISTICS = b"\x00\x04" class DeviceInformation(enum.IntEnum): diff --git a/pymodbus/framer/ascii.py b/pymodbus/framer/ascii.py index 53465448bd..074a3d589e 100644 --- a/pymodbus/framer/ascii.py +++ b/pymodbus/framer/ascii.py @@ -10,7 +10,7 @@ from binascii import a2b_hex, b2a_hex from ..logging import Log -from ..pdu.device import ModbusControlBlock +from ..pdu import ModbusControlBlock from .base import FramerBase @@ -77,18 +77,13 @@ def decode(self, data: bytes) -> tuple[int, int, int, bytes]: if not self.check_LRC(msg, lrc): Log.debug("LRC wrong in frame: {} skipping", data, ":hex") continue - return used_len, dev_id, 0, msg[1:] + return used_len, dev_id, 0, msg - def encode(self, payload: bytes, device_id: int, _tid: int) -> bytes: + def encode(self, payload: bytes, _tid: int) -> bytes: """Encode ADU.""" - dev_id = device_id.to_bytes(1, "big") - checksum = self.compute_LRC(dev_id + payload) + checksum = self.compute_LRC(payload) frame = ( - self.START - + f"{device_id:02x}".encode() - + b2a_hex(payload) - + f"{checksum:02x}".encode() - + self.end + self.START + b2a_hex(payload) + f"{checksum:02x}".encode() + self.end ).upper() return frame diff --git a/pymodbus/framer/base.py b/pymodbus/framer/base.py index f7af67d5b6..e65475f8aa 100644 --- a/pymodbus/framer/base.py +++ b/pymodbus/framer/base.py @@ -11,7 +11,7 @@ from ..exceptions import ModbusIOException from ..logging import Log -from ..pdu import DecodePDU, ModbusPDU +from ..pdu import DecodePDU, ModbusPdu class FramerType(str, Enum): @@ -48,7 +48,7 @@ def decode(self, _data: bytes) -> tuple[int, int, int, bytes]: """ return 0, 0, 0, self.EMPTY - def encode(self, payload: bytes, _dev_id: int, _tid: int) -> bytes: + def encode(self, payload: bytes, _tid: int) -> bytes: """Encode ADU. returns: @@ -67,18 +67,15 @@ def next_transaction_id(self, transaction_id: int) -> int: _ = transaction_id return 0 - def buildFrame(self, message: ModbusPDU) -> bytes: - """Create a ready to send modbus packet. - - :param message: The populated request/response to send - """ - data = message.function_code.to_bytes(1, "big") + self.decoder.encode(message) - frame = self.encode(data, message.dev_id, message.transaction_id) + def buildFrame(self, pdu: ModbusPdu) -> bytes: + """Create a ready to send modbus packet.""" + data = self.decoder.encode(pdu) + frame = self.encode(data, pdu.transaction_id) return frame def handleFrame( self, data: bytes, exp_devid: int, exp_tid: int - ) -> tuple[int, ModbusPDU | None]: + ) -> tuple[int, ModbusPdu | None]: """Process incoming data.""" used_len = 0 while True: diff --git a/pymodbus/framer/rtu.py b/pymodbus/framer/rtu.py index fc7fc11863..7140b9cef0 100644 --- a/pymodbus/framer/rtu.py +++ b/pymodbus/framer/rtu.py @@ -83,29 +83,23 @@ def decode(self, data: bytes) -> tuple[int, int, int, bytes]: Log.debug("Short frame: {} wait for more data", data, ":hex") return 0, 0, 0, self.EMPTY dev_id = int(data[used_len]) - try: - size = self.decoder.calculateRtuFrameSize(data[used_len:]) - except IndexError: - Log.debug("Frame - byte count not received, wait for more data") + if not (size := self.decoder.calculatePduSize(data[used_len:-2])): + Log.debug( + "Frame - not enough bytes to calculate PDU size, wait for more data" + ) return 0, dev_id, 0, self.EMPTY - if not size: - continue - if data_len < used_len + size: - Log.debug("Frame - not ready") - return 0, dev_id, 0, self.EMPTY - crc_start = used_len + size - 2 + crc_start = used_len + size crc = data[crc_start : crc_start + 2] crc_val = (int(crc[0]) << 8) + int(crc[1]) if not FramerRTU.check_CRC(data[used_len:crc_start], crc_val): Log.debug("Frame CRC check failed, possible garbage") return data_len, 0, 0, self.EMPTY - return data_len, dev_id, 0, data[used_len + 1 : crc_start] + return data_len, dev_id, 0, data[used_len:crc_start] return 0, 0, 0, self.EMPTY - def encode(self, payload: bytes, device_id: int, _tid: int) -> bytes: + def encode(self, payload: bytes, _tid: int) -> bytes: """Encode ADU.""" - frame = device_id.to_bytes(1, "big") + payload - return frame + FramerRTU.compute_CRC(frame).to_bytes(2, "big") + return payload + FramerRTU.compute_CRC(payload).to_bytes(2, "big") @classmethod def check_CRC(cls, data: bytes, check: int) -> bool: diff --git a/pymodbus/framer/socket.py b/pymodbus/framer/socket.py index 0980031467..fe6eaa2abe 100644 --- a/pymodbus/framer/socket.py +++ b/pymodbus/framer/socket.py @@ -36,7 +36,7 @@ def decode(self, data: bytes) -> tuple[int, int, int, bytes]: return 0, 0, 0, self.EMPTY if msg_len == 8 and data_len == 9: msg_len = 9 - return msg_len, dev_id, tid, data[7:msg_len] + return msg_len, dev_id, tid, data[6:msg_len] def next_transaction_id(self, transaction_id: int) -> int: """Return the transaction id to use for the next request. @@ -48,13 +48,12 @@ def next_transaction_id(self, transaction_id: int) -> int: return 1 return transaction_id + 1 - def encode(self, payload: bytes, device_id: int, tid: int) -> bytes: + def encode(self, payload: bytes, tid: int) -> bytes: """Encode ADU.""" frame = ( tid.to_bytes(2, "big") + b"\x00\x00" - + (len(payload) + 1).to_bytes(2, "big") - + device_id.to_bytes(1, "big") + + len(payload).to_bytes(2, "big") + payload ) return frame diff --git a/pymodbus/pdu/__init__.py b/pymodbus/pdu/__init__.py index 45112f9e1d..e7812a58ea 100644 --- a/pymodbus/pdu/__init__.py +++ b/pymodbus/pdu/__init__.py @@ -2,22 +2,32 @@ __all__ = [ "DecodePDU", - "DiagnosticBase", - "ExceptionResponse", "FileRecord", - "ModbusPDU", - "ReadCoilsRequest", - "ReadDeviceInformationRequest", - "ReadExceptionStatusRequest", - "ReadHoldingRegistersRequest", + "ModbusControlBlock", + "ModbusDeviceIdentification", + "ModbusPdu", + "PDUexception", + "StoreGet", + "StoreSet", + "pack_bitstring", + "unpack_bitstring", ] -from .bit_message import ReadCoilsRequest -from .decoders import DecodePDU -from .diag_message import DiagnosticBase -from .exceptionresponse import ExceptionResponse -from .file_message import FileRecord -from .mei_message import ReadDeviceInformationRequest -from .other_message import ReadExceptionStatusRequest -from .pdu import ModbusPDU -from .register_message import ReadHoldingRegistersRequest +from .data_message import PDUreadCoils +from .device import ModbusControlBlock, ModbusDeviceIdentification +from .diag_message import PDUdiagnostic +from .other_message import FileRecord, PDUreadExceptionStatus +from .pdu import ( + DecodePDU, + ModbusPdu, + PDUexception, + StoreGet, + StoreSet, + pack_bitstring, + unpack_bitstring, +) + + +_ = PDUreadCoils +_ = PDUdiagnostic +_ = PDUreadExceptionStatus diff --git a/pymodbus/pdu/bit_message.py b/pymodbus/pdu/bit_message.py deleted file mode 100644 index 98d6fa5363..0000000000 --- a/pymodbus/pdu/bit_message.py +++ /dev/null @@ -1,301 +0,0 @@ -"""Bit Reading Request/Response messages.""" - -import struct -from collections.abc import Sequence -from typing import cast - -from ..constants import ExcCodes, ModbusStatus -from ..datastore import ModbusServerContext -from .decoders import DecodePDU -from .exceptionresponse import ExceptionResponse -from .pdu import ModbusPDU -from .utils import pack_bitstring, unpack_bitstring - - -class ReadCoilsRequest(ModbusPDU): - """ReadCoilsRequest.""" - - function_code = 1 - MAX_COUNT = 2000 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 - - def x_encode(self) -> bytes: - """Encode a request pdu.""" - self.verifyCount(self.MAX_COUNT) - self.verifyAddress() - return struct.pack(">HH", self.address, self.count) - - def x_decode(self, data: bytes) -> None: - """Decode a request pdu.""" - self.address, self.count = struct.unpack(">HH", data[:4]) - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Run request against a datastore.""" - if not 1 <= self.count <= self.MAX_COUNT: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - values = await context.async_getValues( - device_id, self.function_code, self.address, self.count - ) - if isinstance(values, ExcCodes): - return ExceptionResponse(self.function_code, values) - return ReadCoilsResponse( - dev_id=self.dev_id, - transaction_id=self.transaction_id, - bits=cast(list[bool], values), - ) - - -class ReadDiscreteInputsRequest(ModbusPDU): - """ReadDiscreteInputsRequest.""" - - function_code = 2 - MAX_COUNT = 2000 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 - - def x_encode(self) -> bytes: - """Encode a request pdu.""" - self.verifyCount(self.MAX_COUNT) - self.verifyAddress() - return struct.pack(">HH", self.address, self.count) - - def x_decode(self, data: bytes) -> None: - """Decode a request pdu.""" - self.address, self.count = struct.unpack(">HH", data[:4]) - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Run request against a datastore.""" - if not 1 <= self.count <= self.MAX_COUNT: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - values = await context.async_getValues( - device_id, self.function_code, self.address, self.count - ) - if isinstance(values, ExcCodes): - return ExceptionResponse(self.function_code, values) - return ReadDiscreteInputsResponse( - dev_id=self.dev_id, - transaction_id=self.transaction_id, - bits=cast(list[bool], values), - ) - - -class ReadCoilsResponse(ModbusPDU): - """ReadCoilsResponse.""" - - function_code = 1 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 - - def x_encode(self) -> bytes: - """Encode response pdu.""" - result = pack_bitstring(self.bits) - return struct.pack(">B", len(result)) + result - - def x_decode(self, data: bytes) -> None: - """Decode response pdu.""" - self.bits = unpack_bitstring(data[1:]) - - -class ReadDiscreteInputsResponse(ModbusPDU): - """ReadDiscreteInputsResponse.""" - - function_code = 2 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 - - def x_encode(self) -> bytes: - """Encode response pdu.""" - result = pack_bitstring(self.bits) - return struct.pack(">B", len(result)) + result - - def x_decode(self, data: bytes) -> None: - """Decode response pdu.""" - self.bits = unpack_bitstring(data[1:]) - - -class WriteSingleCoilResponse(ModbusPDU): - """WriteSingleCoilResponse.""" - - function_code = 5 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 - - def x_encode(self) -> bytes: - """Encode write coil request.""" - self.verifyAddress() - val = ModbusStatus.ON if self.bits[0] else ModbusStatus.OFF - return struct.pack(">HH", self.address, val) - - def x_decode(self, data: bytes) -> None: - """Decode a write coil request.""" - self.address, value = struct.unpack(">HH", data[:4]) - self.bits = [bool(value)] - - -class WriteSingleCoilRequest(ModbusPDU): - """WriteSingleCoilRequest.""" - - function_code = 5 - _value: int | None = None - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 - - def x_encode(self) -> bytes: - """Encode write coil request.""" - self.verifyAddress() - val = ModbusStatus.ON if self.bits[0] else ModbusStatus.OFF - return struct.pack(">HH", self.address, val) - - def x_decode(self, data: bytes) -> None: - """Decode a write coil request.""" - self.address, self._value = struct.unpack(">HH", data[:4]) - self.bits = [bool(self._value)] - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Run a request against a datastore.""" - if self._value not in (None, ModbusStatus.ON, ModbusStatus.OFF): - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - if rc := await context.async_setValues( - device_id, self.function_code, self.address, self.bits - ): - return ExceptionResponse(self.function_code, rc) - values = await context.async_getValues( - device_id, self.function_code, self.address, 1 - ) - if isinstance(values, ExcCodes): - return ExceptionResponse(self.function_code, values) - return WriteSingleCoilResponse( - address=self.address, - bits=cast(list[bool], values), - dev_id=self.dev_id, - transaction_id=self.transaction_id, - ) - - -class WriteMultipleCoilsRequest(ModbusPDU): - """WriteMultipleCoilsRequest.""" - - function_code = 15 - count: int - byte_count: int | None - data_byte_count: int - MAX_COUNT = 1968 # 0x07B0, largest count whose PDU fits in 253 bytes - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[6]) + 6 + 3 - - def __init__( - self, - address: int = 0, - bits: Sequence[bool] | None = None, - dev_id: int = 0, - transaction_id: int = 0, - ) -> None: - """Initialize a write multiple coils request.""" - super().__init__( - address=address, - bits=bits, - dev_id=dev_id, - transaction_id=transaction_id, - ) - self.count = len(self.bits) - self.byte_count = None - self.data_byte_count = 0 - - def x_encode(self) -> bytes: - """Encode write coils request.""" - self.count = len(self.bits) - self.verifyAddress() - self.verifyCount(self.MAX_COUNT) - byte_count = (self.count + 7) // 8 - return struct.pack( - ">HHB", self.address, self.count, byte_count - ) + pack_bitstring(self.bits) - - def x_decode(self, data: bytes) -> None: - """Decode a write coils request.""" - self.address, self.count, self.byte_count = struct.unpack(">HHB", data[0:5]) - self.data_byte_count = len(data) - 5 - self.bits = unpack_bitstring(data[5 : 5 + cast(int, self.byte_count)])[ - : self.count - ] - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Run a request against a datastore.""" - if self.byte_count is None: - self.count = len(self.bits) - elif not 1 <= self.count <= self.MAX_COUNT: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - else: - expected_byte_count = (self.count + 7) // 8 - if ( - self.byte_count != expected_byte_count - or self.data_byte_count != self.byte_count - ): - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - rc = await context.async_setValues( - device_id, self.function_code, self.address, self.bits - ) - if rc: - return ExceptionResponse(self.function_code, rc) - - return WriteMultipleCoilsResponse( - address=self.address, - count=self.count, - dev_id=self.dev_id, - transaction_id=self.transaction_id, - ) - - -class WriteMultipleCoilsResponse(ModbusPDU): - """WriteMultipleCoilsResponse.""" - - function_code = 15 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 - - def x_encode(self) -> bytes: - """Encode write coils response.""" - return struct.pack(">HH", self.address, self.count) - - def x_decode(self, data: bytes) -> None: - """Decode a write coils response.""" - self.address, self.count = struct.unpack(">HH", data[:4]) - - -DecodePDU.add_pdu(ReadCoilsRequest, ReadCoilsResponse) -DecodePDU.add_pdu(ReadDiscreteInputsRequest, ReadDiscreteInputsResponse) -DecodePDU.add_pdu(WriteSingleCoilRequest, WriteSingleCoilResponse) -DecodePDU.add_pdu(WriteMultipleCoilsRequest, WriteMultipleCoilsResponse) diff --git a/pymodbus/pdu/data_message.py b/pymodbus/pdu/data_message.py new file mode 100644 index 0000000000..1da71b98b2 --- /dev/null +++ b/pymodbus/pdu/data_message.py @@ -0,0 +1,592 @@ +"""Bit Reading Request/Response messages.""" + +import struct +from collections.abc import Sequence +from copy import copy +from typing import cast + +from ..constants import ExcCodes, ModbusStatus +from .pdu import ( + DecodePDU, + ModbusPdu, + StoreGet, + StoreSet, + pack_bitstring, + unpack_bitstring, +) + + +class PDUreadCoils(ModbusPdu): + """ReadCoils.""" + + function_code = 1 + MAX_COUNT = 2000 + + def __init__( + self, + *args, + address: int | None = None, + count: int | None = None, + bits: Sequence[bool] | None = None, + **kwargs, + ) -> None: + """Initialize.""" + if bits and not count: + count = len(bits) + self.address: int = address if address is not None else -1 + self.count: int = count if count is not None else -1 + self.bits = copy(bits) or [] + super().__init__(*args, **kwargs) + + def verify(self) -> str | None: + """Verify params.""" + if not 1 <= self.count <= self.MAX_COUNT: + return f"Invalid count({self.count})" + if self.is_request and not 0 <= self.address <= 65535: + return f"Invalid address({self.address})" + return None + + def __str__(self) -> str: + """Build representation of pdu.""" + return ( + super().__str__() + + f"address={self.address}, count={self.count}, bits={self.bits}" + ) + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + if (lx := len(data)) < 3: + return 0 + if self.is_request: + return 0 if lx < 6 else 6 + leff = int(data[2]) + 3 + return 0 if lx < leff else leff + + def to_bytes(self) -> bytes: + """Encode the message.""" + if text := self.verify(): + self.raiseExp(text) + if self.is_request: + return self.preamble() + struct.pack(">HH", self.address, self.count) + result = pack_bitstring(self.bits) + return self.preamble() + struct.pack(">B", len(result)) + result + + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if self.is_request: + self.address, self.count = struct.unpack(">HH", data[2:6]) + else: + byte_count = int(data[2]) + self.bits = unpack_bitstring(data[3:]) + self.count = len(self.bits) + if self.count != byte_count * 8: + return ( + f"byte_count({byte_count}) * 8 not identical to count({self.count})" + ) + if text := self.verify(): + return text + return None + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get bits from datastore.""" + values = await v_get(self.dev_id, self.function_code, self.address, self.count) + if isinstance(values, ExcCodes): + return self.respondExp(values) + self.is_request = False + self.bits = cast(list[bool], values) + return self + + +class PDUreadDiscreteInputs(PDUreadCoils): + """ReadDiscreteInputsRequest.""" + + function_code = 2 + + +class PDUwriteSingleCoil(PDUreadCoils): + """WriteSingleCoil.""" + + function_code = 5 + MAX_COUNT = 1 + + def verify(self) -> str | None: + """Verify params.""" + if text := super().verify(): + return text + if len(self.bits) != 1: + return f"Invalid bits({self.bits})" + return None + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + return 0 if len(data) < 6 else 6 + + def to_bytes(self) -> bytes: + """Encode the message.""" + if text := self.verify(): + self.raiseExp(text) + val = ModbusStatus.ON if self.bits[0] else ModbusStatus.OFF + return super().preamble() + struct.pack(">HH", self.address, val) + + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + self.address, value = struct.unpack(">HH", data[2:]) + self.bits = ( + [bool(value)] if value in (ModbusStatus.ON, ModbusStatus.OFF) else [] + ) + self.count = len(self.bits) + if text := self.verify(): + return text + return None + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get bits from datastore.""" + if not self.bits: + return self.respondExp(ExcCodes.ILLEGAL_VALUE) + if rc := await v_set(self.dev_id, self.function_code, self.address, self.bits): + return self.respondExp(rc) + values = await v_get(self.dev_id, self.function_code, self.address, self.count) + if isinstance(values, ExcCodes): + return self.respondExp(values) + self.is_request = False + self.bits = cast(list[bool], values) + return self + + +class PDUwriteMultipleCoils(PDUreadCoils): + """WriteMultipleCoils.""" + + function_code = 15 + MAX_COUNT = 1968 + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + lx = len(data) + if not self.is_request: + return 0 if lx < 6 else 6 + return 0 if lx < 7 or lx < (leff := int(data[6]) + 7) else leff + + def to_bytes(self) -> bytes: + """Encode the message.""" + if text := self.verify(): + self.raiseExp(text) + if self.is_request: + byte_count = (self.count + 7) // 8 + return ( + self.preamble() + + struct.pack( + ">HHB", + self.address, + self.count, + byte_count, + ) + + pack_bitstring(self.bits) + ) + return self.preamble() + struct.pack(">HH", self.address, self.count) + + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if self.is_request: + self.address, self.count, byte_count = struct.unpack(">HHB", data[2:7]) + self.bits = unpack_bitstring(data[7:]) + if (self.count + 7) // 8 != byte_count: + return f"byte_count({byte_count}) not identical to count({self.count})" + else: + self.address, self.count = struct.unpack(">HH", data[2:]) + if text := self.verify(): + return text + return None + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get bits from datastore.""" + if rc := await v_set(self.dev_id, self.function_code, self.address, self.bits): + return self.respondExp(rc) + values = await v_get(self.dev_id, self.function_code, self.address, self.count) + if isinstance(values, ExcCodes): + return self.respondExp(values) + self.is_request = False + self.bits = cast(list[bool], values) + return self + + +class PDUreadHoldingRegisters(ModbusPdu): + """ReadHoldingRegisters.""" + + function_code = 3 + MAX_COUNT = 125 + + def __init__( + self, + *args, + address: int | None = None, + count: int | None = None, + registers: Sequence[int] | None = None, + **kwargs, + ) -> None: + """Initialize.""" + if registers and not count: + count = len(registers) + self.address: int = address if address is not None else -1 + self.count: int = count if count is not None else -1 + self.registers = copy(registers) or [] + super().__init__(*args, **kwargs) + + def verify(self) -> str | None: + """Verify params.""" + if not 0 <= self.count <= self.MAX_COUNT: + return f"Invalid count({self.count})" + if self.is_request and not 0 <= self.address <= 65535: + return f"Invalid address({self.address})" + return None + + def __str__(self) -> str: + """Build representation of pdu.""" + return ( + super().__str__() + + f"address={self.address}, count={self.count}, registers={self.registers}" + ) + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + if (lx := len(data)) < 3: + return 0 + if self.is_request: + if lx < 6: + return 0 + return 6 + return 0 if lx < (leff := int(data[2]) + 3) else leff + + def to_bytes(self) -> bytes: + """Encode the message.""" + if text := self.verify(): + self.raiseExp(text) + if self.is_request: + return self.preamble() + struct.pack(">HH", self.address, self.count) + result = struct.pack(">B", len(self.registers) * 2) + for register in self.registers: + result += struct.pack(">H", register) + return self.preamble() + result + + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if self.is_request: + self.address, self.count = struct.unpack(">HH", data[2:]) + else: + if (byte_count := int(data[2])) + 3 != (x := len(data)): + return f"byte_count {byte_count} > length of packet {x}" + self.registers = [] + for i in range(3, byte_count + 3, 2): + self.registers.append(struct.unpack(">H", data[i : i + 2])[0]) + self.count = len(self.registers) + if text := self.verify(): + return text + return None + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get bits from datastore.""" + values = await v_get(self.dev_id, self.function_code, self.address, self.count) + if isinstance(values, ExcCodes): + return self.respondExp(values) + self.is_request = False + self.registers = cast(list[int], values) + return self + + +class PDUreadInputRegisters(PDUreadHoldingRegisters): + """ReadInputRegisters.""" + + function_code = 4 + + +class PDUwriteSingleRegister(PDUreadHoldingRegisters): + """WriteSingleRegister.""" + + function_code = 6 + MAX_COUNT = 1 + + def verify(self) -> str | None: + """Verify params.""" + if text := super().verify(): + return text + if len(self.registers) != 1: + return f"Invalid registers({self.registers})" + return None + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + return 0 if len(data) < 6 else 6 + + def to_bytes(self) -> bytes: + """Encode the message.""" + if text := self.verify(): + self.raiseExp(text) + return self.preamble() + struct.pack(">HH", self.address, self.registers[0]) + + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + self.address, register = struct.unpack(">HH", data[2:]) + self.registers = [register] + self.count = len(self.registers) + if text := self.verify(): + return text + return None + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get registers from datastore.""" + if rc := await v_set( + self.dev_id, self.function_code, self.address, self.registers + ): + return self.respondExp(rc) + + registers = await v_get(self.dev_id, self.function_code, self.address, 1) + if isinstance(registers, ExcCodes): + return self.respondExp(registers) + self.is_request = False + self.registers = cast(list[int], registers) + return self + + +class PDUwriteMultipleRegisters(PDUreadHoldingRegisters): + """WriteMultipleRegisters.""" + + function_code = 16 + MAX_COUNT = 123 + + def verify(self) -> str | None: + """Verify params.""" + if text := super().verify(): + return text + if self.is_request and len(self.registers) != self.count: + return f"Invalid registers({self.registers})" + return None + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + lx = len(data) + if not self.is_request: + return 0 if lx < 6 else 6 + return 0 if lx < 7 or lx < (leff := int(data[6]) + 7) else leff + + def to_bytes(self) -> bytes: + """Encode the message.""" + if text := self.verify(): + self.raiseExp(text) + if self.is_request: + packet = struct.pack(">HHB", self.address, self.count, self.count * 2) + for value in self.registers: + packet += struct.pack(">H", value) + return self.preamble() + packet + return self.preamble() + struct.pack(">HH", self.address, self.count) + + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if self.is_request: + self.address, self.count, byte_count = struct.unpack(">HHB", data[2:7]) + if (x_len := len(data)) < byte_count + 7: + return f"byte_count({byte_count}) larger than packet)" + self.registers = [ + struct.unpack(">H", data[idx : idx + 2])[0] + for idx in range(7, x_len, 2) + ] + self.count = len(self.registers) + if self.count * 2 != byte_count: + return f"byte_count({byte_count}) not identical to count({self.count})" + else: + self.address, self.count = struct.unpack(">HH", data[2:]) + if text := self.verify(): + return text + return None + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get bits from datastore.""" + if rc := await v_set( + self.dev_id, self.function_code, self.address, self.registers + ): + return self.respondExp(rc) + self.is_request = False + return self + + +class PDUreadWriteMultipleRegisters(PDUreadHoldingRegisters): + """ReadWriteMultipleRegisters.""" + + function_code = 23 + MAX_COUNT = 125 + MAX_WRITE_COUNT = 121 + + def __init__( + self, + *args, + write_address: int | None = None, + **kwargs, + ) -> None: + """Initialize.""" + self.write_address: int = write_address if write_address is not None else -1 + super().__init__(*args, **kwargs) + + def verify(self) -> str | None: + """Verify params.""" + if text := super().verify(): + return text + if not 0 <= (x := len(self.registers)) <= self.MAX_WRITE_COUNT: + return f"Invalid write count({x})" + if self.is_request and not 0 <= self.write_address <= 65535: + return f"Invalid write_address({self.write_address})" + return None + + def __str__(self) -> str: + """Build representation of pdu.""" + return ( + super().__str__() + + f"address={self.address}, count={self.count}, write_address={self.write_address}, registers={self.registers}" + ) + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + if (lx := len(data)) < 6: + return 0 + if self.is_request: + return 0 if lx < 11 or lx < (leff := int(data[10]) + 11) else leff + return 0 if lx < (leff := int(data[2]) + 3) else leff + + def to_bytes(self) -> bytes: + """Encode the message.""" + if text := self.verify(): + self.raiseExp(text) + reg_len = len(self.registers) + reg_to_bytes = b"" + for register in self.registers: + reg_to_bytes += struct.pack(">H", register) + if self.is_request: + return ( + self.preamble() + + struct.pack( + ">HHHHB", + self.address, + self.count, + self.write_address, + reg_len, + reg_len * 2, + ) + + reg_to_bytes + ) + return self.preamble() + struct.pack(">B", reg_len * 2) + reg_to_bytes + + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if self.is_request: + (self.address, self.count, self.write_address, write_count, byte_count) = ( + struct.unpack(">HHHHB", data[2:11]) + ) + if byte_count + 11 != (x_len := len(data)): + return f"byte_count {byte_count} > length of packet {x_len}" + if byte_count != write_count * 2: + return f"byte_count {byte_count} * 2 not identical to {write_count}" + self.registers = [ + struct.unpack(">H", data[i : i + 2])[0] for i in range(11, x_len, 2) + ] + else: + if (byte_count := int(data[2])) + 3 != (x_len := len(data)): + return f"byte_count {byte_count} > length of packet {x_len}" + self.registers = [] + for i in range(3, x_len, 2): + self.registers.append(struct.unpack(">H", data[i : i + 2])[0]) + self.count = len(self.registers) + if text := self.verify(): + return text + return None + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get bits from datastore.""" + rc = await v_set( + self.dev_id, self.function_code, self.write_address, self.registers + ) + if rc: + return self.respondExp(rc) + values = await v_get(self.dev_id, self.function_code, self.address, self.count) + if isinstance(values, ExcCodes): + return self.respondExp(values) + self.is_request = False + self.registers = cast(list[int], values) + return self + + +class PDUmaskWriteRegister(PDUreadHoldingRegisters): + """MaskWriteRegister.""" + + function_code = 0x16 + MAX_COUNT = 123 + + def __init__( + self, + *args, + and_mask: int = 0xFFFF, + or_mask: int = 0x0000, + **kwargs, + ) -> None: + """Initialize.""" + super().__init__(*args, **kwargs) + self.and_mask = and_mask + self.or_mask = or_mask + self.count = 1 + + def verify(self) -> str | None: + """Verify params.""" + if text := super().verify(): + return text + if not 0x0000 <= self.and_mask <= 0xFFFF: + return "Illegal and_mask" + if not 0x0000 <= self.or_mask <= 0xFFFF: + return "Illegal or_mask" + return None + + def __str__(self) -> str: + """Build representation of pdu.""" + return super().__str__() + f", and_mask={self.and_mask}, or_mask={self.or_mask}" + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + return 0 if len(data) < 8 else 8 + + def to_bytes(self) -> bytes: + """Encode the message.""" + if text := self.verify(): + self.raiseExp(text) + return self.preamble() + struct.pack( + ">HHH", self.address, self.and_mask, self.or_mask + ) + + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + self.address, self.and_mask, self.or_mask = struct.unpack(">HHH", data[2:8]) + self.count = 1 + if text := self.verify(): + return text + return None + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get bits from datastore.""" + values = await v_get(self.dev_id, self.function_code, self.address, self.count) + if isinstance(values, ExcCodes): + return self.respondExp(values) + values = (cast(Sequence[int], values)[0] & self.and_mask) | ( + self.or_mask & ~self.and_mask + ) + if rc := await v_set( + self.dev_id, self.function_code, self.address, self.registers + ): + return self.respondExp(rc) + self.is_request = False + return self + + +DecodePDU.add_pdu(PDUreadCoils) +DecodePDU.add_pdu(PDUreadDiscreteInputs) +DecodePDU.add_pdu(PDUwriteSingleCoil) +DecodePDU.add_pdu(PDUwriteMultipleCoils) +DecodePDU.add_pdu(PDUreadHoldingRegisters) +DecodePDU.add_pdu(PDUreadInputRegisters) +DecodePDU.add_pdu(PDUwriteMultipleRegisters) +DecodePDU.add_pdu(PDUwriteSingleRegister) +DecodePDU.add_pdu(PDUreadWriteMultipleRegisters) +DecodePDU.add_pdu(PDUmaskWriteRegister) diff --git a/pymodbus/pdu/decoders.py b/pymodbus/pdu/decoders.py deleted file mode 100644 index d0114684b3..0000000000 --- a/pymodbus/pdu/decoders.py +++ /dev/null @@ -1,105 +0,0 @@ -"""Modbus Request/Response Decoders.""" - -from __future__ import annotations - -import copy -import struct - -from ..exceptions import MessageRegisterException, ModbusIOException -from ..logging import Log -from .exceptionresponse import ExceptionResponse -from .pdu import ModbusPDU - - -class DecodePDU: - """Decode pdu requests/responses (server/client).""" - - pdu_table: dict[int, tuple[type[ModbusPDU], type[ModbusPDU]]] = {} - pdu_sub_table: dict[int, dict[int, tuple[type[ModbusPDU], type[ModbusPDU]]]] = {} - - def __init__(self, is_server: bool) -> None: - """Initialize function_tables.""" - self.pdu_inx = 0 if is_server else 1 - self.is_server = is_server - - def _lookupPduClass(self, data: bytes) -> type[ModbusPDU] | None: - """Use `function_code` to determine the class of the PDU.""" - if (func_code := int(data[1])) > 0x80: - return ExceptionResponse - if not (pdu := self.pdu_table.get(func_code, (None, None))[self.pdu_inx]): - return None - if (sub_func_code := pdu.decode_sub_function_code(data)) < 0: - return pdu - return self.pdu_sub_table[func_code].get(sub_func_code, (None, None))[ - self.pdu_inx - ] - - def list_function_codes(self): - """Return list of function codes.""" - return list(self.pdu_table) - - @classmethod - def add_pdu(cls, req: type[ModbusPDU], resp: type[ModbusPDU]): - """Register request/response.""" - cls.pdu_table[req.function_code] = (req, resp) - - @classmethod - def add_sub_pdu(cls, req: type[ModbusPDU], resp: type[ModbusPDU]): - """Register request/response.""" - if req.function_code not in cls.pdu_sub_table: - cls.pdu_sub_table[req.function_code] = {} - cls.pdu_sub_table[req.function_code][req.sub_function_code] = (req, resp) - - def register(self, custom_class: type[ModbusPDU]) -> None: - """Register a function and sub function class with the decoder.""" - if not issubclass(custom_class, ModbusPDU): - raise MessageRegisterException( - f'"{custom_class.__class__.__name__}" is Not a valid Modbus Message' - ". Class needs to be derived from `ModbusPDU` " - ) - if "pdu_table" not in self.__dict__: - self.pdu_table = copy.deepcopy(DecodePDU.pdu_table) - self.pdu_table[custom_class.function_code] = (custom_class, custom_class) - - def decode(self, frame: bytes) -> ModbusPDU: - """Decode a frame.""" - if not frame: - raise ModbusIOException("Cannot decode empty frame") - function_code = 0 - try: - if (function_code := int(frame[0])) > 0x80: - if self.is_server: - raise ModbusIOException( - f"Reserved function code {function_code}", - function_code=function_code, - ) - pdu_exp = ExceptionResponse(function_code & 0x7F) - pdu_exp.from_frame(False, frame) - return pdu_exp - if not (pdu_class := self._lookupPduClass(b"\x00" + frame)): - raise ModbusIOException( - f"Unknown response {function_code}", function_code=function_code - ) - pdu = pdu_class() - pdu.x_decode(frame[1:]) - Log.debug( - "decoded PDU function_code({} sub {}) -> {} ", - pdu.function_code, - pdu.sub_function_code, - str(pdu), - ) - return pdu - except (ValueError, IndexError, struct.error) as exc: - raise ModbusIOException( - f"Unable to decode frame {exc}", function_code=function_code - ) from exc - - def calculateRtuFrameSize(self, data: bytes) -> int: - """Calculate the size of a PDU.""" - if not (pdu_class := self._lookupPduClass(data)): - return 0 - return pdu_class.x_calculateRtuFrameSize(data) - - def encode(self, pdu: ModbusPDU) -> bytes: - """Calculate the size of a PDU.""" - return pdu.x_encode() diff --git a/pymodbus/pdu/device.py b/pymodbus/pdu/device.py index f1f54cc668..95b3788037 100644 --- a/pymodbus/pdu/device.py +++ b/pymodbus/pdu/device.py @@ -7,19 +7,188 @@ from __future__ import annotations - -__all__ = [ - "DeviceInformationFactory", - "ModbusDeviceIdentification", - "ModbusPlusStatistics", -] - import struct +from abc import ABC, abstractmethod -# pylint: disable=missing-type-doc from ..constants import DeviceInformation +from ..exceptions import ParameterException from ..utilities import dict_property -from .events import ModbusEvent +from .pdu import pack_bitstring, unpack_bitstring + + +# ---------------------------------------------------------------------------# +# Modbus Event +# +# An event byte returned by the Get Communications Event Log function +# can be any one of four types. The type is defined by bit 7 +# (the high-order bit) in each byte. It may be further defined by bit 6. +# ---------------------------------------------------------------------------# +class ModbusEvent(ABC): + """Define modbus events.""" + + @abstractmethod + def encode(self) -> bytes: + """Encode the status bits to an event message.""" + + @abstractmethod + def decode(self, event): + """Decode the event message to its status bits.""" + + +class RemoteReceiveEvent(ModbusEvent): + """Remote device MODBUS Receive Event. + + The remote device stores this type of event byte when a query message + is received. It is stored before the remote device processes the message. + This event is defined by bit 7 set to logic "1". The other bits will be + set to a logic "1" if the corresponding condition is TRUE. The bit layout + is:: + + Bit Contents + ---------------------------------- + 0 Not Used + 2 Not Used + 3 Not Used + 4 Character Overrun + 5 Currently in Listen Only Mode + 6 Broadcast Receive + 7 1 + """ + + def __init__(self, overrun=False, listen=False, broadcast=False): + """Initialize a new event instance.""" + self.overrun = overrun + self.listen = listen + self.broadcast = broadcast + + def encode(self) -> bytes: + """Encode the status bits to an event message.""" + bits = [False] * 3 + bits += [self.overrun, self.listen, self.broadcast, True] + packet = pack_bitstring(bits) + return packet + + def decode(self, event: bytes) -> None: + """Decode the event message to its status bits.""" + bits = unpack_bitstring(event) + self.overrun = bits[4] + self.listen = bits[5] + self.broadcast = bits[6] + + +class RemoteSendEvent(ModbusEvent): + """Remote device MODBUS Send Event. + + The remote device stores this type of event byte when it finishes + processing a request message. It is stored if the remote device + returned a normal or exception response, or no response. + + This event is defined by bit 7 set to a logic "0", with bit 6 set to a "1". + The other bits will be set to a logic "1" if the corresponding + condition is TRUE. The bit layout is:: + + Bit Contents + ----------------------------------------------------------- + 0 Read Exception Sent (Exception Codes 1-3) + 1 Device Abort Exception Sent (Exception Code 4) + 2 Device Busy Exception Sent (Exception Codes 5-6) + 3 Device Program NAK Exception Sent (Exception Code 7) + 4 Write Timeout Error Occurred + 5 Currently in Listen Only Mode + 6 1 + 7 0 + """ + + def __init__( + self, + read=False, + device_abort=False, + device_busy=False, + device_nak=False, + write_timeout=False, + listen=False, + ): + """Initialize a new event instance.""" + self.read = read + self.device_abort = device_abort + self.device_busy = device_busy + self.device_nak = device_nak + self.write_timeout = write_timeout + self.listen = listen + + def encode(self): + """Encode the status bits to an event message.""" + bits = [ + self.read, + self.device_abort, + self.device_busy, + self.device_nak, + self.write_timeout, + self.listen, + ] + bits += [True, False] + packet = pack_bitstring(bits) + return packet + + def decode(self, event): + """Decode the event message to its status bits.""" + bits = unpack_bitstring(event) + self.read = bits[0] + self.device_abort = bits[1] + self.device_busy = bits[2] + self.device_nak = bits[3] + self.write_timeout = bits[4] + self.listen = bits[5] + + +class EnteredListenModeEvent(ModbusEvent): + """Enter Remote device Listen Only Mode. + + The remote device stores this type of event byte when it enters + the Listen Only Mode. The event is defined by a content of 04 hex. + """ + + value = 0x04 + __encoded = b"\x04" + + def encode(self): + """Encode the status bits to an event message.""" + return self.__encoded + + def decode(self, event): + """Decode the event message to its status bits.""" + if event != self.__encoded: + raise ParameterException("Invalid decoded value") + + +class CommunicationRestartEvent(ModbusEvent): + """Restart remote device Initiated Communication. + + The remote device stores this type of event byte when its communications + port is restarted. The remote device can be restarted by the Diagnostics + function (code 08), with sub-function Restart Communications Option + (code 00 01). + + That function also places the remote device into a "Continue on Error" + or "Stop on Error" mode. If the remote device is placed into "Continue on + Error" mode, the event byte is added to the existing event log. If the + remote device is placed into "Stop on Error" mode, the byte is added to + the log and the rest of the log is cleared to zeros. + + The event is defined by a content of zero. + """ + + value = 0x00 + __encoded = b"\x00" + + def encode(self): + """Encode the status bits to an event message.""" + return self.__encoded + + def decode(self, event): + """Decode the event message to its status bits.""" + if event != self.__encoded: + raise ParameterException("Invalid decoded value") # ---------------------------------------------------------------------------# @@ -87,10 +256,7 @@ def __init__(self) -> None: self.reset() def __iter__(self): - """Iterate over the statistics. - - :returns: An iterator of the modbus plus statistics - """ + """Iterate over the statistics.""" return iter(self.stat_data.items()) def reset(self) -> None: @@ -99,17 +265,11 @@ def reset(self) -> None: self.stat_data[key] = [0x00] * len(self.stat_data[key]) def summary(self): - """Return a summary of the modbus plus statistics. - - :returns: 54 16-bit words representing the status - """ + """Return a summary of the modbus plus statistics.""" return iter(self.stat_data.values()) - def x_encode(self) -> list[int]: - """Return a summary of the modbus plus statistics. - - :returns: An iterator over lists of 8-bit integers representing each statistic - """ + def encode(self) -> list[int]: + """Return a summary of the modbus plus statistics.""" values = [v for sublist in self.stat_data.values() for v in sublist] total = [(values[i] << 8) | values[i + 1] for i in range(0, len(values), 2)] return total @@ -151,15 +311,7 @@ class ModbusDeviceIdentification: ] def __init__(self, info=None, info_name=None): - """Initialize the datastore with the elements you need. - - (note acceptable range is [0x00-0x06,0x80-0xFF] inclusive) - - :param info: Device information as {int:string} dictionary - :param info_name: Device information as {name:string} dictionary - """ - # Copy the defaults, so each identity has its own values instead of - # all instances writing into the class-level dict. + """Initialize the datastore with the elements you need.""" self.stat_data = dict(self.stat_data) if isinstance(info_name, dict): for key in info_name: @@ -172,49 +324,28 @@ def __init__(self, info=None, info_name=None): self.stat_data[key] = info[key] def __iter__(self): - """Iterate over the device information. - - :returns: An iterator of the device information - """ + """Iterate over the device information.""" return iter(self.stat_data.items()) def summary(self): - """Return a summary of the main items. - - :returns: An dictionary of the main items - """ + """Return a summary of the main items.""" return dict(zip(self.__names, iter(self.stat_data.values()))) def update(self, value): - """Update the values of this identity. - - using another identify as the value - - :param value: The value to copy values from - """ + """Update the values of this identity.""" self.stat_data.update(value) def __setitem__(self, key, value): - """Access the device information. - - :param key: The register to set - :param value: The new value for referenced register - """ + """Access the device information.""" if key not in [0x07, 0x08]: self.stat_data[key] = value def __getitem__(self, key): - """Access the device information. - - :param key: The register to read - """ + """Access the device information.""" return self.stat_data.get(key, "") def __str__(self): - """Build a representation of the device. - - :returns: A string representation of the device - """ + """Build a representation of the device.""" return "DeviceIdentity" # -------------------------------------------------------------------------# @@ -262,34 +393,18 @@ class DeviceInformationFactory: # pylint: disable=too-few-public-methods @classmethod def get(cls, control, read_code=DeviceInformation.BASIC, object_id=0x00): - """Get the requested device data from the system. - - :param control: The control block to pull data from - :param read_code: The read code to process - :param object_id: The specific object_id to read - :returns: The requested data (id, length, value) - """ + """Get the requested device data from the system.""" identity = control.Identity return cls.__lookup[read_code](cls, identity, object_id) @classmethod def __get(cls, identity, object_id): # pylint: disable=unused-private-member - """Read a single object_id from the device information. - - :param identity: The identity block to pull data from - :param object_id: The specific object id to read - :returns: The requested data (id, length, value) - """ + """Read a single object_id from the device information.""" return {object_id: identity[object_id]} @classmethod def __gets(cls, identity, object_ids): # pylint: disable=unused-private-member - """Read multiple object_ids from the device information. - - :param identity: The identity block to pull data from - :param object_ids: The specific object ids to read - :returns: The requested data (id, length, value) - """ + """Read multiple object_ids from the device information.""" return {oid: identity[oid] for oid in object_ids if identity[oid]} @@ -375,19 +490,11 @@ class ModbusCountersHandler: ] def __iter__(self): - """Iterate over the device counters. - - :returns: An iterator of the device counters - """ + """Iterate over the device counters.""" return zip(self.__names, iter(self.stat_data.values())) def update(self, values): - """Update the values of this identity. - - using another identify as the value - - :param values: The value to copy values from - """ + """Update the values of this identity.""" for k, v_item in iter(values.items()): v_item += self.__getattribute__( # pylint: disable=unnecessary-dunder-call k @@ -399,10 +506,7 @@ def reset(self): self.stat_data = dict.fromkeys(range(9), 0x00) def summary(self): - """Return a summary of the counters current status. - - :returns: A byte with each bit representing each counter - """ + """Return a summary of the counters current status.""" count, result = 0x01, 0x00 for i in iter(self.stat_data.values()): if i != 0x00: # pylint: disable=compare-to-zero @@ -451,17 +555,11 @@ class ModbusControlBlock: # Magic # -------------------------------------------------------------------------# def __str__(self): - """Build a representation of the control block. - - :returns: A string representation of the control block - """ + """Build a representation of the control block.""" return "ModbusControl" def __iter__(self): - """Iterate over the device counters. - - :returns: An iterator of the device counters - """ + """Iterate over the device counters.""" return self._counters.__iter__() def __new__(cls): @@ -474,20 +572,14 @@ def __new__(cls): # Events # -------------------------------------------------------------------------# def addEvent(self, event: ModbusEvent): - """Add a new event to the event log. - - :param event: A new event to add to the log - """ + """Add a new event to the event log.""" self._events.insert(0, event) self._events = self._events[0:64] # chomp to 64 entries self.Counter.Event += 1 def getEvents(self): - """Return an encoded collection of the event log. - - :returns: The encoded events packet - """ - events = [event.x_encode() for event in self._events] + """Return an encoded collection of the event log.""" + events = [event.encode() for event in self._events] return b"".join(events) def clearEvents(self): @@ -512,10 +604,7 @@ def reset(self): # Listen Properties # -------------------------------------------------------------------------# def _setListenOnly(self, value): - """Toggle the listen only status. - - :param value: The value to set the listen status to - """ + """Toggle the listen only status.""" self._listen_only = bool(value) ListenOnly = property(lambda s: s._listen_only, _setListenOnly) @@ -524,10 +613,7 @@ def _setListenOnly(self, value): # Mode Properties # -------------------------------------------------------------------------# def _setMode(self, mode): - """Toggle the current serial mode. - - :param mode: The data transfer method in (RTU, ASCII) - """ + """Toggle the current serial mode.""" if mode in {"ASCII", "RTU"}: self._mode = mode @@ -537,10 +623,7 @@ def _setMode(self, mode): # Delimiter Properties # -------------------------------------------------------------------------# def _setDelimiter(self, char): - """Change the serial delimiter character. - - :param char: The new serial delimiter character - """ + """Change the serial delimiter character.""" if isinstance(char, str): self._delimiter = char.encode() if isinstance(char, bytes): @@ -554,19 +637,12 @@ def _setDelimiter(self, char): # Diagnostic Properties # -------------------------------------------------------------------------# def setDiagnostic(self, mapping): - """Set the value in the diagnostic register. - - :param mapping: Dictionary of key:value pairs to set - """ + """Set the value in the diagnostic register.""" for entry in iter(mapping.items()): self._diagnostic[entry[0]] = bool(entry[1]) def getDiagnostic(self, bit): - """Get the value in the diagnostic register. - - :param bit: The bit to get - :returns: The current value of the requested bit - """ + """Get the value in the diagnostic register.""" try: if bit and 0 <= bit < len(self._diagnostic): return self._diagnostic[bit] @@ -575,8 +651,5 @@ def getDiagnostic(self, bit): return None def getDiagnosticRegister(self): - """Get the entire diagnostic register. - - :returns: The diagnostic register collection - """ + """Get the entire diagnostic register.""" return self._diagnostic diff --git a/pymodbus/pdu/diag_message.py b/pymodbus/pdu/diag_message.py index aa17c82c3a..6e7d6db6a5 100644 --- a/pymodbus/pdu/diag_message.py +++ b/pymodbus/pdu/diag_message.py @@ -3,504 +3,434 @@ from __future__ import annotations import struct -from typing import cast +from typing import Any -from ..constants import ModbusPlusOperation -from ..datastore import ModbusServerContext -from .decoders import DecodePDU -from .device import ModbusControlBlock -from .pdu import ModbusPDU -from .utils import pack_bitstring +from ..constants import CLEAR_STATISTICS, DeviceInformation, ExcCodes, MoreData +from .device import DeviceInformationFactory, ModbusControlBlock +from .pdu import DecodePDU, ModbusPdu, PDUexception, StoreGet, StoreSet, pack_bitstring _MCB = ModbusControlBlock() -class DiagnosticBase(ModbusPDU): - """DiagnosticBase.""" +class PDUdiagnostic(ModbusPdu): + """Diagnostic base.""" function_code = 0x08 - sub_function_code: int = 9999 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 def __init__( self, - message: bytes | int | list | tuple | None = 0, - dev_id: int = 1, - transaction_id: int = 0, + *args, + message: bytes | int | list | tuple | None = None, + **kwargs, ) -> None: - """Initialize a diagnostic request.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id) - self.message: bytes | int | list | tuple | None = message + """Initialize.""" + super().__init__(*args, **kwargs) + if isinstance(message, int): + self.message = message.to_bytes(2, "big") + elif isinstance(message, (list, tuple)): + packet = b"" + for piece in message: + packet += struct.pack(">H", piece) + self.message = packet + else: + self.message = message or b"\x00\x00" - def x_encode(self) -> bytes: - """Encode a diagnostic response.""" - packet = struct.pack(">H", self.sub_function_code) - if self.message is not None: - if isinstance(self.message, bytes): - packet += self.message - return packet - if isinstance(self.message, int): - packet += struct.pack(">H", self.message) - return packet - if isinstance(self.message, (list, tuple)): - for piece in self.message: - packet += struct.pack(">H", piece) - return packet - raise TypeError(f"UNKNOWN DIAG message type: {type(self.message)}") - return packet + def __str__(self) -> str: + """Build representation of pdu.""" + return super().__str__() + f", message={self.message}" + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + return 0 if len(data) < 6 else 6 @classmethod def decode_sub_function_code(cls, data: bytes) -> int: - """Decode sub function code (2 bytes).""" + """Decode sub function code.""" return int.from_bytes(data[2:4], "big") - def x_decode(self, data: bytes) -> None: - """Decode a diagnostic request.""" - (self.sub_function_code,) = struct.unpack(">H", data[:2]) - data = data[2:] - if self.sub_function_code == ReturnQueryDataRequest.sub_function_code: - self.message = data - elif data_len := len(data): - if data_len % 2: - data_len += 1 - data += b"0" - if (word_len := data_len // 2) == 1: - (self.message,) = struct.unpack(">H", data[:2]) - else: - self.message = struct.unpack(">" + "H" * word_len, data[: 2 * word_len]) - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Implement dummy.""" - _ = context - response = { - DiagnosticBase.sub_function_code: DiagnosticBase, - ReturnQueryDataResponse.sub_function_code: ReturnQueryDataResponse, - RestartCommunicationsOptionResponse.sub_function_code: RestartCommunicationsOptionResponse, - }[self.sub_function_code] - return response( - message=self.message, dev_id=device_id, transaction_id=self.transaction_id + def to_bytes(self) -> bytes: + """Encode the message.""" + return ( + self.preamble() + struct.pack(">H", self.sub_function_code) + self.message ) + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + (self.sub_function_code,) = struct.unpack(">H", data[2:4]) + self.message = data[4:] -class ReturnQueryDataRequest(DiagnosticBase): - """ReturnQueryDataRequest.""" + def sub_build_response(self) -> None: + """get/set info in _MCB.""" + return - sub_function_code = 0x0000 + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Update internal data.""" + self.is_request = False + self.sub_build_response() + return self -class ReturnQueryDataResponse(DiagnosticBase): - """ReturnQueryDataResponse.""" +class PDUreturnQueryData(PDUdiagnostic): + """ReturnQueryData.""" sub_function_code = 0x0000 -class RestartCommunicationsOptionRequest(DiagnosticBase): - """RestartCommunicationsOptionRequest.""" - - sub_function_code = 0x0001 - - -class RestartCommunicationsOptionResponse(DiagnosticBase): - """RestartCommunicationsOptionResponse.""" +class PDUrestartCommunicationsOption(PDUdiagnostic): + """RestartCommunicationsOption.""" sub_function_code = 0x0001 -class ReturnDiagnosticRegisterRequest(DiagnosticBase): - """ReturnDiagnosticRegisterRequest.""" +class PDUreturnDiagnosticRegister(PDUdiagnostic): + """ReturnDiagnosticRegister.""" sub_function_code = 0x0002 - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - register = pack_bitstring(_MCB.getDiagnosticRegister()) - return ReturnDiagnosticRegisterResponse( - message=register, dev_id=device_id, transaction_id=self.transaction_id - ) + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + self.message = pack_bitstring(_MCB.getDiagnosticRegister()) -class ReturnDiagnosticRegisterResponse(DiagnosticBase): - """ReturnDiagnosticRegisterResponse.""" - - sub_function_code = 0x0002 - - -class ChangeAsciiInputDelimiterRequest(DiagnosticBase): - """ChangeAsciiInputDelimiterRequest.""" +class PDUchangeAsciiInputDelimiter(PDUdiagnostic): + """ChangeAsciiInputDelimiter.""" sub_function_code = 0x0003 - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - char = (cast(int, self.message) & 0xFF00) >> 8 + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + char = self.message[0] _MCB.Delimiter = char - return ChangeAsciiInputDelimiterResponse( - message=self.message, dev_id=device_id, transaction_id=self.transaction_id - ) -class ChangeAsciiInputDelimiterResponse(DiagnosticBase): - """ChangeAsciiInputDelimiterResponse.""" - - sub_function_code = 0x0003 - - -class ForceListenOnlyModeRequest(DiagnosticBase): - """ForceListenOnlyModeRequest.""" +class PDUforceListenOnlyMode(PDUdiagnostic): + """ForceListenOnlyMode.""" sub_function_code = 0x0004 - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" _MCB.ListenOnly = True - return ForceListenOnlyModeResponse( - dev_id=device_id, transaction_id=self.transaction_id - ) -class ForceListenOnlyModeResponse(DiagnosticBase): - """ForceListenOnlyModeResponse. - - This does not send a response - """ - - sub_function_code = 0x0004 - - def __init__(self, dev_id=1, transaction_id=0): - """Initialize to block a return response.""" - DiagnosticBase.__init__(self, dev_id=dev_id, transaction_id=transaction_id) - self.message = [] - - -class ClearCountersRequest(DiagnosticBase): - """ClearCountersRequest.""" +class PDUclearCounters(PDUdiagnostic): + """ClearCounters.""" sub_function_code = 0x000A - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" _MCB.reset() - return ClearCountersResponse( - dev_id=device_id, transaction_id=self.transaction_id - ) - -class ClearCountersResponse(DiagnosticBase): - """ClearCountersResponse.""" - - sub_function_code = 0x000A - -class ReturnBusMessageCountRequest(DiagnosticBase): - """ReturnBusMessageCountRequest.""" +class PDUreturnBusMessageCount(PDUdiagnostic): + """ReturnBusMessageCount.""" sub_function_code = 0x000B - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - count = _MCB.Counter.BusMessage - return ReturnBusMessageCountResponse( - message=count, dev_id=device_id, transaction_id=self.transaction_id - ) - - -class ReturnBusMessageCountResponse(DiagnosticBase): - """ReturnBusMessageCountResponse.""" - - sub_function_code = 0x000B + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + self.message = _MCB.Counter.BusMessage -class ReturnBusCommunicationErrorCountRequest(DiagnosticBase): - """ReturnBusCommunicationErrorCountRequest.""" +class PDUreturnBusCommunicationErrorCount(PDUdiagnostic): + """ReturnBusCommunicationErrorCount.""" sub_function_code = 0x000C - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - count = _MCB.Counter.BusCommunicationError - return ReturnBusCommunicationErrorCountResponse( - message=count, dev_id=device_id, transaction_id=self.transaction_id - ) - - -class ReturnBusCommunicationErrorCountResponse(DiagnosticBase): - """ReturnBusCommunicationErrorCountResponse.""" - - sub_function_code = 0x000C + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + self.message = _MCB.Counter.BusCommunicationError -class ReturnBusExceptionErrorCountRequest(DiagnosticBase): - """ReturnBusExceptionErrorCountRequest.""" +class PDUreturnBusExceptionErrorCount(PDUdiagnostic): + """ReturnBusExceptionErrorCount.""" sub_function_code = 0x000D - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - count = _MCB.Counter.BusExceptionError - return ReturnBusExceptionErrorCountResponse( - message=count, dev_id=device_id, transaction_id=self.transaction_id - ) + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + self.message = _MCB.Counter.BusExceptionError -class ReturnBusExceptionErrorCountResponse(DiagnosticBase): - """ReturnBusExceptionErrorCountResponse.""" - - sub_function_code = 0x000D - - -class ReturnDeviceMessageCountRequest(DiagnosticBase): - """ReturnDeviceMessageCountRequest.""" +class PDUreturnDeviceMessageCount(PDUdiagnostic): + """ReturnDeviceMessageCount.""" sub_function_code = 0x000E - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - count = _MCB.Counter.DeviceMessage - return ReturnDeviceMessageCountResponse( - message=count, dev_id=device_id, transaction_id=self.transaction_id - ) - + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + self.message = _MCB.Counter.DeviceMessage -class ReturnDeviceMessageCountResponse(DiagnosticBase): - """ReturnDeviceMessageCountResponse.""" - - sub_function_code = 0x000E - -class ReturnDeviceNoResponseCountRequest(DiagnosticBase): - """ReturnDeviceNoResponseCountRequest.""" +class PDUreturnDeviceNoResponseCount(PDUdiagnostic): + """ReturnDeviceNoResponseCount.""" sub_function_code = 0x000F - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - count = _MCB.Counter.DeviceNoResponse - return ReturnDeviceNoResponseCountResponse( - message=count, dev_id=device_id, transaction_id=self.transaction_id - ) - - -class ReturnDeviceNoResponseCountResponse(DiagnosticBase): - """ReturnDeviceNoResponseCountResponse.""" - - sub_function_code = 0x000F + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + self.message = _MCB.Counter.DeviceNoResponse -class ReturnDeviceNAKCountRequest(DiagnosticBase): - """ReturnDeviceNAKCountRequest.""" +class PDUreturnDeviceNAKCount(PDUdiagnostic): + """ReturnDeviceNAKCount.""" sub_function_code = 0x0010 - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - count = _MCB.Counter.DeviceNAK - return ReturnDeviceNAKCountResponse( - message=count, dev_id=device_id, transaction_id=self.transaction_id - ) - + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + self.message = _MCB.Counter.DeviceNAK -class ReturnDeviceNAKCountResponse(DiagnosticBase): - """ReturnDeviceNAKCountResponse.""" - - sub_function_code = 0x0010 - -class ReturnDeviceBusyCountRequest(DiagnosticBase): - """ReturnDeviceBusyCountRequest.""" +class PDUreturnDeviceBusyCount(PDUdiagnostic): + """ReturnDeviceBusyCount.""" sub_function_code = 0x0011 - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - count = _MCB.Counter.DEVICE_BUSY - return ReturnDeviceBusyCountResponse( - message=count, dev_id=device_id, transaction_id=self.transaction_id - ) - - -class ReturnDeviceBusyCountResponse(DiagnosticBase): - """ReturnDeviceBusyCountResponse.""" - - sub_function_code = 0x0011 + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + self.message = _MCB.Counter.DEVICE_BUSY -class ReturnDeviceBusCharacterOverrunCountRequest(DiagnosticBase): - """ReturnDeviceBusCharacterOverrunCountRequest.""" +class PDUreturnDeviceBusCharacterOverrunCount(PDUdiagnostic): + """ReturnDeviceBusCharacterOverrunCount.""" sub_function_code = 0x0012 - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - count = _MCB.Counter.BusCharacterOverrun - return ReturnDeviceBusCharacterOverrunCountResponse( - message=count, dev_id=device_id, transaction_id=self.transaction_id - ) + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + self.message = _MCB.Counter.BusCharacterOverrun -class ReturnDeviceBusCharacterOverrunCountResponse(DiagnosticBase): - """ReturnDeviceBusCharacterOverrunCountResponse.""" +class PDUreturnIopOverrunCount(PDUdiagnostic): + """ReturnIopOverrunCount.""" - sub_function_code = 0x0012 + sub_function_code = 0x0013 + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + self.message = _MCB.Counter.BusCharacterOverrun -class ReturnIopOverrunCountRequest(DiagnosticBase): - """ReturnIopOverrunCountRequest.""" - sub_function_code = 0x0013 +class PDUclearOverrunCount(PDUdiagnostic): + """ClearOverrunCount.""" - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - count = _MCB.Counter.BusCharacterOverrun - return ReturnIopOverrunCountResponse( - message=count, dev_id=device_id, transaction_id=self.transaction_id - ) + sub_function_code = 0x0014 + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + _MCB.Counter.BusCharacterOverrun = 0x0000 -class ReturnIopOverrunCountResponse(DiagnosticBase): - """ReturnIopOverrunCountResponse.""" - sub_function_code = 0x0013 +class PDUgetClearModbusPlus(PDUdiagnostic): + """GetClearModbusPlus.""" + sub_function_code = 0x0015 -class ClearOverrunCountRequest(DiagnosticBase): - """ClearOverrunCountRequest.""" + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + return 0 if (lx := len(data)) < (leff := 6 + (111 if lx > 7 else 0)) else leff - sub_function_code = 0x0014 + def sub_build_response(self) -> None: + """Get/set info in _MCB.""" + if self.message == CLEAR_STATISTICS: + _MCB.Plus.reset() + else: + packet = b"" + for piece in _MCB.Plus.encode(): + packet += struct.pack(">H", piece) + self.message = packet - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - _MCB.Counter.BusCharacterOverrun = 0x0000 - return ClearOverrunCountResponse( - dev_id=device_id, transaction_id=self.transaction_id + def to_bytes(self): + """Encode a diagnostic response.""" + return ( + self.preamble() + struct.pack(">H", self.sub_function_code) + self.message ) -class ClearOverrunCountResponse(DiagnosticBase): - """ClearOverrunCountResponse.""" +class _OutOfSpaceException(Exception): + """Internal out of space exception.""" - sub_function_code = 0x0014 + # This exception exists here as a simple, local way to manage response + # length control for the only MODBUS command which requires it under + # standard, non-error conditions. + # + # See Page 5/50 of MODBUS Application Protocol Specification V1.1b3. + def __init__(self, oid: int) -> None: + self.oid = oid + super().__init__() + self.oid = oid -class GetClearModbusPlusRequest(DiagnosticBase): - """GetClearModbusPlusRequest.""" - sub_function_code = 0x0015 +class PDUreadDeviceInformation(ModbusPdu): + """Base PDU for dispatching Encapsulated Interface Transport messages.""" - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - message: int | list | None = None # the clear operation does not return info - if self.message == ModbusPlusOperation.CLEAR_STATISTICS: - _MCB.Plus.reset() - message = ModbusPlusOperation.CLEAR_STATISTICS - else: - message = [self.message] - message += _MCB.Plus.x_encode() - return GetClearModbusPlusResponse( - message=message, dev_id=device_id, transaction_id=self.transaction_id + function_code = 0x2B + sub_function_code = 0x0E + + def __init__( + self, + *args, + read_code: int | None = None, + object_id: int = 0, + information: dict[int, Any] | None = None, + **kwargs, + ) -> None: + """Initialize.""" + super().__init__(*args, **kwargs) + self.read_code = read_code or int(DeviceInformation.BASIC) + self.object_id = object_id + self.information: dict[int, Any] = information or {} + self.number_of_objects = 0 + self.conformity = 0x83 # I support everything right now + self.next_object_id = 0x00 + self.more_follows = MoreData.NOTHING + self.space_left = 253 - 6 + + def __str__(self) -> str: + """Build representation of pdu.""" + return super().__str__() + ( + ", " + + f"read_code={self.read_code}, " + + f"object_id={self.object_id}, " + + f"information={self.information}, " + + f"number_of_objects={self.number_of_objects}, " + + f"conformity={self.conformity}, " + + f"next_object_id={self.next_object_id}, " + + f"more_follows={self.more_follows}, " + + f"space_left={self.space_left}, " ) - def x_encode(self): - """Encode a diagnostic response.""" - packet = struct.pack(">H", self.sub_function_code) - packet += struct.pack(">H", self.message) - return packet + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + lx = len(data) + if self.is_request: + return 0 if lx < 5 else 5 + if lx < (size := 8): + return 0 + count = int(data[7]) + while count > 0: + if lx < size + 2: + return 0 + _, object_length = struct.unpack(">BB", data[size : size + 2]) + size += object_length + 2 + count -= 1 + return size + @classmethod + def decode_sub_function_code(cls, data: bytes) -> int: + """Decode sub function code.""" + return int(data[2]) + + def _encode_object(self, object_id: int, data: str | bytes | ModbusPdu) -> bytes: + """Encode object.""" + if isinstance(data, str): + data = data.encode() + elif not isinstance(data, bytes): + data = data.to_bytes() + data_len = len(data) + self.space_left -= 2 + data_len + if self.space_left <= 0: + raise _OutOfSpaceException(object_id) + encoded_obj = struct.pack(">BB", object_id, data_len) + encoded_obj += data + self.number_of_objects += 1 + return encoded_obj + + def to_bytes(self) -> bytes: + """Encode the message.""" + if self.is_request: + packet = self.preamble() + struct.pack( + ">BBB", self.sub_function_code, self.read_code, self.object_id + ) + return packet + packet = self.preamble() + struct.pack( + ">BBB", self.sub_function_code, self.read_code, self.conformity + ) + objects = b"" + try: + for object_id, data in iter(self.information.items()): + if isinstance(data, list): + for item in data: + objects += self._encode_object(object_id, item) + else: + objects += self._encode_object(object_id, data) + except _OutOfSpaceException as exc: + self.next_object_id = exc.oid + self.more_follows = MoreData.KEEP_READING + + packet += struct.pack( + ">BBB", self.more_follows, self.next_object_id, self.number_of_objects + ) + packet += objects + return packet -class GetClearModbusPlusResponse(DiagnosticBase): - """GetClearModbusPlusResponse.""" + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if self.is_request: + self.read_code, self.object_id = struct.unpack(">BB", data[3:5]) + return + ( + self.read_code, + self.conformity, + self.more_follows, + self.next_object_id, + self.number_of_objects, + ) = struct.unpack(">BBBBB", data[3:8]) + self.information.clear() + count = 8 # skip the header information + while count < len(data): + object_id, object_length = struct.unpack(">BB", data[count : count + 2]) + count += object_length + 2 + if object_id not in self.information: + self.information[object_id] = data[count - object_length : count] + elif isinstance(self.information[object_id], list): + self.information[object_id].append(data[count - object_length : count]) + else: + self.information[object_id] = [ + self.information[object_id], + data[count - object_length : count], + ] - sub_function_code = 0x0015 + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Update diagnostic request on the given device.""" + if not 0x00 <= self.object_id <= 0xFF: + return PDUexception(self.dev_id, self.function_code, ExcCodes.ILLEGAL_VALUE) + if not 0x01 <= self.read_code <= 0x04: + return PDUexception(self.dev_id, self.function_code, ExcCodes.ILLEGAL_VALUE) - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of the message. - - Func_code (1 byte) + Sub function code (2 byte) + Operation (2 byte) + Data (108 bytes) - """ - size_data = 111 if len(data) > 7 else 0 - return 1 + 2 + 2 + 2 + size_data - - -DecodePDU.add_pdu(DiagnosticBase, DiagnosticBase) -DecodePDU.add_sub_pdu(ReturnQueryDataRequest, ReturnQueryDataResponse) -DecodePDU.add_sub_pdu( - RestartCommunicationsOptionRequest, RestartCommunicationsOptionResponse -) -DecodePDU.add_sub_pdu(ReturnDiagnosticRegisterRequest, ReturnDiagnosticRegisterResponse) -DecodePDU.add_sub_pdu( - ChangeAsciiInputDelimiterRequest, ChangeAsciiInputDelimiterResponse -) -DecodePDU.add_sub_pdu(ForceListenOnlyModeRequest, ForceListenOnlyModeResponse) -DecodePDU.add_sub_pdu(ClearCountersRequest, ClearCountersResponse) -DecodePDU.add_sub_pdu(ReturnBusMessageCountRequest, ReturnBusMessageCountResponse) -DecodePDU.add_sub_pdu( - ReturnBusCommunicationErrorCountRequest, ReturnBusCommunicationErrorCountResponse -) -DecodePDU.add_sub_pdu( - ReturnBusExceptionErrorCountRequest, ReturnBusExceptionErrorCountResponse -) -DecodePDU.add_sub_pdu(ReturnDeviceMessageCountRequest, ReturnDeviceMessageCountResponse) -DecodePDU.add_sub_pdu( - ReturnDeviceNoResponseCountRequest, ReturnDeviceNoResponseCountResponse -) -DecodePDU.add_sub_pdu(ReturnDeviceNAKCountRequest, ReturnDeviceNAKCountResponse) -DecodePDU.add_sub_pdu(ReturnDeviceBusyCountRequest, ReturnDeviceBusyCountResponse) -DecodePDU.add_sub_pdu( - ReturnDeviceBusCharacterOverrunCountRequest, - ReturnDeviceBusCharacterOverrunCountResponse, -) -DecodePDU.add_sub_pdu(ReturnIopOverrunCountRequest, ReturnIopOverrunCountResponse) -DecodePDU.add_sub_pdu(ClearOverrunCountRequest, ClearOverrunCountResponse) -DecodePDU.add_sub_pdu(GetClearModbusPlusRequest, GetClearModbusPlusResponse) + self.information = DeviceInformationFactory.get( + _MCB, self.read_code, self.object_id + ) + if self.read_code == DeviceInformation.SPECIFIC and ( + 0x07 <= self.object_id < 0x80 or not self.information.get(self.object_id) + ): + return PDUexception( + self.dev_id, self.function_code, ExcCodes.ILLEGAL_ADDRESS + ) + self.is_request = False + return self + + +DecodePDU.add_pdu(PDUdiagnostic) +DecodePDU.add_pdu(PDUreturnQueryData) +DecodePDU.add_pdu(PDUrestartCommunicationsOption) +DecodePDU.add_pdu(PDUreturnDiagnosticRegister) +DecodePDU.add_pdu(PDUchangeAsciiInputDelimiter) +DecodePDU.add_pdu(PDUforceListenOnlyMode) +DecodePDU.add_pdu(PDUclearCounters) +DecodePDU.add_pdu(PDUreturnBusMessageCount) +DecodePDU.add_pdu(PDUreturnBusCommunicationErrorCount) +DecodePDU.add_pdu(PDUreturnBusExceptionErrorCount) +DecodePDU.add_pdu(PDUreturnDeviceMessageCount) +DecodePDU.add_pdu(PDUreturnDeviceNoResponseCount) +DecodePDU.add_pdu(PDUreturnDeviceNAKCount) +DecodePDU.add_pdu(PDUreturnDeviceBusyCount) +DecodePDU.add_pdu(PDUreturnDeviceBusCharacterOverrunCount) +DecodePDU.add_pdu(PDUreturnIopOverrunCount) +DecodePDU.add_pdu(PDUclearOverrunCount) +DecodePDU.add_pdu(PDUgetClearModbusPlus) +DecodePDU.add_pdu(PDUreadDeviceInformation) diff --git a/pymodbus/pdu/events.py b/pymodbus/pdu/events.py deleted file mode 100644 index c402463055..0000000000 --- a/pymodbus/pdu/events.py +++ /dev/null @@ -1,210 +0,0 @@ -"""Modbus Remote Events. - -An event byte returned by the Get Communications Event Log function -can be any one of four types. The type is defined by bit 7 -(the high-order bit) in each byte. It may be further defined by bit 6. -""" - -# pylint: disable=missing-type-doc -from abc import ABC, abstractmethod - -from ..exceptions import ParameterException -from .utils import pack_bitstring, unpack_bitstring - - -class ModbusEvent(ABC): - """Define modbus events.""" - - @abstractmethod - def x_encode(self) -> bytes: - """Encode the status bits to an event message.""" - - @abstractmethod - def x_decode(self, event): - """Decode the event message to its status bits. - - :param event: The event to decode - """ - - -class RemoteReceiveEvent(ModbusEvent): - """Remote device MODBUS Receive Event. - - The remote device stores this type of event byte when a query message - is received. It is stored before the remote device processes the message. - This event is defined by bit 7 set to logic "1". The other bits will be - set to a logic "1" if the corresponding condition is TRUE. The bit layout - is:: - - Bit Contents - ---------------------------------- - 0 Not Used - 2 Not Used - 3 Not Used - 4 Character Overrun - 5 Currently in Listen Only Mode - 6 Broadcast Receive - 7 1 - """ - - def __init__(self, overrun=False, listen=False, broadcast=False): - """Initialize a new event instance.""" - self.overrun = overrun - self.listen = listen - self.broadcast = broadcast - - def x_encode(self) -> bytes: - """Encode the status bits to an event message. - - :returns: The encoded event message - """ - bits = [False] * 3 - bits += [self.overrun, self.listen, self.broadcast, True] - packet = pack_bitstring(bits) - return packet - - def x_decode(self, event: bytes) -> None: - """Decode the event message to its status bits. - - :param event: The event to decode - """ - bits = unpack_bitstring(event) - self.overrun = bits[4] - self.listen = bits[5] - self.broadcast = bits[6] - - -class RemoteSendEvent(ModbusEvent): - """Remote device MODBUS Send Event. - - The remote device stores this type of event byte when it finishes - processing a request message. It is stored if the remote device - returned a normal or exception response, or no response. - - This event is defined by bit 7 set to a logic "0", with bit 6 set to a "1". - The other bits will be set to a logic "1" if the corresponding - condition is TRUE. The bit layout is:: - - Bit Contents - ----------------------------------------------------------- - 0 Read Exception Sent (Exception Codes 1-3) - 1 Device Abort Exception Sent (Exception Code 4) - 2 Device Busy Exception Sent (Exception Codes 5-6) - 3 Device Program NAK Exception Sent (Exception Code 7) - 4 Write Timeout Error Occurred - 5 Currently in Listen Only Mode - 6 1 - 7 0 - """ - - def __init__( - self, - read=False, - device_abort=False, - device_busy=False, - device_nak=False, - write_timeout=False, - listen=False, - ): - """Initialize a new event instance.""" - self.read = read - self.device_abort = device_abort - self.device_busy = device_busy - self.device_nak = device_nak - self.write_timeout = write_timeout - self.listen = listen - - def x_encode(self): - """Encode the status bits to an event message. - - :returns: The encoded event message - """ - bits = [ - self.read, - self.device_abort, - self.device_busy, - self.device_nak, - self.write_timeout, - self.listen, - ] - bits += [True, False] - packet = pack_bitstring(bits) - return packet - - def x_decode(self, event): - """Decode the event message to its status bits. - - :param event: The event to decode - """ - # todo fix the start byte count # pylint: disable=fixme - bits = unpack_bitstring(event) - self.read = bits[0] - self.device_abort = bits[1] - self.device_busy = bits[2] - self.device_nak = bits[3] - self.write_timeout = bits[4] - self.listen = bits[5] - - -class EnteredListenModeEvent(ModbusEvent): - """Enter Remote device Listen Only Mode. - - The remote device stores this type of event byte when it enters - the Listen Only Mode. The event is defined by a content of 04 hex. - """ - - value = 0x04 - __encoded = b"\x04" - - def x_encode(self): - """Encode the status bits to an event message. - - :returns: The encoded event message - """ - return self.__encoded - - def x_decode(self, event): - """Decode the event message to its status bits. - - :param event: The event to decode - :raises ParameterException: - """ - if event != self.__encoded: - raise ParameterException("Invalid decoded value") - - -class CommunicationRestartEvent(ModbusEvent): - """Restart remote device Initiated Communication. - - The remote device stores this type of event byte when its communications - port is restarted. The remote device can be restarted by the Diagnostics - function (code 08), with sub-function Restart Communications Option - (code 00 01). - - That function also places the remote device into a "Continue on Error" - or "Stop on Error" mode. If the remote device is placed into "Continue on - Error" mode, the event byte is added to the existing event log. If the - remote device is placed into "Stop on Error" mode, the byte is added to - the log and the rest of the log is cleared to zeros. - - The event is defined by a content of zero. - """ - - value = 0x00 - __encoded = b"\x00" - - def x_encode(self): - """Encode the status bits to an event message. - - :returns: The encoded event message - """ - return self.__encoded - - def x_decode(self, event): - """Decode the event message to its status bits. - - :param event: The event to decode - :raises ParameterException: - """ - if event != self.__encoded: - raise ParameterException("Invalid decoded value") diff --git a/pymodbus/pdu/exceptionresponse.py b/pymodbus/pdu/exceptionresponse.py deleted file mode 100644 index 8374543145..0000000000 --- a/pymodbus/pdu/exceptionresponse.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Contains exceptionResponse class for modbus.""" - -from __future__ import annotations - -import struct - -from .pdu import ModbusPDU - - -class ExceptionResponse(ModbusPDU): - """Base class for a modbus exception PDU.""" - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 5 - - def __init__( - self, - function_code: int, - exception_code: int = 0, - device_id: int = 1, - transaction: int = 0, - ) -> None: - """Initialize the modbus exception response.""" - super().__init__(transaction_id=transaction, dev_id=device_id) - self.function_code = function_code | 0x80 - self.exception_code = exception_code - - def __str__(self) -> str: - """Build a representation of an exception response.""" - return ( - f"{self.__class__.__name__}(" - f"dev_id={self.dev_id}, " - f"function_code={self.function_code}, " - f"exception_code={self.exception_code})" - ) - - def x_encode(self) -> bytes: - """Encode a modbus exception response.""" - return struct.pack(">B", self.exception_code) - - def x_decode(self, data: bytes) -> None: - """Decode data part of the message.""" - _ = data - - def isError(self) -> bool: - """Check if the error is a success or failure.""" - return True - - def from_frame(self, is_request: bool, data: bytes) -> int: - """Decode a modbus exception response.""" - _ = is_request - self.function_code = int(data[0]) - self.exception_code = int(data[1]) - return 5 diff --git a/pymodbus/pdu/file_message.py b/pymodbus/pdu/file_message.py deleted file mode 100644 index f7a5e8cda6..0000000000 --- a/pymodbus/pdu/file_message.py +++ /dev/null @@ -1,340 +0,0 @@ -"""File Record Read/Write Messages.""" - -from __future__ import annotations - -import struct -from dataclasses import dataclass - -from ..datastore import ModbusServerContext -from ..exceptions import ModbusException, ModbusIOException -from .decoders import DecodePDU -from .pdu import ModbusPDU - - -@dataclass -class FileRecord: - """Represents a file record and its relevant data.""" - - file_number: int = 0 - record_number: int = 0 - record_data: bytes = b"" - record_length: int = 0 - - def __post_init__(self) -> None: - """Initialize a new instance.""" - if self.record_data: - if self.record_length: - raise ModbusException("Use either record_data= or record_length=") - self.record_length = len(self.record_data) - if self.record_length % 2: - raise ModbusException("length of record_data must be a multiple of 2") - self.record_length //= 2 - - -class ReadFileRecordRequest(ModbusPDU): - """ReadFileRecordRequest.""" - - function_code = 0x14 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 - - def __init__( - self, - records: list[FileRecord] | None = None, - dev_id: int = 1, - transaction_id: int = 0, - ) -> None: - """Initialize a new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id) - self.records: list[FileRecord] = records or [] - - def x_encode(self) -> bytes: - """Encode the request packet.""" - packet = struct.pack("B", len(self.records) * 7) - for record in self.records: - packet += struct.pack( - ">BHHH", - 0x06, - record.file_number, - record.record_number, - record.record_length, - ) - return packet - - def x_decode(self, data: bytes) -> None: - """Decode the incoming request.""" - self.records = [] - if (byte_count := int(data[0])) > len(data) - 1: - raise ModbusIOException( - f"Invalid byte count: {byte_count}", function_code=self.function_code - ) - for count in range(1, byte_count, 7): - decoded = struct.unpack(">BHHH", data[count : count + 7]) - record = FileRecord( - file_number=decoded[1], - record_number=decoded[2], - ) - record.record_length = decoded[3] - self.records.append(record) - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - for record in self.records: - record.record_data = b"SERVER DUMMY RECORD." - record.record_length = len(record.record_data) // 2 - return ReadFileRecordResponse( - records=self.records, dev_id=device_id, transaction_id=self.transaction_id - ) - - -class ReadFileRecordResponse(ModbusPDU): - """ReadFileRecordResponse.""" - - function_code = 0x14 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 - - def __init__( - self, - records: list[FileRecord] | None = None, - dev_id: int = 1, - transaction_id: int = 0, - ) -> None: - """Initialize a new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id) - self.records: list[FileRecord] = records or [] - - def x_encode(self) -> bytes: - """Encode the response.""" - total = sum(len(record.record_data) + 1 + 1 for record in self.records) - packet = struct.pack("B", total) - for record in self.records: - packet += struct.pack(">BB", len(record.record_data) + 1, 0x06) - packet += record.record_data - return packet - - def x_decode(self, data: bytes) -> None: - """Decode the response.""" - count = 1 - self.records.clear() - byte_count = int(data[0]) - while count < byte_count: - calc_length, _ = struct.unpack(">BB", data[count : count + 2]) - count += 2 - - record_length = calc_length - 1 # response length includes the type byte - record = FileRecord( - record_data=data[count : count + record_length], - ) - count += record_length - self.records.append(record) - - -class WriteFileRecordRequest(ModbusPDU): - """WriteFileRecordRequest.""" - - function_code = 0x15 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 - - def __init__( - self, - records: list[FileRecord] | None = None, - dev_id: int = 1, - transaction_id: int = 0, - ) -> None: - """Initialize a new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id) - self.records: list[FileRecord] = records or [] - - def x_encode(self) -> bytes: - """Encode the request packet.""" - total_length = sum((record.record_length * 2) + 7 for record in self.records) - packet = struct.pack("B", total_length) - - for record in self.records: - packet += struct.pack( - ">BHHH", - 0x06, - record.file_number, - record.record_number, - record.record_length, - ) - packet += record.record_data - return packet - - def x_decode(self, data: bytes) -> None: - """Decode the incoming request.""" - if (byte_count := int(data[0])) > len(data) - 1: - raise ModbusIOException( - f"Invalid byte count: {byte_count}", function_code=self.function_code - ) - count = 1 - self.records.clear() - while count < byte_count: - decoded = struct.unpack(">BHHH", data[count : count + 7]) - calc_length = decoded[3] * 2 - count += calc_length + 7 - record = FileRecord( - file_number=decoded[1], - record_number=decoded[2], - record_data=data[count - calc_length : count], - ) - record.record_length = decoded[3] - self.records.append(record) - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - return WriteFileRecordResponse( - records=self.records, dev_id=device_id, transaction_id=self.transaction_id - ) - - -class WriteFileRecordResponse(ModbusPDU): - """The normal response is an echo of the request.""" - - function_code = 0x15 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 - - def __init__( - self, - records: list[FileRecord] | None = None, - dev_id: int = 1, - transaction_id: int = 0, - ) -> None: - """Initialize a new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id) - self.records: list[FileRecord] = records or [] - - def x_encode(self) -> bytes: - """Encode the response.""" - total_length = sum((record.record_length * 2) + 7 for record in self.records) - packet = struct.pack("B", total_length) - for record in self.records: - packet += struct.pack( - ">BHHH", - 0x06, - record.file_number, - record.record_number, - record.record_length, - ) - packet += record.record_data - return packet - - def x_decode(self, data: bytes) -> None: - """Decode the incoming request.""" - count = 1 - self.records.clear() - byte_count = int(data[0]) - while count < byte_count: - decoded = struct.unpack(">BHHH", data[count : count + 7]) - calc_length = decoded[3] * 2 - count += calc_length + 7 - record = FileRecord( - file_number=decoded[1], - record_number=decoded[2], - record_data=data[count - calc_length : count], - ) - record.record_length = decoded[3] - self.records.append(record) - - -class ReadFifoQueueRequest(ModbusPDU): - """ReadFifoQueueRequest.""" - - function_code = 0x18 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 6 - - def __init__( - self, address: int = 0, dev_id: int = 1, transaction_id: int = 0 - ) -> None: - """Initialize a new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id) - self.address = address - self.verifyAddress() - - def x_encode(self) -> bytes: - """Encode the request packet.""" - return struct.pack(">H", self.address) - - def x_decode(self, data: bytes) -> None: - """Decode the incoming request.""" - self.address = struct.unpack(">H", data[:2])[0] - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - values = [0, 1, 2, 3] # server dummy response (should be in datastore) - return ReadFifoQueueResponse( - values=values, dev_id=device_id, transaction_id=self.transaction_id - ) - - -class ReadFifoQueueResponse(ModbusPDU): - """ReadFifoQueueResponse.""" - - function_code = 0x18 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of the message.""" - hi_byte = int(data[2]) - lo_byte = int(data[3]) - return ((hi_byte << 8) + lo_byte) + 6 - - def __init__( - self, values: list[int] | None = None, dev_id: int = 1, transaction_id: int = 0 - ) -> None: - """Initialize a new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id) - self.values = values or [] - - def x_encode(self) -> bytes: - """Encode the response.""" - length = len(self.values) - packet = struct.pack(">HH", 2 + length * 2, length) - for value in self.values: - packet += struct.pack(">H", value) - return packet - - def x_decode(self, data: bytes) -> None: - """Decode a the response.""" - self.values = [] - _, count = struct.unpack(">HH", data[0:4]) - if 4 + count * 2 > len(data): - raise ModbusIOException( - f"Invalid fifo count: {count}", function_code=self.function_code - ) - for index in range(0, count): - idx = 4 + index * 2 - self.values.append(struct.unpack(">H", data[idx : idx + 2])[0]) - - -DecodePDU.add_pdu(ReadFileRecordRequest, ReadFileRecordResponse) -DecodePDU.add_pdu(WriteFileRecordRequest, WriteFileRecordResponse) -DecodePDU.add_pdu(ReadFifoQueueRequest, ReadFifoQueueResponse) diff --git a/pymodbus/pdu/mei_message.py b/pymodbus/pdu/mei_message.py deleted file mode 100644 index 08504c9cce..0000000000 --- a/pymodbus/pdu/mei_message.py +++ /dev/null @@ -1,210 +0,0 @@ -"""Encapsulated Interface (MEI) Transport Messages.""" - -from __future__ import annotations - -import struct -from abc import abstractmethod -from typing import Any - -from ..constants import DeviceInformation, ExcCodes, MoreData -from ..datastore import ModbusServerContext -from .decoders import DecodePDU -from .device import DeviceInformationFactory, ModbusControlBlock -from .exceptionresponse import ExceptionResponse -from .pdu import ModbusPDU - - -_MCB = ModbusControlBlock() - - -class _OutOfSpaceException(Exception): - """Internal out of space exception.""" - - # This exception exists here as a simple, local way to manage response - # length control for the only MODBUS command which requires it under - # standard, non-error conditions. - # - # See Page 5/50 of MODBUS Application Protocol Specification V1.1b3. - - def __init__(self, oid: int) -> None: - self.oid = oid - super().__init__() - self.oid = oid - - -class EncapsulatedInterfaceTransportBase(ModbusPDU): - """Base PDU for dispatching Encapsulated Interface Transport messages.""" - - function_code = 0x2B - - @classmethod - def decode_sub_function_code(cls, data: bytes) -> int: - """Decode the MEI type.""" - return int(data[2]) - - @abstractmethod - def x_encode(self) -> bytes: - """Encode the request packet.""" - - -class ReadDeviceInformationRequest(EncapsulatedInterfaceTransportBase): - """ReadDeviceInformationRequest.""" - - sub_function_code = 0x0E - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 7 - - def __init__( - self, - read_code: int | None = None, - object_id: int = 0, - dev_id: int = 1, - transaction_id: int = 0, - ) -> None: - """Initialize a new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id) - self.read_code = read_code or DeviceInformation.BASIC - self.object_id = object_id - - def x_encode(self) -> bytes: - """Encode the request packet.""" - packet = struct.pack( - ">BBB", self.sub_function_code, self.read_code, self.object_id - ) - return packet - - def x_decode(self, data: bytes) -> None: - """Decode data part of the message.""" - self.sub_function_code, self.read_code, self.object_id = struct.unpack( - ">BBB", data[:3] - ) - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - if not 0x00 <= self.object_id <= 0xFF: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - if not 0x01 <= self.read_code <= 0x04: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - - information = DeviceInformationFactory.get(_MCB, self.read_code, self.object_id) - if self.read_code == DeviceInformation.SPECIFIC and ( - 0x07 <= self.object_id < 0x80 or not information.get(self.object_id) - ): - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_ADDRESS) - return ReadDeviceInformationResponse( - read_code=self.read_code, - information=information, - dev_id=device_id, - transaction_id=self.transaction_id, - ) - - -class ReadDeviceInformationResponse(EncapsulatedInterfaceTransportBase): - """ReadDeviceInformationResponse.""" - - sub_function_code = 0x0E - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of the message.""" - size = 8 # skip the header information - if (data_len := len(data)) < size: - return 999 - count = int(data[7]) - - while count > 0: - if data_len < size + 2: - return 998 - _, object_length = struct.unpack(">BB", data[size : size + 2]) - size += object_length + 2 - count -= 1 - return size + 2 - - def __init__( - self, - read_code: int | None = None, - information: dict[int, Any] | None = None, - dev_id: int = 1, - transaction_id: int = 0, - ) -> None: - """Initialize a new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id) - self.read_code = read_code or DeviceInformation.BASIC - self.information: dict[int, Any] = information or {} - self.number_of_objects = 0 - self.conformity = 0x83 # I support everything right now - self.next_object_id = 0x00 - self.more_follows = MoreData.NOTHING - self.space_left = 253 - 6 - - def _encode_object(self, object_id: int, data: str | bytes | ModbusPDU) -> bytes: - """Encode object.""" - if isinstance(data, str): - data = data.encode() - elif not isinstance(data, bytes): - data = data.x_encode() - data_len = len(data) - self.space_left -= 2 + data_len - if self.space_left <= 0: - raise _OutOfSpaceException(object_id) - encoded_obj = struct.pack(">BB", object_id, data_len) - encoded_obj += data - self.number_of_objects += 1 - return encoded_obj - - def x_encode(self) -> bytes: - """Encode the response.""" - packet = struct.pack( - ">BBB", self.sub_function_code, self.read_code, self.conformity - ) - objects = b"" - try: - for object_id, data in iter(self.information.items()): - if isinstance(data, list): - for item in data: - objects += self._encode_object(object_id, item) - else: - objects += self._encode_object(object_id, data) - except _OutOfSpaceException as exc: - self.next_object_id = exc.oid - self.more_follows = MoreData.KEEP_READING - - packet += struct.pack( - ">BBB", self.more_follows, self.next_object_id, self.number_of_objects - ) - packet += objects - return packet - - def x_decode(self, data: bytes) -> None: - """Decode a the response.""" - params = struct.unpack(">BBBBBB", data[0:6]) - self.sub_function_code, self.read_code = params[0:2] - self.conformity, self.more_follows = params[2:4] - self.next_object_id, self.number_of_objects = params[4:6] - count = 6 # skip the header information - self.information.clear() - - while count < len(data): - object_id, object_length = struct.unpack(">BB", data[count : count + 2]) - count += object_length + 2 - if object_id not in self.information: - self.information[object_id] = data[count - object_length : count] - elif isinstance(self.information[object_id], list): - self.information[object_id].append(data[count - object_length : count]) - else: - self.information[object_id] = [ - self.information[object_id], - data[count - object_length : count], - ] - - -DecodePDU.add_pdu( - EncapsulatedInterfaceTransportBase, EncapsulatedInterfaceTransportBase -) -DecodePDU.add_sub_pdu(ReadDeviceInformationRequest, ReadDeviceInformationResponse) diff --git a/pymodbus/pdu/other_message.py b/pymodbus/pdu/other_message.py index 3a7d649128..71aad2893a 100644 --- a/pymodbus/pdu/other_message.py +++ b/pymodbus/pdu/other_message.py @@ -3,222 +3,240 @@ from __future__ import annotations import struct +from copy import deepcopy +from dataclasses import dataclass from ..constants import ModbusStatus -from ..datastore import ModbusServerContext -from ..exceptions import ModbusIOException -from .decoders import DecodePDU +from ..exceptions import ModbusException from .device import DeviceInformationFactory, ModbusControlBlock -from .pdu import ModbusPDU +from .pdu import DecodePDU, ModbusPdu, StoreGet, StoreSet _MCB = ModbusControlBlock() -class ReadExceptionStatusRequest(ModbusPDU): - """ReadExceptionStatusRequest.""" +class PDUreadExceptionStatus(ModbusPdu): + """ReadExceptionStatus.""" function_code = 0x07 - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 4 - - def x_encode(self) -> bytes: - """Encode the message.""" - return b"" - - def x_decode(self, data: bytes) -> None: - """Decode data part of the message.""" - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - status = _MCB.Counter.summary() - return ReadExceptionStatusResponse( - status=status, dev_id=device_id, transaction_id=self.transaction_id - ) - - -class ReadExceptionStatusResponse(ModbusPDU): - """ReadExceptionStatusResponse.""" + def __init__( + self, + *args, + status: int = 0, + **kwargs, + ) -> None: + """Initialize.""" + super().__init__(*args, **kwargs) + self.status: int = status or 0 - function_code = 0x07 + def __str__(self) -> str: + """Build representation of pdu.""" + return super().__str__() + f", status={self.status}" - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: + def calculatePduSize(self, data: bytes) -> int: """Calculate the size of a PDU.""" - return 5 - - def x_encode(self) -> bytes: - """Encode the response.""" - return struct.pack(">B", self.status) + lx = len(data) + if self.is_request: + return 0 if lx < 2 else 2 + return 0 if lx < 3 else 3 - def x_decode(self, data: bytes) -> None: - """Decode a the response.""" - self.status = int(data[0]) + def to_bytes(self) -> bytes: + """Encode the message.""" + return ( + self.preamble() + b"" + if self.is_request + else self.preamble() + struct.pack(">B", self.status) + ) + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if not self.is_request: + self.status = int(data[2]) -# Encapsulate interface transport 43, 14 -# CANopen general reference 43, 13 + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Update internal data.""" + self.status = _MCB.Counter.summary() + self.is_request = False + return self -class GetCommEventCounterRequest(ModbusPDU): - """GetCommEventCounterRequest.""" +class PDUgetCommEventCounter(ModbusPdu): + """GetCommEventCounter.""" function_code = 0x0B - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 4 - - def x_encode(self) -> bytes: - """Encode the message.""" - return b"" - - def x_decode(self, data: bytes) -> None: - """Decode data part of the message.""" - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - count = _MCB.Counter.Event - return GetCommEventCounterResponse( - count=count, dev_id=device_id, transaction_id=self.transaction_id - ) - - -class GetCommEventCounterResponse(ModbusPDU): - """GetCommEventCounterRequest.""" + def __init__( + self, + *args, + status: int = 0, + count: int = 0, + **kwargs, + ) -> None: + """Initialize.""" + super().__init__(*args, **kwargs) + self.status: int = status or True + self.count: int = count - function_code = 0x0B + def __str__(self) -> str: + """Build representation of pdu.""" + return super().__str__() + f", count={self.count}, status={self.status}" - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: + def calculatePduSize(self, data: bytes) -> int: """Calculate the size of a PDU.""" - return 8 + lx = len(data) + if self.is_request: + return 0 if lx < 2 else 2 + return 0 if lx < 6 else 6 - def x_encode(self) -> bytes: - """Encode the response.""" + def to_bytes(self) -> bytes: + """Encode the message.""" + if self.is_request: + return self.preamble() + b"" ready = ModbusStatus.READY if self.status else ModbusStatus.WAITING - return struct.pack(">HH", ready, self.count) + return self.preamble() + struct.pack(">HH", ready, self.count) - def x_decode(self, data: bytes) -> None: - """Decode a the response.""" - ready, self.count = struct.unpack(">HH", data[:4]) - self.status = ready == ModbusStatus.READY + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if not self.is_request: + ready, self.count = struct.unpack(">HH", data[2:6]) + self.status = ready == ModbusStatus.READY + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Update internal data.""" + self.count = _MCB.Counter.Event + self.is_request = False + return self -class GetCommEventLogRequest(ModbusPDU): - """GetCommEventLogRequest.""" - function_code = 0x0C - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 4 - - def x_encode(self) -> bytes: - """Encode the message.""" - return b"" - - def x_decode(self, data: bytes) -> None: - """Decode data part of the message.""" - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context - return GetCommEventLogResponse( - status=True, - message_count=_MCB.Counter.BusMessage, - event_count=_MCB.Counter.Event, - events=list(_MCB.getEvents()), - dev_id=device_id, - transaction_id=self.transaction_id, - ) - - -class GetCommEventLogResponse(ModbusPDU): - """GetCommEventLogRequest.""" +class PDUgetCommEventLog(ModbusPdu): + """GetCommEventLog.""" function_code = 0x0C - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 - def __init__( self, + *args, status: bool = True, message_count: int = 0, event_count: int = 0, events: list[int] | None = None, - dev_id: int = 1, - transaction_id: int = 0, + **kwargs, ) -> None: - """Initialize a new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id, status=status) + """Initialize.""" + super().__init__(*args, **kwargs) + self.status = status self.message_count = message_count self.event_count = event_count self.events = events or [] - def x_encode(self) -> bytes: - """Encode the response.""" - if self.status: - ready = ModbusStatus.READY - else: - ready = ModbusStatus.WAITING - packet = struct.pack(">B", 6 + len(self.events)) - packet += struct.pack(">H", ready) - packet += struct.pack(">HH", self.event_count, self.message_count) + def __str__(self) -> str: + """Build representation of pdu.""" + return ( + super().__str__() + + f", status={self.status}, message_count={self.message_count}" + + f", event_count={self.event_count}, events={self.events}" + ) + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + lx = len(data) + if self.is_request: + return 0 if lx < 2 else 2 + return 0 if lx < 6 or lx < (leff := int(data[2]) + 3) else leff + + def to_bytes(self) -> bytes: + """Encode the message.""" + if self.is_request: + return self.preamble() + b"" + ready = ModbusStatus.READY if self.status else ModbusStatus.WAITING + packet = self.preamble() + struct.pack(">B", 6 + len(self.events)) + packet += struct.pack(">HHH", ready, self.event_count, self.message_count) packet += b"".join(struct.pack(">B", e) for e in self.events) return packet - def x_decode(self, data: bytes) -> None: - """Decode a the response.""" - length = int(data[0]) - status = struct.unpack(">H", data[1:3])[0] + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if self.is_request: + return + length = int(data[2]) - 6 + status = struct.unpack(">H", data[3:5])[0] self.status = status == ModbusStatus.READY - self.event_count = struct.unpack(">H", data[3:5])[0] - self.message_count = struct.unpack(">H", data[5:7])[0] + self.event_count = struct.unpack(">H", data[5:7])[0] + self.message_count = struct.unpack(">H", data[7:9])[0] self.events = [] - for i in range(7, length + 1): + for i in range(9, length + 9): self.events.append(int(data[i])) + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Update internal data.""" + self.status = True + self.message_count = _MCB.Counter.BusMessage + self.event_count = _MCB.Counter.Event + self.events = list(_MCB.getEvents()) + return self + + +ID_ON = 0xFF +ID_OFF = 0x00 + -class ReportDeviceIdRequest(ModbusPDU): - """ReportDeviceIdRequest.""" +class PDUreportDeviceId(ModbusPdu): + """ReportDeviceId.""" function_code = 0x11 - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: + def __init__( + self, + *args, + identifier: bytes = b"\x00", + status: bool = True, + **kwargs, + ) -> None: + """Initialize.""" + super().__init__(*args, **kwargs) + self.status = status + self.identifier = identifier + + def __str__(self) -> str: + """Build representation of pdu.""" + return ( + super().__str__() + f", status={self.status}, identifier={self.identifier}" + ) + + def calculatePduSize(self, data: bytes) -> int: """Calculate the size of a PDU.""" - return 4 + lx = len(data) + if self.is_request: + return 0 if lx < 2 else 2 + return 0 if lx < 3 or lx < (leff := int(data[2]) + 3) else leff - def x_encode(self) -> bytes: + def to_bytes(self) -> bytes: """Encode the message.""" - return b"" + if self.is_request: + return self.preamble() + b"" + status = ID_ON if self.status else ID_OFF + length = len(self.identifier) + 1 + packet = self.preamble() + struct.pack(">B", length) + packet += self.identifier # we assume it is already encoded + packet += struct.pack(">B", status) + return packet - def x_decode(self, data: bytes) -> None: - """Decode data part of the message.""" + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if self.is_request: + return None + byte_count = int(data[2]) + if not 1 <= byte_count <= len(data) - 3: + return f"byte_count {byte_count} outside 1..{len(data) - 1} " + self.identifier = data[3 : byte_count + 2] + status = int(data[-1]) + self.status = status == ID_ON + return None - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Update internal data.""" information = DeviceInformationFactory.get(_MCB) id_data = [] for v_item in information.values(): @@ -228,66 +246,242 @@ async def datastore_update( id_data.append(v_item.encode()) identifier = b"-".join(id_data) - identifier = identifier or b"Pymodbus" - return ReportDeviceIdResponse( - identifier=identifier, dev_id=device_id, transaction_id=self.transaction_id - ) + self.identifier = identifier or b"Pymodbus" + return self -ID_ON = 0xFF -ID_OFF = 0x00 +@dataclass +class FileRecord: + """Represents a file record and its relevant data.""" + file_number: int = 0 + record_number: int = 0 + record_data: bytes = b"" + record_length: int = 0 -class ReportDeviceIdResponse(ModbusPDU): - """ReportDeviceIdRequeste.""" + def __post_init__(self) -> None: + """Initialize a new instance.""" + if self.record_data: + if self.record_length: + raise ModbusException("Use either record_data= or record_length=") + self.record_length = len(self.record_data) + if self.record_length % 2: + raise ModbusException("length of record_data must be a multiple of 2") + self.record_length //= 2 - function_code = 0x11 - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: +class PDUreadFileRecord(ModbusPdu): + """ReadFileRecord.""" + + function_code = 0x14 + + def __init__( + self, + *args, + records: list[FileRecord] | None = None, + **kwargs, + ) -> None: + """Initialize.""" + super().__init__(*args, **kwargs) + self.records: list[FileRecord] = deepcopy(records) if records else [] + + def __str__(self) -> str: + """Build representation of pdu.""" + return super().__str__() + f", records={self.records}" + + def calculatePduSize(self, data: bytes) -> int: """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 + return 0 if (lx := len(data)) < 6 or lx < (leff := int(data[2]) + 3) else leff + + def to_bytes(self) -> bytes: + """Encode the message.""" + if self.is_request: + packet = self.preamble() + struct.pack("B", len(self.records) * 7) + for record in self.records: + packet += struct.pack( + ">BHHH", + 0x06, + record.file_number, + record.record_number, + record.record_length, + ) + else: + total = sum(len(record.record_data) + 2 for record in self.records) + packet = self.preamble() + struct.pack("B", total) + for record in self.records: + packet += struct.pack(">BB", len(record.record_data) + 1, 0x06) + packet += record.record_data + return packet + + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if self.is_request: + self.records = [] + if (byte_count := int(data[2])) + 3 != len(data): + return f"Invalid byte count: {byte_count}" + for count in range(3, byte_count + 3, 7): + decoded = struct.unpack(">BHHH", data[count : count + 7]) + record = FileRecord( + file_number=decoded[1], + record_number=decoded[2], + ) + record.record_length = decoded[3] + self.records.append(record) + else: + count = 1 + self.records.clear() + byte_count = int(data[2]) + while count < byte_count: + calc_length, _ = struct.unpack(">BB", data[count + 2 : count + 4]) + count += 2 + record_length = calc_length - 1 + record = FileRecord( + record_data=data[count : count + record_length], + ) + count += record_length + self.records.append(record) + return None + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get bits from datastore.""" + for record in self.records: + record.record_data = b"SERVER DUMMY RECORD." + record.record_length = len(record.record_data) // 2 + self.is_request = False + return self + + +class PDUwriteFileRecord(ModbusPdu): + """WriteFileRecord.""" + + function_code = 0x15 def __init__( self, - identifier: bytes = b"\x00", - status: bool = True, - dev_id: int = 1, - transaction_id: int = 0, + *args, + records: list[FileRecord] | None = None, + **kwargs, ) -> None: - """Initialize a new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id, status=status) - self.identifier = identifier - self.byte_count = 0 + """Initialize.""" + super().__init__(*args, **kwargs) + self.records: list[FileRecord] = records or [] - def x_encode(self) -> bytes: - """Encode the response.""" - status = ID_ON if self.status else ID_OFF - length = len(self.identifier) + 1 - packet = struct.pack(">B", length) - packet += self.identifier # we assume it is already encoded - packet += struct.pack(">B", status) + def __str__(self) -> str: + """Build representation of pdu.""" + return super().__str__() + f", records={self.records}" + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + return 0 if (lx := len(data)) < 6 or lx < (leff := int(data[2]) + 3) else leff + + def to_bytes(self) -> bytes: + """Encode the message.""" + total_length = sum((record.record_length * 2) + 7 for record in self.records) + packet = self.preamble() + struct.pack("B", total_length) + for record in self.records: + packet += struct.pack( + ">BHHH", + 0x06, + record.file_number, + record.record_number, + record.record_length, + ) + packet += record.record_data return packet - def x_decode(self, data: bytes) -> None: - """Decode a the response. - - Since the identifier is device dependent, we just return the - raw value that a user can decode to whatever it should be. - """ - self.byte_count = int(data[0]) - if not 1 <= self.byte_count <= len(data) - 1: - raise ModbusIOException( - f"byte_count {self.byte_count} outside 1..{len(data) - 1} " - f"for packet of length {len(data)}", - function_code=self.function_code, + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + self.records.clear() + if (byte_count := int(data[2])) + 3 != len(data): + return f"Invalid byte count: {byte_count}" + count = 0 + while count < byte_count: + decoded = struct.unpack(">BHHH", data[count + 3 : count + 10]) + calc_length = decoded[3] * 2 + count += calc_length + 7 + record = FileRecord( + file_number=decoded[1], + record_number=decoded[2], + record_data=data[count - calc_length : count], ) - self.identifier = data[1 : self.byte_count] - status = int(data[self.byte_count]) - self.status = status == ID_ON + record.record_length = decoded[3] + self.records.append(record) + return None + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get bits from datastore.""" + self.is_request = False + return self + + +class PDUreadFifoQueue(ModbusPdu): + """ReadFifoQueue.""" + function_code = 0x18 + + def __init__( + self, + *args, + values: list[int] | None = None, + address: int | None = None, + **kwargs, + ) -> None: + """Initialize.""" + super().__init__(*args, **kwargs) + self.values: list[int] = values or [] + self.address: int = address or 0 + + def __str__(self) -> str: + """Build representation of pdu.""" + return super().__str__() + f", address={self.address}, values={self.values}" + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + byte_count = 4 + if (lx := len(data)) < byte_count: + return 0 + if self.is_request: + return byte_count + byte_count += (int(data[2]) << 8) + int(data[3]) + return 0 if lx < byte_count else byte_count + + def to_bytes(self) -> bytes: + """Encode the message.""" + if self.is_request: + return self.preamble() + struct.pack(">H", self.address) + length = len(self.values) + packet = self.preamble() + struct.pack(">HH", 2 + length * 2, length) + for value in self.values: + packet += struct.pack(">H", value) + return packet -DecodePDU.add_pdu(ReadExceptionStatusRequest, ReadExceptionStatusResponse) -DecodePDU.add_pdu(GetCommEventCounterRequest, GetCommEventCounterResponse) -DecodePDU.add_pdu(GetCommEventLogRequest, GetCommEventLogResponse) -DecodePDU.add_pdu(ReportDeviceIdRequest, ReportDeviceIdResponse) + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + if self.is_request: + self.address = struct.unpack(">H", data[2:])[0] + return None + self.values = [] + byte_count, count = struct.unpack(">HH", data[2:6]) + if byte_count + 4 != len(data): + return f"Illegal bytecount {byte_count}" + if 6 + count * 2 != len(data): + return f"Invalid fifo count: {count}" + for index in range(0, count): + idx = 6 + index * 2 + self.values.append(struct.unpack(">H", data[idx : idx + 2])[0]) + return None + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get bits from datastore.""" + self.is_request = False + self.values = [0, 1, 2, 3] # server dummy response (should be in datastore) + return self + + +DecodePDU.add_pdu(PDUreadExceptionStatus) +DecodePDU.add_pdu(PDUgetCommEventCounter) +DecodePDU.add_pdu(PDUgetCommEventLog) +DecodePDU.add_pdu(PDUreportDeviceId) +DecodePDU.add_pdu(PDUreadFileRecord) +DecodePDU.add_pdu(PDUwriteFileRecord) +DecodePDU.add_pdu(PDUreadFifoQueue) diff --git a/pymodbus/pdu/pdu.py b/pymodbus/pdu/pdu.py index 19efc00478..7f260b7099 100644 --- a/pymodbus/pdu/pdu.py +++ b/pymodbus/pdu/pdu.py @@ -2,47 +2,78 @@ from __future__ import annotations -import asyncio -from abc import abstractmethod -from collections.abc import Sequence +import struct +from collections.abc import Awaitable, Callable, Sequence +from typing import TypeAlias -from ..datastore import ModbusServerContext -from ..exceptions import ModbusIOException, NotImplementedException +from ..constants import MAX_TRANSACTION_ID, ExcCodes +from ..exceptions import ModbusIOException +from ..logging import Log -class ModbusPDU: +StoreGet: TypeAlias = Callable[ + [int, int, int, int], Awaitable[list[int] | list[bool] | ExcCodes] +] +StoreSet: TypeAlias = Callable[ + [int, int, int, Sequence[int] | Sequence[bool]], Awaitable[ExcCodes | None] +] + + +class ModbusPdu: """Base class for all Modbus messages.""" - function_code: int = 0 + function_code: int = -1 sub_function_code: int = -1 + MAX_COUNT: int = 10000 def __init__( self, - dev_id: int = 0, + is_request: bool, + dev_id: int, transaction_id: int = 0, - address: int = 0, - count: int = 0, - bits: Sequence[bool] | None = None, - registers: Sequence[int] | None = None, - status: int = 1, ) -> None: """Initialize the base data for a modbus request.""" + self.is_request: bool = is_request self.dev_id: int = dev_id - if dev_id > 255: - raise ModbusIOException( - f"Invalid ID {dev_id}", - transaction_id=transaction_id, - dev_id=dev_id, - ) self.transaction_id: int = transaction_id - self.address: int = address - self.bits: Sequence[bool] = bits or [] - self.registers: Sequence[int] = registers or [] - self.count: int = count or len(self.registers) - self.status: int = status - self.exception_code: int = 0 - self.fut: asyncio.Future - self.retries: int = 0 + self.registers: Sequence[int] + self.bits: Sequence[bool] + self.address: int + self.count: int + if not 0 <= self.dev_id <= 255: + self.raiseExp("Invalid device id({dev_id})") + if not 0 <= self.transaction_id <= MAX_TRANSACTION_ID: + self.raiseExp("Invalid device id({dev_id})") + + def raiseExp(self, error: str) -> None: + """Raise exception, with known data.""" + raise ModbusIOException( + error, + dev_id=self.dev_id, + function_code=self.function_code, + transaction_id=self.transaction_id, + ) + + def respondExp(self, exc_code: ExcCodes) -> PDUexception: + """Build exception response.""" + return PDUexception( + self.dev_id, + self.function_code, + exc_code, + transaction_id=self.transaction_id, + ) + + def isError(self) -> bool: + """Check if the error is a success or failure.""" + return False + + def __str__(self) -> str: + """Build representation of pdu.""" + x_type = "request" if self.is_request else "response" + return ( + f"{self.__class__.__name__}-{x_type} " + f"(dev_id={self.dev_id}, function_code={self.function_code}, transaction_id={self.transaction_id}" + ) @classmethod def decode_sub_function_code(cls, data: bytes) -> int: @@ -50,56 +81,181 @@ def decode_sub_function_code(cls, data: bytes) -> int: _ = data return -1 - def isError(self) -> bool: - """Check if the error is a success or failure.""" - return False + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + _ = data + return 2 + + def preamble(self) -> bytes: + """Encode the message.""" + return struct.pack(">BB", self.dev_id, self.function_code) - def verifyCount(self, max_count: int, count: int = -1) -> None: - """Validate API supplied count.""" - if count == -1: - count = self.count - if not 1 <= count <= max_count: - raise ValueError(f"1 <= count {count} <= {max_count} !") + def to_bytes(self) -> bytes: + """Encode the message.""" + return b"" + + def from_bytes(self, data: bytes) -> str | None: + """Decode message.""" + self.dev_id, self.function_code = struct.unpack(">BB", data[:2]) + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get/Set values from datastore.""" + _ = v_get, v_set + return self.respondExp(ExcCodes.DEVICE_BUSY) + + +class PDUexception(ModbusPdu): + """Base class for a modbus exception PDU.""" + + def __init__( + self, + dev_id: int, + function_code: int, + exception_code: int, + **kwargs, + ) -> None: + """Initialize.""" + super().__init__(False, dev_id, **kwargs) + self.function_code = function_code | 0x80 + self.exception_code = exception_code - def verifyAddress(self, address: int = -1) -> None: - """Validate API supplied address.""" - if address == -1: - address = self.address - if not 0 <= address <= 65535: - raise ValueError(f"0 <= address {address} <= 65535 !") + def isError(self) -> bool: + """Check if the error is a success or failure.""" + return True def __str__(self) -> str: - """Build a representation of a Modbus response.""" - return ( - f"{self.__class__.__name__}(" - f"dev_id={self.dev_id}, " - f"transaction_id={self.transaction_id}, " - f"address={self.address}, " - f"count={self.count}, " - f"bits={self.bits!s}, " - f"registers={self.registers!s}, " - f"status={self.status!s}, " - f"retries={self.retries})" - ) + """Build representation of pdu.""" + return super().__str__() + f", exception_code={self.exception_code}" + + def calculatePduSize(self, data: bytes) -> int: + """Calculate the size of a PDU.""" + if len(data) < 3: + return 0 + return 3 - @abstractmethod - def x_encode(self) -> bytes: + def to_bytes(self) -> bytes: """Encode the message.""" + return self.preamble() + struct.pack(">B", self.exception_code) - @abstractmethod - def x_decode(self, data: bytes) -> None: - """Decode data part of the message.""" - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - _ = context, device_id - raise NotImplementedException( - f"datastore_update() not implemented {self.__class__.__name__}" - ) + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + self.function_code, self.exception_code = struct.unpack(">BB", data[1:]) + + async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: + """Get from datastore.""" + self.exception_code = ExcCodes.ILLEGAL_FUNCTION + return self + + +class DecodePDU: + """Decode pdu requests/responses (server/client).""" + + pdu_table: dict[int, type[ModbusPdu]] = {} + pdu_sub_table: dict[int, dict[int, type[ModbusPdu]]] = {} + + def __init__(self, is_server: bool) -> None: + """Initialize function_tables.""" + self.is_server = is_server @classmethod - @abstractmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: + def _lookupPduClass(cls, data: bytes) -> type[ModbusPdu] | None: + """Use `function_code` to determine the class of the PDU.""" + if (data_len := len(data)) < 2: + return None + if (func_code := int(data[1])) > 0x80: + return PDUexception + if not (pdu := cls.pdu_table.get(func_code, None)): + return None + if data_len == 2 or (sub_func_code := pdu.decode_sub_function_code(data)) < 0: + return pdu + return cls.pdu_sub_table[func_code].get(sub_func_code, None) + + @classmethod + def add_pdu(cls, pdu: type[ModbusPdu]) -> None: + """Register request/response.""" + cls.pdu_table[pdu.function_code] = pdu + if pdu.sub_function_code >= 0: + if pdu.function_code not in cls.pdu_sub_table: + cls.pdu_sub_table[pdu.function_code] = {} + cls.pdu_sub_table[pdu.function_code][pdu.sub_function_code] = pdu + + def decode(self, data: bytes) -> ModbusPdu: + """Decode a frame.""" + if not data: + raise ModbusIOException("Cannot decode empty frame") + if not (pdu_class := self._lookupPduClass(data)): + raise ModbusIOException("Unknown response ") + if pdu_class == PDUexception: + pdu = PDUexception(0, 0, 0) + else: + pdu = pdu_class(self.is_server, 0) + if len(data) != pdu.calculatePduSize(data): + raise ModbusIOException("Unknown response ", function_code=int(data[1])) + if txt := pdu.from_bytes(data): + Log.debug(f"cannot decode PDU {pdu!s} reason: {txt}") + pdu = PDUexception(0, data[1], ExcCodes.ILLEGAL_VALUE) + else: + Log.debug("decoded PDU " + str(pdu)) + return pdu + + def calculatePduSize(self, data: bytes) -> int: """Calculate the size of a PDU.""" + if not (pdu_class := self._lookupPduClass(data)): + return 0 + if pdu_class == PDUexception: + pdu = PDUexception(0, 0, 0) + else: + pdu = pdu_class(self.is_server, 0) + return pdu.calculatePduSize(data) + + def encode(self, pdu: ModbusPdu) -> bytes: + """Create message from PDU.""" + return pdu.to_bytes() + + +def pack_bitstring(bits: Sequence[bool], align_byte=True) -> bytes: + """Create a bytestring out of a list of bits. + + example:: + + bits = [True, False, False, False] + + [False, False, False, True] + + [True, False, True, False] + + [False, False, False, False] + result = pack_bitstring(bits) + bytes 0x05 0x81 + """ + ret = b"" + i = packed = 0 + t_bits = list(bits) + bits_extra = 8 if align_byte else 16 + if extra := len(bits) % bits_extra: + t_bits += [False] * (bits_extra - extra) + for byte_inx in range(0, len(t_bits), 8): + for bit in reversed(t_bits[byte_inx : byte_inx + 8]): + packed <<= 1 + if bit: + packed += 1 + i += 1 + if i == 8: + ret += struct.pack(">B", packed) + i = packed = 0 + return ret + + +def unpack_bitstring(data: bytes) -> list[bool]: + """Create bit list out of a bytestring. + + example:: + + bytes 0x05 0x81 + result = unpack_bitstring(bytes) + + [True, False, True, False] + [False, False, False, False] + [True, False, False, False] + [False, False, False, True] + """ + res = [] + for _, t_byte in enumerate(data): + for bit in (1, 2, 4, 8, 16, 32, 64, 128): + res.append(bool(t_byte & bit)) + return res diff --git a/pymodbus/pdu/register_message.py b/pymodbus/pdu/register_message.py deleted file mode 100644 index 9475286cdc..0000000000 --- a/pymodbus/pdu/register_message.py +++ /dev/null @@ -1,510 +0,0 @@ -"""Register Reading Request/Response.""" - -from __future__ import annotations - -import struct -from collections.abc import Sequence -from typing import cast - -from ..constants import ExcCodes -from ..datastore import ModbusServerContext -from ..exceptions import ModbusIOException -from .decoders import DecodePDU -from .exceptionresponse import ExceptionResponse -from .pdu import ModbusPDU - - -class ReadHoldingRegistersRequest(ModbusPDU): - """ReadHoldingRegistersRequest.""" - - function_code = 3 - MAX_COUNT = 125 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 - - def x_encode(self) -> bytes: - """Encode the request packet.""" - self.verifyAddress() - self.verifyCount(self.MAX_COUNT) - return struct.pack(">HH", self.address, self.count) - - def x_decode(self, data: bytes) -> None: - """Decode a register request packet.""" - self.address, self.count = struct.unpack(">HH", data[:4]) - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - if not 1 <= self.count <= self.MAX_COUNT: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - values = await context.async_getValues( - device_id, self.function_code, self.address, self.count - ) - if isinstance(values, ExcCodes): - return ExceptionResponse(self.function_code, values) - return ReadHoldingRegistersResponse( - registers=cast(list[int], values), - dev_id=device_id, - transaction_id=self.transaction_id, - ) - - -class ReadHoldingRegistersResponse(ModbusPDU): - """ReadHoldingRegistersResponse.""" - - function_code = 3 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 - - def x_encode(self) -> bytes: - """Encode the response packet.""" - result = struct.pack(">B", len(self.registers) * 2) - for register in self.registers: - result += struct.pack(">H", register) - return result - - def x_decode(self, data: bytes) -> None: - """Decode a register response packet.""" - self.registers = [] - if (data_len := int(data[0])) >= len(data): - raise ModbusIOException( - f"byte_count {data_len} > length of packet {len(data)}", - function_code=self.function_code, - ) - for i in range(1, data_len, 2): - self.registers.append(struct.unpack(">H", data[i : i + 2])[0]) - - -class ReadInputRegistersRequest(ModbusPDU): - """ReadInputRegistersRequest.""" - - function_code = 4 - MAX_COUNT = 125 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 - - def x_encode(self) -> bytes: - """Encode the request packet.""" - self.verifyAddress() - self.verifyCount(self.MAX_COUNT) - return struct.pack(">HH", self.address, self.count) - - def x_decode(self, data: bytes) -> None: - """Decode a register request packet.""" - self.address, self.count = struct.unpack(">HH", data[:4]) - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - if not 1 <= self.count <= self.MAX_COUNT: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - values = await context.async_getValues( - device_id, self.function_code, self.address, self.count - ) - if isinstance(values, ExcCodes): - return ExceptionResponse(self.function_code, values) - return ReadInputRegistersResponse( - registers=cast(list[int], values), - dev_id=device_id, - transaction_id=self.transaction_id, - ) - - -class ReadInputRegistersResponse(ModbusPDU): - """ReadInputRegistersResponse.""" - - function_code = 4 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 - - def x_encode(self) -> bytes: - """Encode the response packet.""" - result = struct.pack(">B", len(self.registers) * 2) - for register in self.registers: - result += struct.pack(">H", register) - return result - - def x_decode(self, data: bytes) -> None: - """Decode a register response packet.""" - self.registers = [] - if (data_len := int(data[0])) >= len(data): - raise ModbusIOException( - f"byte_count {data_len} > length of packet {len(data)}", - function_code=self.function_code, - ) - for i in range(1, data_len, 2): - self.registers.append(struct.unpack(">H", data[i : i + 2])[0]) - - -class ReadWriteMultipleRegistersRequest(ModbusPDU): - """ReadWriteMultipleRegistersRequest.""" - - function_code = 23 - MAX_READ_COUNT = 125 - MAX_WRITE_COUNT = 121 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[10]) + 10 + 3 - - def __init__( - self, - read_address: int = 0x00, - read_count: int = 0, - write_address: int = 0x00, - write_registers: Sequence[int] | None = None, - dev_id: int = 1, - transaction_id: int = 0, - ) -> None: - """Initialize a new request message.""" - if not write_registers: - write_registers = [] - super().__init__(transaction_id=transaction_id, dev_id=dev_id) - self.read_address = read_address - self.read_count = read_count - self.write_address = write_address - self.write_registers = write_registers - self.write_count = len(self.write_registers) - self.write_byte_count = self.write_count * 2 - self._payload_byte_count: int | None = None - - def x_encode(self) -> bytes: - """Encode the request packet.""" - self.verifyAddress(address=self.read_address) - self.verifyAddress(address=self.write_address) - self.verifyCount(self.MAX_READ_COUNT, count=self.read_count) - self.verifyCount(self.MAX_WRITE_COUNT, count=self.write_count) - result = struct.pack( - ">HHHHB", - self.read_address, - self.read_count, - self.write_address, - self.write_count, - self.write_byte_count, - ) - for register in self.write_registers: - result += struct.pack(">H", register) - return result - - def x_decode(self, data: bytes) -> None: - """Decode the register request packet.""" - ( - self.read_address, - self.read_count, - self.write_address, - self.write_count, - self.write_byte_count, - ) = struct.unpack(">HHHHB", data[:9]) - self.verifyCount(self.MAX_READ_COUNT, count=self.write_count) - self._payload_byte_count = len(data) - 9 - self.write_registers = [ - struct.unpack(">H", data[i : i + 2])[0] - for i in range(9, min(len(data), self.write_byte_count + 9) - 1, 2) - ] - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - if not (1 <= self.read_count <= 0x07D): - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - if not 1 <= self.write_count <= 0x079: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - if self.write_byte_count != self.write_count * 2 or ( - self._payload_byte_count is not None - and self._payload_byte_count != self.write_byte_count - ): - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - rc = await context.async_setValues( - device_id, self.function_code, self.write_address, self.write_registers - ) - if rc: - return ExceptionResponse(self.function_code, rc) - registers = await context.async_getValues( - device_id, self.function_code, self.read_address, self.read_count - ) - if isinstance(registers, ExcCodes): - return ExceptionResponse(self.function_code, registers) - return ReadWriteMultipleRegistersResponse( - registers=cast(list[int], registers), - dev_id=device_id, - transaction_id=self.transaction_id, - ) - - -class ReadWriteMultipleRegistersResponse(ModbusPDU): - """ReadWriteMultipleRegistersResponse.""" - - function_code = 23 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[2]) + 2 + 3 - - def x_encode(self) -> bytes: - """Encode the response packet.""" - result = struct.pack(">B", len(self.registers) * 2) - for register in self.registers: - result += struct.pack(">H", register) - return result - - def x_decode(self, data: bytes) -> None: - """Decode a register response packet.""" - self.registers = [] - if (data_len := int(data[0])) >= len(data): - raise ModbusIOException( - f"byte_count {data_len} > length of packet {len(data)}", - function_code=self.function_code, - ) - for i in range(1, data_len, 2): - self.registers.append(struct.unpack(">H", data[i : i + 2])[0]) - - -class WriteSingleRegisterResponse(ModbusPDU): - """WriteSingleRegisterResponse.""" - - function_code = 6 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 - - def x_encode(self) -> bytes: - """Encode a write single register packet packet request.""" - return struct.pack(">HH", self.address, self.registers[0]) - - def x_decode(self, data: bytes) -> None: - """Decode a write single register packet packet request.""" - self.address, register = struct.unpack(">HH", data[:4]) - self.registers = [register] - - -class WriteSingleRegisterRequest(ModbusPDU): - """WriteSingleRegisterRequest.""" - - function_code = 6 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 - - def x_encode(self) -> bytes: - """Encode a write single register packet packet request.""" - return struct.pack(">HH", self.address, self.registers[0]) - - def x_decode(self, data: bytes) -> None: - """Decode a write single register packet packet request.""" - self.address, register = struct.unpack(">HH", data[:4]) - self.registers = [register] - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - if not 0 <= self.registers[0] <= 0xFFFF: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - rc = await context.async_setValues( - device_id, self.function_code, self.address, self.registers - ) - if rc: - return ExceptionResponse(self.function_code, rc) - values = await context.async_getValues( - device_id, self.function_code, self.address, 1 - ) - if isinstance(values, ExcCodes): - return ExceptionResponse(self.function_code, values) - return WriteSingleRegisterResponse( - address=self.address, registers=cast(list[int], values) - ) - - -class WriteMultipleRegistersRequest(ModbusPDU): - """WriteMultipleRegistersRequest.""" - - function_code = 16 - _pdu_length = 5 # func + adress1 + adress2 + outputQuant1 + outputQuant2 - byte_count: int | None = None - _payload_byte_count: int | None = None - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return int(data[6]) + 6 + 3 - - def x_encode(self) -> bytes: - """Encode a write single register packet packet request.""" - packet = struct.pack(">HHB", self.address, self.count, self.count * 2) - for value in self.registers: - packet += struct.pack(">H", value) - return packet - - def x_decode(self, data: bytes) -> None: - """Decode a write single register packet packet request.""" - self.address, self.count, self.byte_count = struct.unpack(">HHB", data[:5]) - self._payload_byte_count = len(data) - 5 - self.registers = [ - struct.unpack(">H", data[idx : idx + 2])[0] - for idx in range(5, min(len(data), self.byte_count + 5) - 1, 2) - ] - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - if not 1 <= self.count <= 0x07B: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - if self.byte_count is not None and ( - self.byte_count != self.count * 2 - or self._payload_byte_count != self.byte_count - ): - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - rc = await context.async_setValues( - device_id, self.function_code, self.address, self.registers - ) - if rc: - return ExceptionResponse(self.function_code, rc) - return WriteMultipleRegistersResponse( - address=self.address, - count=self.count, - dev_id=device_id, - transaction_id=self.transaction_id, - ) - - -class WriteMultipleRegistersResponse(ModbusPDU): - """WriteMultipleRegistersResponse.""" - - function_code = 16 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 8 - - def x_encode(self) -> bytes: - """Encode a write single register packet packet request.""" - return struct.pack(">HH", self.address, self.count) - - def x_decode(self, data: bytes) -> None: - """Decode a write single register packet packet request.""" - self.address, self.count = struct.unpack(">HH", data[:4]) - - -class MaskWriteRegisterRequest(ModbusPDU): - """MaskWriteRegisterRequest.""" - - function_code = 0x16 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 10 - - def __init__( - self, - address=0x0000, - and_mask=0xFFFF, - or_mask=0x0000, - dev_id=1, - transaction_id=0, - ) -> None: - """Initialize a new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id, address=address) - self.and_mask = and_mask - self.or_mask = or_mask - - def x_encode(self) -> bytes: - """Encode the request packet.""" - return struct.pack(">HHH", self.address, self.and_mask, self.or_mask) - - def x_decode(self, data: bytes) -> None: - """Decode the incoming request.""" - self.address, self.and_mask, self.or_mask = struct.unpack(">HHH", data[:6]) - - async def datastore_update( - self, context: ModbusServerContext, device_id: int - ) -> ModbusPDU: - """Update diagnostic request on the given device.""" - if not 0x0000 <= self.and_mask <= 0xFFFF: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - if not 0x0000 <= self.or_mask <= 0xFFFF: - return ExceptionResponse(self.function_code, ExcCodes.ILLEGAL_VALUE) - values = await context.async_getValues( - device_id, self.function_code, self.address, 1 - ) - if isinstance(values, ExcCodes): - return ExceptionResponse(self.function_code, values) - values = (cast(Sequence[int | bool], values)[0] & self.and_mask) | ( - self.or_mask & ~self.and_mask - ) - rc = await context.async_setValues( - device_id, self.function_code, self.address, cast(list[int], [values]) - ) - if rc: - return ExceptionResponse(self.function_code, rc) - return MaskWriteRegisterResponse( - address=self.address, - and_mask=self.and_mask, - or_mask=self.or_mask, - dev_id=device_id, - transaction_id=self.transaction_id, - ) - - -class MaskWriteRegisterResponse(ModbusPDU): - """MaskWriteRegisterResponse.""" - - function_code = 0x16 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 10 - - def __init__( - self, - address=0x0000, - and_mask=0xFFFF, - or_mask=0x0000, - dev_id=1, - transaction_id=0, - ) -> None: - """Initialize new instance.""" - super().__init__(transaction_id=transaction_id, dev_id=dev_id, address=address) - self.and_mask = and_mask - self.or_mask = or_mask - - def x_encode(self) -> bytes: - """Encode the response.""" - self.verifyAddress() - return struct.pack(">HHH", self.address, self.and_mask, self.or_mask) - - def x_decode(self, data: bytes) -> None: - """Decode a the response.""" - self.address, self.and_mask, self.or_mask = struct.unpack(">HHH", data[:6]) - - -DecodePDU.add_pdu(ReadHoldingRegistersRequest, ReadHoldingRegistersResponse) -DecodePDU.add_pdu(ReadInputRegistersRequest, ReadInputRegistersResponse) -DecodePDU.add_pdu(WriteMultipleRegistersRequest, WriteMultipleRegistersResponse) -DecodePDU.add_pdu(WriteSingleRegisterRequest, WriteSingleRegisterResponse) -DecodePDU.add_pdu(ReadWriteMultipleRegistersRequest, ReadWriteMultipleRegistersResponse) -DecodePDU.add_pdu(MaskWriteRegisterRequest, MaskWriteRegisterResponse) diff --git a/pymodbus/pdu/utils.py b/pymodbus/pdu/utils.py deleted file mode 100644 index 532f33659b..0000000000 --- a/pymodbus/pdu/utils.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Contains base classes for modbus request/response/error packets.""" - -from __future__ import annotations - -import struct -from collections.abc import Sequence - - -def pack_bitstring(bits: Sequence[bool], align_byte=True) -> bytes: - """Create a bytestring out of a list of bits. - - example:: - - bits = [True, False, False, False] + - [False, False, False, True] + - [True, False, True, False] + - [False, False, False, False] - result = pack_bitstring(bits) - bytes 0x05 0x81 - """ - ret = b"" - i = packed = 0 - t_bits = list(bits) - bits_extra = 8 if align_byte else 16 - if extra := len(bits) % bits_extra: - t_bits += [False] * (bits_extra - extra) - for byte_inx in range(0, len(t_bits), 8): - for bit in reversed(t_bits[byte_inx : byte_inx + 8]): - packed <<= 1 - if bit: - packed += 1 - i += 1 - if i == 8: - ret += struct.pack(">B", packed) - i = packed = 0 - return ret - - -def unpack_bitstring(data: bytes) -> list[bool]: - """Create bit list out of a bytestring. - - example:: - - bytes 0x05 0x81 - result = unpack_bitstring(bytes) - - [True, False, True, False] + [False, False, False, False] - [True, False, False, False] + [False, False, False, True] - """ - res = [] - for _, t_byte in enumerate(data): - for bit in (1, 2, 4, 8, 16, 32, 64, 128): - res.append(bool(t_byte & bit)) - return res diff --git a/pymodbus/server/base.py b/pymodbus/server/base.py index fff75ddf52..4a8007745c 100644 --- a/pymodbus/server/base.py +++ b/pymodbus/server/base.py @@ -10,8 +10,12 @@ from ..exceptions import ParameterException from ..framer import FRAMER_NAME_TO_CLASS, FramerType from ..logging import Log -from ..pdu import DecodePDU, ModbusPDU -from ..pdu.device import ModbusControlBlock, ModbusDeviceIdentification +from ..pdu import ( + DecodePDU, + ModbusControlBlock, + ModbusDeviceIdentification, + ModbusPdu, +) from ..simulator import SimDevice from ..simulator.simcore import SimCore from ..transport import CommParams, ModbusProtocol @@ -35,9 +39,9 @@ def __init__( identity: ModbusDeviceIdentification | None, framer: FramerType, trace_packet: Callable[[bool, bytes], bytes] | None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None, trace_connect: Callable[[bool], None] | None, - custom_pdu: list[type[ModbusPDU]] | None, + custom_pdu: list[type[ModbusPdu]] | None, ) -> None: """Initialize base server.""" if not 0 <= params.max_connections <= MAX_CONNECTIONS: @@ -51,8 +55,8 @@ def __init__( self.loop = asyncio.get_running_loop() self.decoder = DecodePDU(True) if custom_pdu: - for func in custom_pdu: - self.decoder.register(func) + for new_pdu in custom_pdu: + DecodePDU.add_pdu(new_pdu) self.context: ModbusServerContext | SimCore if not isinstance(context, ModbusServerContext): self.context = SimCore(context) diff --git a/pymodbus/server/requesthandler.py b/pymodbus/server/requesthandler.py index c267703f0d..4deaa2ef45 100644 --- a/pymodbus/server/requesthandler.py +++ b/pymodbus/server/requesthandler.py @@ -9,7 +9,7 @@ from ..constants import ExcCodes from ..exceptions import ModbusIOException, NoSuchIdException from ..logging import Log -from ..pdu import ExceptionResponse, ModbusPDU +from ..pdu import ModbusPdu, PDUexception from ..transaction import TransactionManager from ..transport import CommParams @@ -68,11 +68,11 @@ def callback_data(self, data: bytes, addr: tuple | None = None) -> int: new_len = super().callback_data(data[used_len:], addr) except ModbusIOException as exc: function_code = 0x00 if exc.fcode is None else exc.fcode - response = ExceptionResponse( + response = PDUexception( + exc.dev_id, function_code, - exception_code=ExcCodes.ILLEGAL_FUNCTION, - device_id=exc.dev_id, - transaction=exc.transaction_id, + ExcCodes.ILLEGAL_FUNCTION, + transaction_id=exc.transaction_id, ) new_len = exc.used_len self.server_send(response, addr) @@ -85,36 +85,39 @@ def callback_data(self, data: bytes, addr: tuple | None = None) -> int: break return used_len - def handle_later(self, pdu: ModbusPDU, addr: tuple | None) -> None: + def handle_later(self, pdu: ModbusPdu, addr: tuple | None) -> None: """Change sync (async not allowed in call_soon) to async.""" asyncio.run_coroutine_threadsafe(self.handle_request(pdu, addr), self.loop) - async def handle_request(self, pdu: ModbusPDU, addr: tuple | None = None) -> None: + async def handle_request(self, pdu: ModbusPdu, addr: tuple | None = None) -> None: """Handle request.""" try: + get_v = self.server.context.async_getValues + set_v = self.server.context.async_setValues if self.server.broadcast_enable and not pdu.dev_id: # if broadcasting then execute on all device contexts, # note response will be ignored + remember = pdu.dev_id for dev_id in self.server.context.device_ids(): - await pdu.datastore_update(self.server.context, dev_id) + pdu.dev_id = dev_id + await pdu.build_response(get_v, set_v) + pdu.dev_id = remember return - response = await pdu.datastore_update(self.server.context, pdu.dev_id) + response = await pdu.build_response(get_v, set_v) except NoSuchIdException: if self.server.ignore_missing_devices: Log.debug("ignoring request for unknown device id: {}", pdu.dev_id) return # the client will simply timeout waiting for a response Log.error("requested device id does not exist: {}", pdu.dev_id) - response = ExceptionResponse( - pdu.function_code, ExcCodes.GATEWAY_NO_RESPONSE - ) + response = PDUexception(0, pdu.function_code, ExcCodes.GATEWAY_NO_RESPONSE) except Exception as exc: # pylint: disable=broad-except Log.error( "Datastore unable to fulfill request: {}; {}", exc, traceback.format_exc(), ) - response = ExceptionResponse(pdu.function_code, ExcCodes.DEVICE_FAILURE) + response = PDUexception(0, pdu.function_code, ExcCodes.DEVICE_FAILURE) response.transaction_id = pdu.transaction_id response.dev_id = pdu.dev_id self.server_send(response, addr) diff --git a/pymodbus/server/server.py b/pymodbus/server/server.py index e8e4ed5e8f..8e76fc0ee3 100644 --- a/pymodbus/server/server.py +++ b/pymodbus/server/server.py @@ -6,8 +6,7 @@ from ..datastore import ModbusServerContext from ..framer import FramerType -from ..pdu import ModbusPDU -from ..pdu.device import ModbusDeviceIdentification +from ..pdu import ModbusDeviceIdentification, ModbusPdu from ..simulator import SimDevice from ..transport import CommParams, CommType from .base import ModbusBaseServer @@ -30,9 +29,9 @@ def __init__( ignore_missing_devices: bool = False, broadcast_enable: bool = False, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, - custom_pdu: list[type[ModbusPDU]] | None = None, + custom_pdu: list[type[ModbusPdu]] | None = None, max_connections: int = 10, ): """Initialize the socket server. @@ -50,7 +49,7 @@ def __init__( :param trace_packet: Called with bytestream received/to be sent :param trace_pdu: Called with PDU received/to be sent :param trace_connect: Called when connected/disconnected - :param custom_pdu: list of ModbusPDU custom classes + :param custom_pdu: list of ModbusPdu custom classes :param max_connections: Maximum number of connections (0 = no limit) """ params = getattr( @@ -98,9 +97,9 @@ def __init__( ignore_missing_devices=False, broadcast_enable=False, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, - custom_pdu: list[type[ModbusPDU]] | None = None, + custom_pdu: list[type[ModbusPdu]] | None = None, max_connections: int = 10, ): """Overloaded initializer for the socket server. @@ -119,7 +118,7 @@ def __init__( :param trace_packet: Called with bytestream received/to be sent :param trace_pdu: Called with PDU received/to be sent :param trace_connect: Called when connected/disconnected - :param custom_pdu: list of ModbusPDU custom classes + :param custom_pdu: list of ModbusPdu custom classes :param max_connections: Maximum number of connections (0 = no limit) """ if not sslctx: @@ -166,9 +165,9 @@ def __init__( ignore_missing_devices: bool = False, broadcast_enable: bool = False, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, - custom_pdu: list[type[ModbusPDU]] | None = None, + custom_pdu: list[type[ModbusPdu]] | None = None, max_connections: int = 10, ): """Overloaded initializer for the socket server. @@ -186,7 +185,7 @@ def __init__( :param trace_packet: Called with bytestream received/to be sent :param trace_pdu: Called with PDU received/to be sent :param trace_connect: Called when connected/disconnected - :param custom_pdu: list of ModbusPDU custom classes + :param custom_pdu: list of ModbusPdu custom classes :param max_connections: Maximum number of connections (0 = no limit) """ # ---------------- @@ -237,9 +236,9 @@ def __init__( broadcast_enable: bool = False, reconnect_delay: float = 2, trace_packet: Callable[[bool, bytes], bytes] | None = None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None = None, trace_connect: Callable[[bool], None] | None = None, - custom_pdu: list[type[ModbusPDU]] | None = None, + custom_pdu: list[type[ModbusPdu]] | None = None, ): """Initialize the socket server. @@ -262,7 +261,7 @@ def __init__( :param trace_packet: Called with bytestream received/to be sent :param trace_pdu: Called with PDU received/to be sent :param trace_connect: Called when connected/disconnected - :param custom_pdu: list of ModbusPDU custom classes + :param custom_pdu: list of ModbusPdu custom classes """ params = CommParams( comm_type=CommType.SERIAL, diff --git a/pymodbus/server/simulator/http_server.py b/pymodbus/server/simulator/http_server.py index 8157f99d4d..54b24210b8 100644 --- a/pymodbus/server/simulator/http_server.py +++ b/pymodbus/server/simulator/http_server.py @@ -17,8 +17,7 @@ from ...datastore import ModbusServerContext, ModbusSimulatorContext from ...datastore.simulator import CellType, Label from ...logging import Log -from ...pdu import DecodePDU -from ...pdu.device import ModbusDeviceIdentification +from ...pdu import DecodePDU, ModbusDeviceIdentification from ..server import ( ModbusSerialServer, ModbusTcpServer, @@ -377,7 +376,7 @@ def build_html_calls(self, params: dict, html: str) -> str: # pragma: no cover else "" ) function_codes = "" - for function in DecodePDU(True).list_function_codes(): + for function in DecodePDU.pdu_table: selected = "selected" if function == self.call_monitor.function else "" function_codes += ( f"" @@ -546,7 +545,7 @@ def build_json_calls(self, params: dict) -> dict: ) function_codes = [] - for function in DecodePDU(True).list_function_codes(): + for function in DecodePDU.pdu_table: function_codes.append( { "value": function, diff --git a/pymodbus/transaction/transaction.py b/pymodbus/transaction/transaction.py index 26ada4afdb..491974548e 100644 --- a/pymodbus/transaction/transaction.py +++ b/pymodbus/transaction/transaction.py @@ -7,10 +7,11 @@ from threading import RLock from time import monotonic +from ..constants import ExcCodes from ..exceptions import ConnectionException, ModbusIOException from ..framer import FramerBase from ..logging import Log -from ..pdu import ModbusPDU +from ..pdu import ModbusPdu, PDUexception from ..transport import CommParams, CommType, ModbusProtocol @@ -40,7 +41,7 @@ def __init__( retries: int, is_server: bool, trace_packet: Callable[[bool, bytes], bytes] | None, - trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None, + trace_pdu: Callable[[bool, ModbusPdu], ModbusPdu] | None, trace_connect: Callable[[bool], None] | None, sync_client=None, ) -> None: @@ -69,7 +70,7 @@ def __init__( self.cancelled_requests: dict[ tuple[int, int], tuple[asyncio.Future, float] ] = {} - self.last_pdu: ModbusPDU | None = None + self.last_pdu: ModbusPdu | None = None self.last_addr: tuple | None = None def dummy_trace_packet(self, sending: bool, data: bytes) -> bytes: @@ -77,7 +78,7 @@ def dummy_trace_packet(self, sending: bool, data: bytes) -> bytes: _ = sending return data - def dummy_trace_pdu(self, sending: bool, pdu: ModbusPDU) -> ModbusPDU: + def dummy_trace_pdu(self, sending: bool, pdu: ModbusPdu) -> ModbusPdu: """Do dummy trace.""" _ = sending return pdu @@ -86,7 +87,7 @@ def dummy_trace_connect(self, connect: bool) -> None: """Do dummy trace.""" _ = connect - def sync_get_response(self, dev_id, tid) -> ModbusPDU: + def sync_get_response(self, dev_id, tid) -> ModbusPdu: """Receive until PDU is correct or timeout.""" databuffer = b"" deadline = monotonic() + self.comm_params.timeout_connect @@ -127,7 +128,7 @@ def sync_get_response(self, dev_id, tid) -> ModbusPDU: @staticmethod def _io_exception_from_request( - message: str, request: ModbusPDU + message: str, request: ModbusPdu ) -> ModbusIOException: """Build ModbusIOException from an outstanding request.""" return ModbusIOException( @@ -137,7 +138,7 @@ def _io_exception_from_request( dev_id=request.dev_id, ) - def _no_response(self, request: ModbusPDU) -> ModbusIOException: + def _no_response(self, request: ModbusPdu) -> ModbusIOException: """Count a request that got no response, and build the exception to raise.""" if self.count_until_disconnect < 0: if self.comm_params.comm_type != CommType.SERIAL: @@ -151,7 +152,7 @@ def _no_response(self, request: ModbusPDU) -> ModbusIOException: Log.error(txt) return self._io_exception_from_request(txt, request) - def sync_execute(self, no_response_expected: bool, request: ModbusPDU) -> ModbusPDU: + def sync_execute(self, no_response_expected: bool, request: ModbusPdu) -> ModbusPdu: """Execute requests asynchronously. REMARK: this method is identical to execute, apart from the lock and sync_receive. @@ -183,7 +184,6 @@ def sync_execute(self, no_response_expected: bool, request: ModbusPDU) -> Modbus f"ERROR: request uses transaction id={request.transaction_id} but received {response.transaction_id}.", request, ) - response.retries = count_retries return response except asyncio.exceptions.TimeoutError: count_retries += 1 @@ -199,8 +199,8 @@ async def _connect_if_needed(self) -> None: ) async def execute( - self, no_response_expected: bool, request: ModbusPDU - ) -> ModbusPDU: + self, no_response_expected: bool, request: ModbusPdu + ) -> ModbusPdu: """Execute requests asynchronously. REMARK: this method is identical to sync_execute, apart from the lock, try/except @@ -221,7 +221,7 @@ async def execute( if no_response_expected: return None # type: ignore[return-value] try: - response: ModbusPDU = await asyncio.wait_for( + response: ModbusPdu = await asyncio.wait_for( self.response_future, timeout=self.comm_params.timeout_connect ) self.count_until_disconnect = self.max_until_disconnect @@ -240,7 +240,6 @@ async def execute( f"ERROR: request uses transaction id={request.transaction_id} but received {response.transaction_id}.", request, ) - response.retries = count_retries return response except asyncio.exceptions.TimeoutError: count_retries += 1 @@ -259,7 +258,7 @@ async def execute( raise raise self._no_response(request) - def pdu_send(self, pdu: ModbusPDU, addr: tuple | None = None) -> None: + def pdu_send(self, pdu: ModbusPdu, addr: tuple | None = None) -> None: """Build byte stream and send.""" if not self.is_server: self.request_dev_id = pdu.dev_id @@ -286,11 +285,18 @@ def callback_disconnected(self, exc: Exception | None) -> None: def callback_data(self, data: bytes, addr: tuple | None = None) -> int: """Handle received data.""" self.last_pdu = self.last_addr = None - used_len, pdu = self.framer.handleFrame( - self.trace_packet(False, data), - self.request_dev_id, - self.request_transaction_id, - ) + try: + used_len, pdu = self.framer.handleFrame( + self.trace_packet(False, data), + self.request_dev_id, + self.request_transaction_id, + ) + except ModbusIOException as exc: + if not self.is_server: + raise exc + Log.warning("ERROR: received unknown response, IGNORING") + used_len = len(data) + pdu = PDUexception(0, 0, ExcCodes.ILLEGAL_FUNCTION) if pdu: self.last_pdu = self.trace_pdu(False, pdu) self.last_addr = addr diff --git a/test/client/test_client.py b/test/client/test_client.py index 469743bcc2..3d82c685cb 100755 --- a/test/client/test_client.py +++ b/test/client/test_client.py @@ -8,18 +8,15 @@ import pytest import pymodbus.client as lib_client -import pymodbus.pdu.bit_message as pdu_bit +import pymodbus.pdu.data_message as pdu_data import pymodbus.pdu.diag_message as pdu_diag -import pymodbus.pdu.file_message as pdu_file_msg -import pymodbus.pdu.mei_message as pdu_mei -import pymodbus.pdu.other_message as pdu_other_msg -import pymodbus.pdu.register_message as pdu_reg +import pymodbus.pdu.other_message as pdu_other from examples.helper import generate_ssl, get_certificate from pymodbus import FramerType from pymodbus.client.base import ModbusBaseClient from pymodbus.client.mixin import ModbusClientMixin from pymodbus.exceptions import ConnectionException, ModbusException -from pymodbus.pdu import DecodePDU, ModbusPDU +from pymodbus.pdu import DecodePDU, ModbusPdu from pymodbus.transport import CommParams, CommType @@ -47,78 +44,78 @@ class TestMixin: @pytest.mark.parametrize( ("method", "arg", "pdu_request"), [ - ("read_coils", 1, pdu_bit.ReadCoilsRequest), - ("read_discrete_inputs", 1, pdu_bit.ReadDiscreteInputsRequest), - ("read_holding_registers", 1, pdu_reg.ReadHoldingRegistersRequest), - ("read_input_registers", 1, pdu_reg.ReadInputRegistersRequest), - ("write_coil", 2, pdu_bit.WriteSingleCoilRequest), - ("write_register", 2, pdu_reg.WriteSingleRegisterRequest), - ("read_exception_status", 0, pdu_other_msg.ReadExceptionStatusRequest), - ("diag_query_data", 3, pdu_diag.ReturnQueryDataRequest), + ("read_coils", 1, pdu_data.PDUreadCoils), + ("read_discrete_inputs", 1, pdu_data.PDUreadDiscreteInputs), + ("read_holding_registers", 1, pdu_data.PDUreadHoldingRegisters), + ("read_input_registers", 1, pdu_data.PDUreadInputRegisters), + ("write_coil", 2, pdu_data.PDUwriteSingleCoil), + ("write_register", 2, pdu_data.PDUwriteSingleRegister), + ("read_exception_status", 0, pdu_other.PDUreadExceptionStatus), + ("diag_query_data", 3, pdu_diag.PDUreturnQueryData), ( "diag_restart_communication", 4, - pdu_diag.RestartCommunicationsOptionRequest, + pdu_diag.PDUrestartCommunicationsOption, ), ( "diag_read_diagnostic_register", 0, - pdu_diag.ReturnDiagnosticRegisterRequest, + pdu_diag.PDUreturnDiagnosticRegister, ), ( "diag_change_ascii_input_delimeter", 0, - pdu_diag.ChangeAsciiInputDelimiterRequest, + pdu_diag.PDUchangeAsciiInputDelimiter, ), - ("diag_force_listen_only", 0, pdu_diag.ForceListenOnlyModeRequest), - ("diag_clear_counters", 0, pdu_diag.ClearCountersRequest), - ("diag_read_bus_message_count", 0, pdu_diag.ReturnBusMessageCountRequest), + ("diag_force_listen_only", 0, pdu_diag.PDUforceListenOnlyMode), + ("diag_clear_counters", 0, pdu_diag.PDUclearCounters), + ("diag_read_bus_message_count", 0, pdu_diag.PDUreturnBusMessageCount), ( "diag_read_bus_comm_error_count", 0, - pdu_diag.ReturnBusCommunicationErrorCountRequest, + pdu_diag.PDUreturnBusCommunicationErrorCount, ), ( "diag_read_bus_exception_error_count", 0, - pdu_diag.ReturnBusExceptionErrorCountRequest, + pdu_diag.PDUreturnBusExceptionErrorCount, ), ( "diag_read_device_message_count", 0, - pdu_diag.ReturnDeviceMessageCountRequest, + pdu_diag.PDUreturnDeviceMessageCount, ), ( "diag_read_device_no_response_count", 0, - pdu_diag.ReturnDeviceNoResponseCountRequest, + pdu_diag.PDUreturnDeviceNoResponseCount, ), - ("diag_read_device_nak_count", 0, pdu_diag.ReturnDeviceNAKCountRequest), - ("diag_read_device_busy_count", 0, pdu_diag.ReturnDeviceBusyCountRequest), + ("diag_read_device_nak_count", 0, pdu_diag.PDUreturnDeviceNAKCount), + ("diag_read_device_busy_count", 0, pdu_diag.PDUreturnDeviceBusyCount), ( "diag_read_bus_char_overrun_count", 0, - pdu_diag.ReturnDeviceBusCharacterOverrunCountRequest, + pdu_diag.PDUreturnDeviceBusCharacterOverrunCount, ), - ("diag_read_iop_overrun_count", 0, pdu_diag.ReturnIopOverrunCountRequest), - ("diag_clear_overrun_counter", 0, pdu_diag.ClearOverrunCountRequest), - ("diag_getclear_modbus_response", 0, pdu_diag.GetClearModbusPlusRequest), + ("diag_read_iop_overrun_count", 0, pdu_diag.PDUreturnIopOverrunCount), + ("diag_clear_overrun_counter", 0, pdu_diag.PDUclearOverrunCount), + ("diag_getclear_modbus_response", 0, pdu_diag.PDUgetClearModbusPlus), ( "diag_get_comm_event_counter", 0, - pdu_other_msg.GetCommEventCounterRequest, - ), - ("diag_get_comm_event_log", 0, pdu_other_msg.GetCommEventLogRequest), - ("write_coils", 5, pdu_bit.WriteMultipleCoilsRequest), - ("write_registers", 6, pdu_reg.WriteMultipleRegistersRequest), - ("readwrite_registers", 0, pdu_reg.ReadWriteMultipleRegistersRequest), - ("readwrite_registers", 6, pdu_reg.ReadWriteMultipleRegistersRequest), - ("mask_write_register", 1, pdu_reg.MaskWriteRegisterRequest), - ("report_device_id", 0, pdu_other_msg.ReportDeviceIdRequest), - ("read_file_record", 7, pdu_file_msg.ReadFileRecordRequest), - ("write_file_record", 7, pdu_file_msg.WriteFileRecordRequest), - ("read_fifo_queue", 1, pdu_file_msg.ReadFifoQueueRequest), - ("read_device_information", 0, pdu_mei.ReadDeviceInformationRequest), + pdu_other.PDUgetCommEventCounter, + ), + ("diag_get_comm_event_log", 0, pdu_other.PDUgetCommEventLog), + ("write_coils", 5, pdu_data.PDUwriteMultipleCoils), + ("write_registers", 6, pdu_data.PDUwriteMultipleRegisters), + ("readwrite_registers", 0, pdu_data.PDUreadWriteMultipleRegisters), + ("readwrite_registers", 6, pdu_data.PDUreadWriteMultipleRegisters), + ("mask_write_register", 1, pdu_data.PDUmaskWriteRegister), + ("report_device_id", 0, pdu_other.PDUreportDeviceId), + ("read_file_record", 7, pdu_other.PDUreadFileRecord), + ("write_file_record", 7, pdu_other.PDUwriteFileRecord), + ("read_fifo_queue", 1, pdu_other.PDUreadFifoQueue), + ("read_device_information", 0, pdu_diag.PDUreadDeviceInformation), ], ) def test_client_mixin(self, arglist, method, arg, pdu_request): @@ -136,7 +133,7 @@ def fake_execute(_self, _no_response_expected, request): def test_client_mixin_write_sequence(self): """Write methods must accept any Sequence of values, e.g. a tuple (#2957).""" - requests: list[ModbusPDU] = [] + requests: list[ModbusPdu] = [] def fake_execute(_self, _no_response_expected, request): """Collect PDU requests.""" @@ -475,7 +472,7 @@ def test_client_mixin_convert_datatype_fail(self): def test_client_mixin_execute(self): """Test mixin execute.""" a = ModbusClientMixin() - a.execute(False, cast(ModbusPDU, None)) + a.execute(False, cast(ModbusPdu, None)) class TestClientBase: @@ -583,7 +580,6 @@ async def test_client_instanciate( type_args, clientclass, test_default, - mockPDU, ): """Try to instantiate clients.""" cur_args = arg_list[type_args] @@ -602,7 +598,7 @@ async def test_client_instanciate( # a unsuccessful connect client.connect = lambda: False client.transport = None - pdu = mockPDU() + pdu = pdu_data.PDUreadCoils(True, 1, address=1, count=1) with pytest.raises(ConnectionException): client.execute(False, pdu) @@ -620,7 +616,7 @@ async def test_client_modbusbaseclient(self): None, None, ) - client.register(pdu_bit.ReadCoilsResponse) + client.register(pdu_data.PDUreadCoils) assert str(client) client.set_max_no_responses(110) client.close() @@ -797,15 +793,14 @@ def test_client_tls_connect2(self): def test_tcp_client_register(self): """Test tcp client.""" - class CustomRequest(ModbusPDU): # pylint: disable=too-few-public-methods + class CustomRequest(ModbusPdu): # pylint: disable=too-few-public-methods """Dummy custom request.""" function_code = 79 client = lib_client.ModbusTcpClient("127.0.0.1") - client.framer = mock.Mock() client.register(CustomRequest) - client.framer.decoder.register.assert_called_once_with(CustomRequest) + assert CustomRequest.function_code in DecodePDU(True).pdu_table def test_sync_block(self): """Test sync block.""" diff --git a/test/conftest.py b/test/conftest.py index 9996a2fa77..945161eb82 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -11,7 +11,6 @@ import pytest_asyncio from pymodbus.datastore import ModbusDeviceContext, ModbusServerContext -from pymodbus.pdu import ModbusPDU from pymodbus.server import ServerAsyncStop from pymodbus.transport import NULLMODEM_HOST, CommParams, CommType from pymodbus.transport.transport import NullModem @@ -329,28 +328,3 @@ def setblocking(self, _flag): return None return DummySocket - - -@pytest.fixture(name="mockPDU") -def define_dummyPDU(): - """Define mockSocket class.""" - - class DummyPDU(ModbusPDU): # pragma: no cover - """Custom request.""" - - function_code = 0x70 - - @classmethod - def x_calculateRtuFrameSize(cls, data: bytes) -> int: - """Calculate the size of a PDU.""" - return 5 - - def x_encode(self) -> bytes: - """Encode the message.""" - return self.function_code.to_bytes(1, "big") + b"123" - - def x_decode(self, data): - """Decode.""" - _ = data - - return DummyPDU diff --git a/test/examples/test_examples.py b/test/examples/test_examples.py index 8e545d511c..8dbf159fa1 100755 --- a/test/examples/test_examples.py +++ b/test/examples/test_examples.py @@ -31,7 +31,7 @@ from examples.simulator import run_simulator as run_simulator3 from pymodbus.client import ModbusTcpClient, ModbusUdpClient from pymodbus.exceptions import ModbusException -from pymodbus.pdu import ExceptionResponse +from pymodbus.pdu import PDUexception from pymodbus.server import ServerAsyncStop, ServerStop @@ -143,7 +143,9 @@ async def test_client_async_calls_errors(self, mock_server): with pytest.raises(ModbusException): await run_async_client(client, modbus_calls=async_template_call) client.close() - client.read_coils = mock.AsyncMock(return_value=ExceptionResponse(0x05, 0x10)) # type: ignore[method-assign] + client.read_coils = mock.AsyncMock( # type: ignore[method-assign] + return_value=PDUexception(0, 0x05, 0x10) + ) # type: ignore[method-assign] with pytest.raises(ModbusException): await run_async_client(client, modbus_calls=async_template_call) client.close() @@ -155,7 +157,9 @@ async def test_client_calls_errors(self, mock_server): with pytest.raises(ModbusException): await run_async_client(client, modbus_calls=async_template_call) client.close() - client.read_coils = mock.Mock(return_value=ExceptionResponse(0x05, 0x10)) # type: ignore[method-assign] + client.read_coils = mock.Mock( # type: ignore[method-assign] + return_value=PDUexception(0, 0x05, 0x10) + ) # type: ignore[method-assign] with pytest.raises(ModbusException): await run_async_client(client, modbus_calls=template_call) client.close() diff --git a/test/framer/conftest.py b/test/framer/conftest.py deleted file mode 100644 index d57c96dde3..0000000000 --- a/test/framer/conftest.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Configure pytest.""" - -from __future__ import annotations - -import pytest - -from pymodbus.framer import FRAMER_NAME_TO_CLASS, FramerType -from pymodbus.pdu import DecodePDU - - -@pytest.fixture(name="entry") -def prepare_entry(): - """Return framer_type.""" - return FramerType.RTU - - -@pytest.fixture(name="is_server") -def prepare_is_server(): - """Return client/server.""" - return False - - -@pytest.fixture(name="test_framer") -async def prepare_test_framer(entry, is_server): - """Return framer object.""" - return FRAMER_NAME_TO_CLASS[entry](DecodePDU(is_server)) diff --git a/test/framer/generator.py b/test/framer/generator.py deleted file mode 100755 index c28f8f0e0a..0000000000 --- a/test/framer/generator.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python3 -"""Build framer encode responses.""" - -from pymodbus.constants import ExcCodes -from pymodbus.framer import ( - FramerAscii, - FramerRTU, - FramerSocket, - FramerTLS, -) -from pymodbus.pdu import DecodePDU, ExceptionResponse -from pymodbus.pdu.register_message import ( - ReadHoldingRegistersRequest, - ReadHoldingRegistersResponse, -) - - -def set_calls(): - """Define calls.""" - for framer in (FramerAscii, FramerRTU, FramerSocket, FramerTLS): - print(f"framer --> {framer}") - for dev_id in (0, 17, 255): - print(f" dev_id --> {dev_id}") - for tid in (0, 3077): - print(f" tid --> {tid}") - client = framer(DecodePDU(False)) - request = ReadHoldingRegistersRequest( - address=124, count=2, dev_id=dev_id - ) - request.transaction_id = tid - result = client.buildFrame(request) - print(f" request --> {result}") - print(f" request --> {result.hex()}") - server = framer(DecodePDU(True)) - response = ReadHoldingRegistersResponse(registers=[141, 142]) - response.dev_id = dev_id - response.transaction_id = tid - result = server.buildFrame(response) - print(f" response --> {result}") - print(f" response --> {result.hex()}") - exception = ExceptionResponse( - request.function_code, ExcCodes.ILLEGAL_ADDRESS - ) - exception.transaction_id = tid - exception.dev_id = dev_id - result = server.buildFrame(exception) - print(f" exception --> {result}") - print(f" exception --> {result.hex()}") - - -set_calls() diff --git a/test/framer/test_extras.py b/test/framer/test_extras.py index 3671b2e5d3..952736e689 100755 --- a/test/framer/test_extras.py +++ b/test/framer/test_extras.py @@ -11,8 +11,7 @@ FramerSocket, FramerTLS, ) -from pymodbus.pdu import DecodePDU -from pymodbus.pdu.device import ModbusControlBlock +from pymodbus.pdu import DecodePDU, ModbusControlBlock TEST_MESSAGE = b"\x7b\x01\x03\x00\x00\x00\x05\x85\xc9\x7d" @@ -41,7 +40,7 @@ def test_tcp_framer_transaction_half2(self): used_len, pdu = self._tcp.handleFrame(msg1 + msg2, 0, 0) assert pdu assert used_len == len(msg1) + len(msg2) - assert pdu.function_code.to_bytes(1, "big") + self.decoder.encode(pdu) == msg2 + assert self.decoder.encode(pdu) == b"\xff" + msg2 def test_tcp_framer_transaction_half3(self): """Test a half completed tcp frame transaction.""" @@ -53,10 +52,7 @@ def test_tcp_framer_transaction_half3(self): used_len, pdu = self._tcp.handleFrame(msg1 + msg2, 0, 0) assert pdu assert used_len == len(msg1) + len(msg2) - assert ( - pdu.function_code.to_bytes(1, "big") + self.decoder.encode(pdu) - == msg1[7:] + msg2 - ) + assert self.decoder.encode(pdu) == msg1[6:] + msg2 def test_tcp_framer_transaction_short(self): """Test that we can get back on track after an invalid message.""" @@ -68,9 +64,7 @@ def test_tcp_framer_transaction_short(self): used_len, pdu = self._tcp.handleFrame(msg1 + msg2, 0, 0) assert pdu assert used_len == len(msg1) + len(msg2) - assert ( - pdu.function_code.to_bytes(1, "big") + self.decoder.encode(pdu) == msg2[7:] - ) + assert self.decoder.encode(pdu) == msg2[6:] def test_tcp_framer_transaction_wrong_id(self): """Test a half completed tcp frame transaction.""" @@ -91,7 +85,7 @@ def test_tcp_framer_transaction_wrong_fc(self): msg = b"\x00\x01\x00\x00\x00\x06\xff\x70\x01\x02\x00\x08" with pytest.raises(ModbusIOException) as exc_info: self._tcp.handleFrame(msg, 0, 0) - assert exc_info.value.fcode == 0xF0 + assert exc_info.value.fcode == 0x80 def test_tls_incoming_packet(self): """Framer tls incoming packet.""" @@ -120,7 +114,8 @@ def test_rtu_calculate(self): """Test rtu process incoming packets.""" msg = b"\x00\x01\x00\x00\x00\x01\xfc\x1b" with patch( - "pymodbus.pdu.ReadCoilsRequest.x_calculateRtuFrameSize", return_value=0 + "pymodbus.pdu.data_message.PDUreadCoils.calculatePduSize", + return_value=0, ): used_len, pdu = self._rtu.handleFrame(msg, 0, 0) assert not used_len @@ -175,8 +170,8 @@ def test_ascii_framer_skip_wrong_dev_id_then_decode(self): hard-coding bytes that would silently rot if the LRC algorithm ever changed. """ - wrong = self._ascii.encode(b"\x02\x00\x01\x00\x02", 0x10, 0) # dev_id 0x10 - right = self._ascii.encode(b"\x02\x00\x03\x00\x04", 0xFF, 0) # dev_id 0xff + wrong = self._ascii.encode(b"\x10\x02\x00\x01\x00\x02", 0) # dev_id 0x10 + right = self._ascii.encode(b"\xff\x02\x00\x03\x00\x04", 0) # dev_id 0xff used_len, pdu = self._ascii.handleFrame(wrong + right, 0xFF, 0) assert pdu is not None assert pdu.dev_id == 0xFF diff --git a/test/framer/test_framer.py b/test/framer/test_framer.py index 9e82fed764..a950e7b357 100644 --- a/test/framer/test_framer.py +++ b/test/framer/test_framer.py @@ -6,6 +6,7 @@ from pymodbus.exceptions import ModbusIOException from pymodbus.framer import ( + FRAMER_NAME_TO_CLASS, FramerAscii, FramerBase, FramerRTU, @@ -13,36 +14,48 @@ FramerTLS, FramerType, ) -from pymodbus.pdu import DecodePDU -from pymodbus.pdu.bit_message import WriteMultipleCoilsRequest -from pymodbus.pdu.device import ModbusControlBlock -from pymodbus.pdu.register_message import ( - ReadWriteMultipleRegistersRequest, - WriteMultipleRegistersRequest, +from pymodbus.pdu import DecodePDU, ModbusControlBlock +from pymodbus.pdu.data_message import ( + PDUreadInputRegisters, + PDUreadWriteMultipleRegisters, + PDUwriteMultipleCoils, + PDUwriteMultipleRegisters, ) -from test.framer.generator import set_calls + + +@pytest.fixture(name="entry") +def prepare_entry(): + """Return framer_type.""" + return FramerType.RTU + + +@pytest.fixture(name="is_server") +def prepare_is_server(): + """Return client/server.""" + return False + + +@pytest.fixture(name="test_framer") +async def prepare_test_framer(entry, is_server): + """Return framer object.""" + return FRAMER_NAME_TO_CLASS[entry](DecodePDU(is_server)) class TestFramer: """Test module.""" - def test_setup(self, entry, is_server): - """Test setup.""" - assert entry == FramerType.RTU - assert not is_server - set_calls() - - def test_base(self): + def test_frame_0(self): """Test FramerBase.""" - framer = FramerBase(DecodePDU(False)) - framer.decode(b"") - framer.encode(b"", 0, 0) - framer.encode(b"", 2, 0) + base = FramerBase(DecodePDU(True)) + base.decode(b"") + base.encode(b"", 0) + @pytest.mark.parametrize(("is_server"), [True, False]) @pytest.mark.parametrize(("entry"), list(FramerType)) - async def test_framer_init(self, test_framer): - """Test framer type.""" - assert test_framer + def test_frame_1(self, test_framer): + """Test FramerBase.""" + test_framer.decode(b"") + test_framer.encode(b"", 0) @pytest.mark.parametrize( ("func", "test_compare", "expect"), @@ -55,18 +68,18 @@ async def test_framer_init(self, test_framer): (FramerRTU.compute_CRC, None, 0xE2DB), ], ) - def test_LRC_CRC(self, func, test_compare, expect): + def test_frame_2(self, func, test_compare, expect): """Test check_LRC.""" data = b"\x12\x34\x23\x45\x34\x56\x45\x67" assert expect == func(data, test_compare) if test_compare else func(data) - def test_roundtrip_LRC(self): + def test_frame_3(self): """Test combined compute/check LRC.""" data = b"\x12\x34\x23\x45\x34\x56\x45\x67" assert FramerAscii.compute_LRC(data) == 0x1C assert FramerAscii.check_LRC(data, 0x1C) - def test_crc16_table(self): + def test_frame_4(self): """Test the crc16 table is prefilled.""" assert len(FramerRTU.crc16_table) == 256 assert isinstance(FramerRTU.crc16_table[0], int) @@ -88,31 +101,33 @@ def test_next_transaction_id(self, framer, tids): for previous, expected in tids: assert test_framer.next_transaction_id(previous) == expected - def test_roundtrip_CRC(self): + def test_frame_5(self): """Test combined compute/check CRC.""" data = b"\x12\x34\x23\x45\x34\x56\x45\x67" assert FramerRTU.compute_CRC(data) == 0xE2DB assert FramerRTU.check_CRC(data, 0xE2DB) - async def test_handleFrame2(self): + async def test_frame_6(self): """Test handleFrame.""" test_framer = FramerRTU(DecodePDU(True)) - msg = b"\xfe\x04\x00\x03\x00\x01\xd5\xc5\x00" + msg = b"\xfe\x04\x00\x03\x00\x01\xd5\xc5" used_len, pdu = test_framer.handleFrame(msg, 0, 0) assert used_len == len(msg) - assert pdu + assert isinstance(pdu, PDUreadInputRegisters) - def test_ascii_framer_uses_configured_delimiter_on_encode(self): + def test_frame_7(self): """Test ASCII framer encode uses the configured delimiter.""" control = ModbusControlBlock() control.Delimiter = b"=" try: framer = FramerAscii(DecodePDU(False)) - assert framer.encode(b"\x03\x00\x7c\x00\x02", 0, 0) == b":0003007C00027F\r=" + assert ( + framer.encode(b"\x00\x03\x00\x7c\x00\x02", 0) == b":0003007C00027F\r=" + ) finally: control.Delimiter = b"\n" - def test_ascii_framer_uses_configured_delimiter_on_decode(self): + def test_frame_8(self): """Test ASCII framer decode uses the configured delimiter.""" control = ModbusControlBlock() control.Delimiter = b"=" @@ -122,7 +137,7 @@ def test_ascii_framer_uses_configured_delimiter_on_decode(self): assert used_len == len(b":0003007C00027F\r=") assert dev_id == 0 assert tr_id == 0 - assert payload == b"\x03\x00\x7c\x00\x02" + assert payload == b"\x00\x03\x00\x7c\x00\x02" finally: control.Delimiter = b"\n" @@ -285,7 +300,7 @@ def test_encode_type( return frame_obj = frame(DecodePDU(False)) expected = frame_expected[inx1 + inx2 + inx3] - encoded_data = frame_obj.encode(data, dev_id, tr_id) + encoded_data = frame_obj.encode(dev_id.to_bytes(1, "big") + data, tr_id) assert encoded_data == expected @pytest.mark.parametrize( @@ -297,7 +312,7 @@ def test_encode_type( b":0003007C00027F\r\n", 0, 0, - b"\x03\x00\x7c\x00\x02", + b"\x00\x03\x00\x7c\x00\x02", ), # Request ( FramerType.ASCII, @@ -305,7 +320,7 @@ def test_encode_type( b":000304008D008EDE\r\n", 0, 0, - b"\x03\x04\x00\x8d\x00\x8e", + b"\x00\x03\x04\x00\x8d\x00\x8e", ), # Response ( FramerType.ASCII, @@ -313,7 +328,7 @@ def test_encode_type( b":0083027B\r\n", 0, 0, - b"\x83\x02", + b"\x00\x83\x02", ), # Exception ( FramerType.ASCII, @@ -321,7 +336,7 @@ def test_encode_type( b":1103007C00026E\r\n", 17, 0, - b"\x03\x00\x7c\x00\x02", + b"\x11\x03\x00\x7c\x00\x02", ), # Request ( FramerType.ASCII, @@ -329,7 +344,7 @@ def test_encode_type( b":110304008D008ECD\r\n", 17, 0, - b"\x03\x04\x00\x8d\x00\x8e", + b"\x11\x03\x04\x00\x8d\x00\x8e", ), # Response ( FramerType.ASCII, @@ -337,7 +352,7 @@ def test_encode_type( b":1183026A\r\n", 17, 0, - b"\x83\x02", + b"\x11\x83\x02", ), # Exception ( FramerType.ASCII, @@ -345,7 +360,7 @@ def test_encode_type( b":FF03007C000280\r\n", 255, 0, - b"\x03\x00\x7c\x00\x02", + b"\xff\x03\x00\x7c\x00\x02", ), # Request ( FramerType.ASCII, @@ -353,7 +368,7 @@ def test_encode_type( b":FF0304008D008EDF\r\n", 255, 0, - b"\x03\x04\x00\x8d\x00\x8e", + b"\xff\x03\x04\x00\x8d\x00\x8e", ), # Response ( FramerType.ASCII, @@ -361,7 +376,7 @@ def test_encode_type( b":FF83027C\r\n", 255, 0, - b"\x83\x02", + b"\xff\x83\x02", ), # Exception ( FramerType.RTU, @@ -441,7 +456,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x06\x00\x03\x00\x7c\x00\x02", 0, 0, - b"\x03\x00\x7c\x00\x02", + b"\x00\x03\x00\x7c\x00\x02", ), # Request ( FramerType.SOCKET, @@ -449,7 +464,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x07\x00\x03\x04\x00\x8d\x00\x8e", 0, 0, - b"\x03\x04\x00\x8d\x00\x8e", + b"\x00\x03\x04\x00\x8d\x00\x8e", ), # Response ( FramerType.SOCKET, @@ -457,7 +472,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x03\x00\x83\x02", 0, 0, - b"\x83\x02", + b"\x00\x83\x02", ), # Exception ( FramerType.SOCKET, @@ -465,7 +480,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x06\x11\x03\x00\x7c\x00\x02", 17, 0, - b"\x03\x00\x7c\x00\x02", + b"\x11\x03\x00\x7c\x00\x02", ), # Request ( FramerType.SOCKET, @@ -473,7 +488,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x07\x11\x03\x04\x00\x8d\x00\x8e", 17, 0, - b"\x03\x04\x00\x8d\x00\x8e", + b"\x11\x03\x04\x00\x8d\x00\x8e", ), # Response ( FramerType.SOCKET, @@ -481,7 +496,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x03\x11\x83\x02", 17, 0, - b"\x83\x02", + b"\x11\x83\x02", ), # Exception ( FramerType.SOCKET, @@ -489,7 +504,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x06\xff\x03\x00\x7c\x00\x02", 255, 0, - b"\x03\x00\x7c\x00\x02", + b"\xff\x03\x00\x7c\x00\x02", ), # Request ( FramerType.SOCKET, @@ -497,7 +512,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x07\xff\x03\x04\x00\x8d\x00\x8e", 255, 0, - b"\x03\x04\x00\x8d\x00\x8e", + b"\xff\x03\x04\x00\x8d\x00\x8e", ), # Response ( FramerType.SOCKET, @@ -505,7 +520,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x03\xff\x83\x02", 255, 0, - b"\x83\x02", + b"\xff\x83\x02", ), # Exception ( FramerType.SOCKET, @@ -513,7 +528,7 @@ def test_encode_type( b"\x0c\x05\x00\x00\x00\x06\x00\x03\x00\x7c\x00\x02", 0, 3077, - b"\x03\x00\x7c\x00\x02", + b"\x00\x03\x00\x7c\x00\x02", ), # Request ( FramerType.SOCKET, @@ -521,7 +536,7 @@ def test_encode_type( b"\x0c\x05\x00\x00\x00\x07\x00\x03\x04\x00\x8d\x00\x8e", 0, 3077, - b"\x03\x04\x00\x8d\x00\x8e", + b"\x00\x03\x04\x00\x8d\x00\x8e", ), # Response ( FramerType.SOCKET, @@ -529,7 +544,7 @@ def test_encode_type( b"\x0c\x05\x00\x00\x00\x03\x00\x83\x02", 0, 3077, - b"\x83\x02", + b"\x00\x83\x02", ), # Exception ( FramerType.SOCKET, @@ -537,7 +552,7 @@ def test_encode_type( b"\x0c\x05\x00\x00\x00\x06\x11\x03\x00\x7c\x00\x02", 17, 3077, - b"\x03\x00\x7c\x00\x02", + b"\x11\x03\x00\x7c\x00\x02", ), # Request ( FramerType.SOCKET, @@ -545,7 +560,7 @@ def test_encode_type( b"\x0c\x05\x00\x00\x00\x07\x11\x03\x04\x00\x8d\x00\x8e", 17, 3077, - b"\x03\x04\x00\x8d\x00\x8e", + b"\x11\x03\x04\x00\x8d\x00\x8e", ), # Response ( FramerType.SOCKET, @@ -553,7 +568,7 @@ def test_encode_type( b"\x0c\x05\x00\x00\x00\x03\x11\x83\x02", 17, 3077, - b"\x83\x02", + b"\x11\x83\x02", ), # Exception ( FramerType.SOCKET, @@ -561,7 +576,7 @@ def test_encode_type( b"\x0c\x05\x00\x00\x00\x06\xff\x03\x00\x7c\x00\x02", 255, 3077, - b"\x03\x00\x7c\x00\x02", + b"\xff\x03\x00\x7c\x00\x02", ), # Request ( FramerType.SOCKET, @@ -569,7 +584,7 @@ def test_encode_type( b"\x0c\x05\x00\x00\x00\x07\xff\x03\x04\x00\x8d\x00\x8e", 255, 3077, - b"\x03\x04\x00\x8d\x00\x8e", + b"\xff\x03\x04\x00\x8d\x00\x8e", ), # Response ( FramerType.SOCKET, @@ -577,7 +592,7 @@ def test_encode_type( b"\x0c\x05\x00\x00\x00\x03\xff\x83\x02", 255, 3077, - b"\x83\x02", + b"\xff\x83\x02", ), # Exception ( FramerType.TLS, @@ -585,7 +600,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x06\x00\x03\x00\x7c\x00\x02", 0, 0, - b"\x03\x00\x7c\x00\x02", + b"\x00\x03\x00\x7c\x00\x02", ), # Request ( FramerType.TLS, @@ -593,7 +608,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x07\x00\x03\x04\x00\x8d\x00\x8e", 0, 0, - b"\x03\x04\x00\x8d\x00\x8e", + b"\x00\x03\x04\x00\x8d\x00\x8e", ), # Response ( FramerType.TLS, @@ -601,7 +616,7 @@ def test_encode_type( b"\x00\x00\x00\x00\x00\x03\x00\x83\x02", 0, 0, - b"\x83\x02", + b"\x00\x83\x02", ), # Exception ], ) @@ -663,22 +678,22 @@ async def test_decode_type( FramerType.ASCII, b":0003007C00027F\r\n:0003007C00027F\r\n", [ # double good crc - (17, b"\x03\x00\x7c\x00\x02"), - (17, b"\x03\x00\x7c\x00\x02"), + (17, b"\x00\x03\x00\x7c\x00\x02"), + (17, b"\x00\x03\x00\x7c\x00\x02"), ], ), ( FramerType.ASCII, b":0003007C00017F\r\n:0003007C00027F\r\n", [ # bad crc + good CRC - (34, b"\x03\x00\x7c\x00\x02"), + (34, b"\x00\x03\x00\x7c\x00\x02"), ], ), ( FramerType.ASCII, b"abc:0003007C00027F\r\n", [ # garble in front - (20, b"\x03\x00\x7c\x00\x02"), + (20, b"\x00\x03\x00\x7c\x00\x02"), ], ), ( @@ -699,7 +714,7 @@ async def test_decode_type( FramerType.ASCII, b":0003007C00027F\r\nabc", [ # good crc, garble after - (17, b"\x03\x00\x7c\x00\x02"), + (17, b"\x00\x03\x00\x7c\x00\x02"), ], ), ( @@ -713,29 +728,29 @@ async def test_decode_type( FramerType.ASCII, b":0003G07C00027F\r\n:0003007C00027F\r\n", [ # non hex frame + good frame - (34, b"\x03\x00\x7c\x00\x02"), + (34, b"\x00\x03\x00\x7c\x00\x02"), ], ), ( FramerType.ASCII, b":0003007C:0003007C00027F\r\n", [ # truncated frame restarted by a new start + good frame - (26, b"\x03\x00\x7c\x00\x02"), + (26, b"\x00\x03\x00\x7c\x00\x02"), ], ), ( FramerType.SOCKET, b"\x00\x00\x00\x00\x00\x06\x00\x03\x00\x7c\x00\x02\x00\x00\x00\x00\x00\x06\x00\x03\x00\x7c\x00\x02", [ # double good crc - (12, b"\x03\x00\x7c\x00\x02"), - (12, b"\x03\x00\x7c\x00\x02"), + (12, b"\x00\x03\x00\x7c\x00\x02"), + (12, b"\x00\x03\x00\x7c\x00\x02"), ], ), ( FramerType.SOCKET, b"\x0c\x05\x00\x00\x00\x02\xff\x83\x02", [ # Exception - (9, b"\x83\x02"), + (9, b"\xff\x83\x02"), ], ), ( @@ -779,71 +794,76 @@ async def test_decode_complicated(self, test_framer, data, exp): @pytest.mark.parametrize( ("entry", "data", "dev_id", "res_msg"), [ - (FramerType.ASCII, b"\x01\x05\x04\x00\x17", 1, b":010105040017DF\r\n"), - (FramerType.ASCII, b"\x03\x07\x06\x00\x73", 2, b":0203070600737D\r\n"), - (FramerType.ASCII, b"\x08\x00\x01", 3, b":03080001F7\r\n"), - (FramerType.ASCII, b"\x84\x01", 2, b":02840179\r\n"), - (FramerType.RTU, b"\x01\x01\x00", 2, b"\x02\x01\x01\x00\x51\xcc"), + (FramerType.ASCII, b"\x01\x01\x05\x04\x00\x17", 1, b":010105040017DF\r\n"), + (FramerType.ASCII, b"\x02\x03\x07\x06\x00\x73", 2, b":0203070600737D\r\n"), + (FramerType.ASCII, b"\x03\x08\x00\x01", 3, b":03080001F7\r\n"), + (FramerType.ASCII, b"\x02\x84\x01", 2, b":02840179\r\n"), + (FramerType.RTU, b"\x02\x01\x01\x00", 2, b"\x02\x01\x01\x00\x51\xcc"), ( FramerType.RTU, - b"\x03\x06\xae\x41\x56\x52\x43\x40", + b"\x11\x03\x06\xae\x41\x56\x52\x43\x40", 17, b"\x11\x03\x06\xae\x41\x56\x52\x43\x40\x49\xad", ), ( FramerType.RTU, - b"\x01\x03\x01\x00\x0a", + b"\x01\x01\x03\x01\x00\x0a", 1, b"\x01\x01\x03\x01\x00\x0a\xed\x89", ), ( FramerType.SOCKET, - b"\x01\x05\x04\x00\x17", + b"\x1f\x01\x05\x04\x00\x17", 31, b"\x00\x05\x00\x00\x00\x06\x07\x01\x05\x04\x00\x17", ), ( FramerType.SOCKET, - b"\x03\x07\x06\x00\x73", + b"\x20\x03\x07\x06\x00\x73", 32, b"\x00\x09\x00\x00\x00\x06\x02\x03\x07\x06\x00\x73", ), ( FramerType.SOCKET, - b"\x08\x00\x01", + b"\x21\x08\x00\x01", 33, b"\x00\x06\x00\x00\x00\x04\x03\x08\x00\x01", ), ( FramerType.SOCKET, - b"\x84\x01", + b"\x22\x84\x01", 34, b"\x00\x08\x00\x00\x00\x03\x04\x84\x01", ), ( FramerType.TLS, - b"\x01\x05\x04\x00\x17", + b"\x1f\x01\x05\x04\x00\x17", 31, b"\x00\x05\x00\x00\x00\x06\x07\x01\x05\x04\x00\x17", ), ( FramerType.TLS, - b"\x03\x07\x06\x00\x73", + b"\x20\x03\x07\x06\x00\x73", 32, b"\x00\x09\x00\x00\x00\x06\x02\x03\x07\x06\x00\x73", ), ( FramerType.TLS, - b"\x08\x00\x01", + b"\x21\x08\x00\x01", 33, b"\x00\x06\x00\x00\x00\x04\x03\x08\x00\x01", ), - (FramerType.TLS, b"\x84\x01", 34, b"\x00\x08\x00\x00\x00\x03\x04\x84\x01"), + ( + FramerType.TLS, + b"\x22\x84\x01", + 34, + b"\x00\x08\x00\x00\x00\x03\x04\x84\x01", + ), ], ) def test_roundtrip(self, test_framer, data, dev_id, res_msg): """Test encode.""" - msg = test_framer.encode(data, dev_id, 0) + msg = test_framer.encode(data, 0) res_len, res_dev_id, _, res_data = test_framer.decode(msg) assert data == res_data assert dev_id == res_dev_id @@ -893,14 +913,15 @@ def test_handleFrame2(self, test_framer, msg): @pytest.mark.parametrize( "request_pdu", [ - WriteMultipleCoilsRequest(address=1, bits=[True, False, True], dev_id=1), - WriteMultipleRegistersRequest(address=1, registers=[10, 11], dev_id=1), - ReadWriteMultipleRegistersRequest( - read_address=1, - read_count=2, + PDUwriteMultipleCoils(True, 1, address=1, bits=[True, False, True]), + PDUwriteMultipleRegisters(True, 1, address=1, registers=[10, 11]), + PDUreadWriteMultipleRegisters( + True, + 1, + address=1, + count=2, write_address=3, - write_registers=[4, 5], - dev_id=1, + registers=[4, 5], ), ], ) @@ -958,35 +979,9 @@ def test_handleFrame_roundtrip(self, entry, test_framer, msg, dev_id, tid, half) assert result assert result.dev_id == dev_id assert result.transaction_id == tid - expected = test_framer.encode( - result.function_code.to_bytes(1, "big") + DecodePDU(False).encode(result), - dev_id, - 1, - ) + expected = test_framer.encode(DecodePDU(False).encode(result), 1) assert msg == expected - @pytest.mark.parametrize(("is_server"), [True]) - @pytest.mark.parametrize( - ("entry", "msg"), - [ - (FramerType.SOCKET, b"\x00\x01\x00\x00\x00\x02\xff\x01"), - (FramerType.TLS, b"\x00\x01\x00\x00\x00\x02\xff\x01"), - (FramerType.RTU, b"\xff\x01\x81\x80"), - (FramerType.ASCII, b":FF0100\r\n"), - ], - ) - def test_framer_encode(self, test_framer, msg, mockPDU): - """Test a tcp frame transaction.""" - with mock.patch.object(mockPDU, "x_encode") as mock_encode: - message = mockPDU() - message.transaction_id = 0x0001 - message.dev_id = 0xFF - message.function_code = 0x01 - mock_encode.return_value = b"" - - actual = test_framer.buildFrame(message) - assert msg == actual - def test_bad_file_record_request_for_framer_socket(self): """Test a bad file record request keeps the ids the server reply needs.""" framer = FramerSocket(DecodePDU(True)) diff --git a/test/pdu/conftest.py b/test/pdu/conftest.py new file mode 100644 index 0000000000..5099a216a9 --- /dev/null +++ b/test/pdu/conftest.py @@ -0,0 +1,547 @@ +"""Configure pytest.""" + +import pytest + +import pymodbus.pdu.data_message as pdu_data +import pymodbus.pdu.diag_message as pdu_diag +import pymodbus.pdu.other_message as pdu_other + + +@pytest.fixture( + params=[ + ( # 0 + pdu_data.PDUreadCoils, + "read_coils", + ( + {"address": 117, "count": 3}, + b"\x01\x01\x00\x75\x00\x03", + {"bits": [True, True] + [False] * 6}, + b"\x01\x01\x01\x03", + ), + ), + ( # 1 + pdu_data.PDUwriteSingleCoil, + "write_coil", + ( + {"address": 117, "bits": [True]}, + b"\x01\x05\x00\x75\xff\x00", + {"address": 117, "bits": [True]}, + b"\x01\x05\x00\x75\xff\x00", + ), + ), + ( # 2 + pdu_data.PDUwriteMultipleCoils, + "write_coils", + ( + {"address": 117, "bits": [True, False, True]}, + b"\x01\x0f\x00\x75\x00\x03\x01\x05", + {"address": 117, "count": 3}, + b"\x01\x0f\x00\x75\x00\x03", + ), + ), + ( # 3 + pdu_data.PDUreadDiscreteInputs, + "read_discrete_inputs", + ( + {"address": 117, "count": 3}, + b"\x01\x02\x00\x75\x00\x03", + {"bits": [True, True]}, + b"\x01\x02\x01\x03", + ), + ), + ( # 4 + pdu_data.PDUreadHoldingRegisters, + "read_holding_registers", + ( + {"address": 117, "count": 3}, + b"\x01\x03\x00\x75\x00\x03", + {"registers": [3, 17]}, + b"\x01\x03\x04\x00\x03\x00\x11", + ), + ), + ( # 5 + pdu_data.PDUreadInputRegisters, + "read_input_registers", + ( + {"address": 117, "count": 3}, + b"\x01\x04\x00\x75\x00\x03", + {"registers": [3, 17]}, + b"\x01\x04\x04\x00\x03\x00\x11", + ), + ), + ( # 6 + pdu_data.PDUwriteSingleRegister, + "write_register", + ( + {"address": 117, "registers": [112]}, + b"\x01\x06\x00\x75\x00\x70", + {"address": 117, "registers": [112]}, + b"\x01\x06\x00\x75\x00\x70", + ), + ), + ( # 7 + pdu_data.PDUwriteMultipleRegisters, + "write_registers", + ( + {"address": 117, "registers": [111, 121, 131]}, + b"\x01\x10\x00\x75\x00\x03\x06\x00\x6f\x00\x79\x00\x83", + {"address": 117, "count": 3}, + b"\x01\x10\x00\x75\x00\x03", + ), + ), + ( # 8 + pdu_data.PDUreadWriteMultipleRegisters, + "readwrite_registers", + ( + { + "address": 17, + "count": 2, + "write_address": 25, + "registers": [111, 112], + }, + b"\x01\x17\x00\x11\x00\x02\x00\x19\x00\x02\x04\x00\x6f\x00\x70", + {"registers": [111, 112]}, + b"\x01\x17\x04\x00\x6f\x00\x70", + ), + ), + ( # 9 + pdu_data.PDUmaskWriteRegister, + "mask_write_register", + ( + {"address": 0x0104, "and_mask": 0xE1D2, "or_mask": 0x1234}, + b"\x01\x16\x01\x04\xe1\xd2\x12\x34", + {"address": 0x0104, "and_mask": 0xE1D2, "or_mask": 0x1234}, + b"\x01\x16\x01\x04\xe1\xd2\x12\x34", + ), + ), + ( # 10 + pdu_other.PDUreadFileRecord, + "read_file_record", + ( + {"records": [pdu_other.FileRecord(), pdu_other.FileRecord()]}, + b"\x01\x14\x0e\x06\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00", + {"records": [pdu_other.FileRecord(), pdu_other.FileRecord()]}, + b"\x01\x14\x04\x01\x06\x01\x06", + ), + ), + ( # 11 + pdu_other.PDUwriteFileRecord, + "write_file_record", + ( + {"records": [pdu_other.FileRecord(), pdu_other.FileRecord()]}, + b"\x01\x15\x0e\x06\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00", + {"records": [pdu_other.FileRecord(), pdu_other.FileRecord()]}, + b"\x01\x15\x0e\x06\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00", + ), + ), + ( # 12 + pdu_other.PDUreadFifoQueue, + "read_fifo_queue", + ( + {"address": 117}, + b"\x01\x18\x00\x75", + {"values": [123, 456]}, + b"\x01\x18\x00\x06\x00\x02\x00\x7b\x01\xc8", + ), + ), + ( # 13 + pdu_diag.PDUreadDeviceInformation, + "read_device_information", + ( + {"read_code": 0x01, "object_id": 0x02}, + b"\x01\x2b\x0e\x01\x02", + {"read_code": 0x01}, + b"\x01\x2b\x0e\x01\x83\x00\x00\x00", + ), + ), + ( # 14 + pdu_other.PDUreadExceptionStatus, + "read_exception_status", + ({}, b"\x01\x07", {"status": 0x23}, b"\x01\x07\x23"), + ), + ( # 15 + pdu_other.PDUgetCommEventCounter, + "diag_get_comm_event_counter", + ({}, b"\x01\x0b", {"status": 1, "count": 1}, b"\x01\x0b\x00\x00\x00\x01"), + ), + ( # 16 + pdu_other.PDUgetCommEventLog, + "diag_get_comm_event_log", + ( + {}, + b"\x01\x0c", + { + "status": True, + "message_count": 12, + "event_count": 7, + "events": [12, 14], + }, + b"\x01\x0c\x08\x00\x00\x00\x07\x00\x0c\x0c\x0e", + ), + ), + ( # 17 + pdu_other.PDUreportDeviceId, + "report_device_id", + ( + {}, + b"\x01\x11", + {"identifier": b"\x12", "status": True}, + b"\x01\x11\x02\x12\xff", + ), + ), + ( # 18 + pdu_diag.PDUreturnQueryData, + "diag_query_data", + ( + {}, + b"\x01\x08\x00\x00\x00\x00", + {}, + b"\x01\x08\x00\x00\x00\x00", + ), + ), + ( # 19 + pdu_diag.PDUreturnQueryData, + "diag_query_data", + ( + {"message": b"AB"}, + b"\x01\x08\x00\x00\x41\x42", + {"message": b"AB"}, + b"\x01\x08\x00\x00\x41\x42", + ), + ), + ( # 20 + pdu_diag.PDUrestartCommunicationsOption, + "diag_restart_communication", + ( + {}, + b"\x01\x08\x00\x01\x00\x00", + {}, + b"\x01\x08\x00\x01\x00\x00", + ), + ), + ( # 21 + pdu_diag.PDUrestartCommunicationsOption, + "diag_restart_communication", + ( + {"message": b"\xff\x00"}, + b"\x01\x08\x00\x01\xff\x00", + {"message": b"\xff\x00"}, + b"\x01\x08\x00\x01\xff\x00", + ), + ), + ( # 22 + pdu_diag.PDUrestartCommunicationsOption, + "diag_restart_communication", + ( + {"message": b"\x00\x00"}, + b"\x01\x08\x00\x01\x00\x00", + {"message": b"\x00\x00"}, + b"\x01\x08\x00\x01\x00\x00", + ), + ), + ( # 23 + pdu_diag.PDUreturnDiagnosticRegister, + "diag_read_diagnostic_register", + ( + {}, + b"\x01\x08\x00\x02\x00\x00", + {}, + b"\x01\x08\x00\x02\x00\x00", + ), + ), + ( # 24 + pdu_diag.PDUreturnDiagnosticRegister, + "diag_read_diagnostic_register", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x02\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x02\x10\x10", + ), + ), + ( # 25 + pdu_diag.PDUchangeAsciiInputDelimiter, + "diag_change_ascii_input_delimeter", + ( + {}, + b"\x01\x08\x00\x03\x00\x00", + {}, + b"\x01\x08\x00\x03\x00\x00", + ), + ), + ( # 26 + pdu_diag.PDUchangeAsciiInputDelimiter, + "diag_change_ascii_input_delimeter", + ( + {"message": b"A\x00"}, + b"\x01\x08\x00\x03\x41\x00", + {"message": b"A\x00"}, + b"\x01\x08\x00\x03\x41\x00", + ), + ), + ( # 27 + pdu_diag.PDUchangeAsciiInputDelimiter, + "diag_change_ascii_input_delimeter", + ( + {"message": b"\n\x00"}, + b"\x01\x08\x00\x03\x0a\x00", + {"message": b"\n\x00"}, + b"\x01\x08\x00\x03\x0a\x00", + ), + ), + ( # 28 + pdu_diag.PDUforceListenOnlyMode, + "diag_force_listen_only", + ({}, b"\x01\x08\x00\x04\x00\x00", {}, b"\x01\x08\x00\x04\x00\x00"), + ), + ( # 29 + pdu_diag.PDUforceListenOnlyMode, + "diag_force_listen_only", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x04\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x04\x10\x10", + ), + ), + ( # 30 + pdu_diag.PDUclearCounters, + "diag_clear_counters", + ({}, b"\x01\x08\x00\x0a\x00\x00", {}, b"\x01\x08\x00\n\x00\x00"), + ), + ( # 31 + pdu_diag.PDUclearCounters, + "diag_clear_counters", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x0a\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\n\x10\x10", + ), + ), + ( # 32 + pdu_diag.PDUreturnBusMessageCount, + "diag_read_bus_message_count", + ( + {}, + b"\x01\x08\x00\x0b\x00\x00", + {}, + b"\x01\x08\x00\x0b\x00\x00", + ), + ), + ( # 33 + pdu_diag.PDUreturnBusMessageCount, + "diag_read_bus_message_count", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x0b\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x0b\x10\x10", + ), + ), + ( # 34 + pdu_diag.PDUreturnBusCommunicationErrorCount, + "diag_read_bus_comm_error_count", + ( + {}, + b"\x01\x08\x00\x0c\x00\x00", + {}, + b"\x01\x08\x00\x0c\x00\x00", + ), + ), + ( # 35 + pdu_diag.PDUreturnBusCommunicationErrorCount, + "diag_read_bus_comm_error_count", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x0c\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x0c\x10\x10", + ), + ), + ( # 36 + pdu_diag.PDUreturnBusExceptionErrorCount, + "diag_read_bus_exception_error_count", + ( + {}, + b"\x01\x08\x00\x0d\x00\x00", + {}, + b"\x01\x08\x00\x0d\x00\x00", + ), + ), + ( # 37 + pdu_diag.PDUreturnBusExceptionErrorCount, + "diag_read_bus_exception_error_count", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x0d\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x0d\x10\x10", + ), + ), + ( # 38 + pdu_diag.PDUreturnDeviceMessageCount, + "diag_read_device_message_count", + ( + {}, + b"\x01\x08\x00\x0e\x00\x00", + {}, + b"\x01\x08\x00\x0e\x00\x00", + ), + ), + ( # 39 + pdu_diag.PDUreturnDeviceMessageCount, + "diag_read_device_message_count", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x0e\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x0e\x10\x10", + ), + ), + ( # 40 + pdu_diag.PDUreturnDeviceNoResponseCount, + "diag_read_device_no_response_count", + ( + {}, + b"\x01\x08\x00\x0f\x00\x00", + {}, + b"\x01\x08\x00\x0f\x00\x00", + ), + ), + ( # 41 + pdu_diag.PDUreturnDeviceNoResponseCount, + "diag_read_device_no_response_count", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x0f\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x0f\x10\x10", + ), + ), + ( # 42 + pdu_diag.PDUreturnDeviceNAKCount, + "diag_read_device_nak_count", + ( + {}, + b"\x01\x08\x00\x10\x00\x00", + {}, + b"\x01\x08\x00\x10\x00\x00", + ), + ), + ( # 43 + pdu_diag.PDUreturnDeviceNAKCount, + "diag_read_device_nak_count", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x10\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x10\x10\x10", + ), + ), + ( # 44 + pdu_diag.PDUreturnDeviceBusyCount, + "diag_read_device_busy_count", + ( + {}, + b"\x01\x08\x00\x11\x00\x00", + {}, + b"\x01\x08\x00\x11\x00\x00", + ), + ), + ( # 45 + pdu_diag.PDUreturnDeviceBusyCount, + "diag_read_device_busy_count", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x11\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x11\x10\x10", + ), + ), + ( # 46 + pdu_diag.PDUreturnDeviceBusCharacterOverrunCount, + "diag_read_bus_char_overrun_count", + ( + {}, + b"\x01\x08\x00\x12\x00\x00", + {}, + b"\x01\x08\x00\x12\x00\x00", + ), + ), + ( # 47 + pdu_diag.PDUreturnDeviceBusCharacterOverrunCount, + "diag_read_bus_char_overrun_count", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x12\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x12\x10\x10", + ), + ), + ( # 48 + pdu_diag.PDUreturnIopOverrunCount, + "diag_read_iop_overrun_count", + ( + {}, + b"\x01\x08\x00\x13\x00\x00", + {}, + b"\x01\x08\x00\x13\x00\x00", + ), + ), + ( # 49 + pdu_diag.PDUreturnIopOverrunCount, + "diag_read_iop_overrun_count", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x13\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x13\x10\x10", + ), + ), + ( # 50 + pdu_diag.PDUclearOverrunCount, + "diag_clear_overrun_counter", + ( + {}, + b"\x01\x08\x00\x14\x00\x00", + {}, + b"\x01\x08\x00\x14\x00\x00", + ), + ), + ( # 51 + pdu_diag.PDUclearOverrunCount, + "diag_clear_overrun_counter", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x14\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x14\x10\x10", + ), + ), + ( # 52 + pdu_diag.PDUgetClearModbusPlus, + "diag_getclear_modbus_response", + ( + {}, + b"\x01\x08\x00\x15\x00\x00", + {}, + b"\x01\x08\x00\x15\x00\x00", + ), + ), + ( # 53 + pdu_diag.PDUgetClearModbusPlus, + "diag_getclear_modbus_response", + ( + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x15\x10\x10", + {"message": b"\x10\x10"}, + b"\x01\x08\x00\x15\x10\x10", + ), + ), + ], +) +def paramPDU(request): + """Define all requests/responses for use in general tests.""" + pdu, api, entry = request.param + return pdu, api, entry[0], entry[1], entry[2], entry[3] diff --git a/test/pdu/test_bit.py b/test/pdu/test_bit.py deleted file mode 100644 index 26903e11fd..0000000000 --- a/test/pdu/test_bit.py +++ /dev/null @@ -1,340 +0,0 @@ -"""Bit Message Test Fixture.""" - -from unittest import mock - -import pytest - -import pymodbus.pdu.bit_message as bit_msg -from pymodbus.constants import ExcCodes -from pymodbus.pdu.decoders import DecodePDU - - -class TestModbusBitMessage: - """Modbus bit read message tests.""" - - def test_bit_read_base_response_encoding(self): - """Test basic bit message encoding/decoding.""" - for i in range(1, 20): - data = [True] * i - expected = data + [False] * (-len(data) % 8) - pdu = bit_msg.ReadCoilsResponse(bits=data) - pdu.x_decode(pdu.x_encode()) - assert pdu.bits == expected - - def test_bit_read_base_requests(self): - """Test bit read request encoding.""" - for pdu, expected in ( - (bit_msg.ReadCoilsRequest(address=12, count=14), b"\x00\x0c\x00\x0e"), - ( - bit_msg.ReadCoilsResponse(bits=[True, False, True, True, False]), - b"\x01\x0d", - ), - ): - assert pdu.x_encode() == expected - - async def test_bit_read_datastore_update_value_errors(self, mock_server_context): - """Test bit read request encoding.""" - context = mock_server_context() - for pdu in ( - (bit_msg.ReadCoilsRequest(address=1, count=0x800)), - (bit_msg.ReadDiscreteInputsRequest(address=1, count=0x800)), - ): - await pdu.datastore_update(context, 1) - - @pytest.mark.parametrize( - ("request_class", "function_code"), - [ - (bit_msg.ReadCoilsRequest, 1), - (bit_msg.ReadDiscreteInputsRequest, 2), - ], - ) - async def test_bit_read_count_above_max_returns_illegal_value( - self, request_class, function_code, mock_server_context - ): - """An out-of-range bit read quantity must answer 0x03, not silence.""" - context = mock_server_context() - context.async_getValues = mock.AsyncMock(return_value=[True] * 10) - request = request_class(address=0, count=request_class.MAX_COUNT + 1) - result = await request.datastore_update(context, 1) - assert result.function_code == function_code | 0x80 - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - context.async_getValues.assert_not_awaited() - - @pytest.mark.parametrize( - "request_class", - [bit_msg.ReadCoilsRequest, bit_msg.ReadDiscreteInputsRequest], - ) - async def test_bit_read_count_zero_returns_illegal_value( - self, request_class, mock_server_context - ): - """A zero bit read quantity must answer 0x03.""" - context = mock_server_context() - context.async_getValues = mock.AsyncMock(return_value=[True] * 10) - result = await request_class(address=0, count=0).datastore_update(context, 1) - assert result.function_code == request_class.function_code | 0x80 - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - context.async_getValues.assert_not_awaited() - - @pytest.mark.parametrize( - "request_class", - [bit_msg.ReadCoilsRequest, bit_msg.ReadDiscreteInputsRequest], - ) - async def test_bit_read_count_at_max_returns_normal_response( - self, request_class, mock_server_context - ): - """A count exactly at the maximum must be accepted, not rejected.""" - context = mock_server_context() - request = request_class(address=0, count=request_class.MAX_COUNT) - result = await request.datastore_update(context, 1) - assert result.function_code == request_class.function_code - - def test_bit_read_decode_accepts_count_above_max(self): - """Decoding must not raise for an over-max bit read quantity.""" - decoder = DecodePDU(True) - for frame, expected_count in ( - (b"\x01\x00\x00\x07\xd1", 2001), - (b"\x02\x00\x00\x07\xd1", 2001), - ): - pdu = decoder.decode(frame) - assert pdu.count == expected_count - - async def test_bit_datastore_exceptions(self, mock_server_context): - """Test bit exception response from datastore.""" - context = mock_server_context() - context.async_getValues = mock.AsyncMock(return_value=ExcCodes.ILLEGAL_VALUE) - for pdu in ( - (bit_msg.ReadCoilsRequest(address=1, count=5)), - (bit_msg.ReadDiscreteInputsRequest(address=1, count=5)), - (bit_msg.WriteSingleCoilRequest(address=1, bits=[True])), - (bit_msg.WriteMultipleCoilsRequest(address=1, bits=[True] * 5)), - ): - await pdu.datastore_update(context, 0) - - async def test_bit_read_datastore_update_address_errors(self, mock_server_context): - """Test bit read request encoding.""" - context = mock_server_context() - for pdu in ( - (bit_msg.ReadCoilsRequest(address=1, count=0x800)), - (bit_msg.ReadDiscreteInputsRequest(address=1, count=0x800)), - ): - await pdu.datastore_update(context, 1) - - def test_bit_write_base_requests(self): - """Test bit write base.""" - for pdu, expected in ( - ( - bit_msg.WriteSingleCoilRequest(address=1, bits=[True]), - b"\x00\x01\xff\x00", - ), - ( - bit_msg.WriteMultipleCoilsRequest(address=1, bits=[True] * 5), - b"\x00\x01\x00\x05\x01\x1f", - ), - ( - bit_msg.WriteMultipleCoilsRequest(address=1, bits=[True]), - b"\x00\x01\x00\x01\x01\x01", - ), - ( - bit_msg.WriteMultipleCoilsResponse(address=1, count=5), - b"\x00\x01\x00\x05", - ), - ( - bit_msg.WriteMultipleCoilsResponse(address=1, count=1), - b"\x00\x01\x00\x01", - ), - ): - assert pdu.x_encode() == expected - - def test_write_message_coil(self): - """Test bit write message.""" - _ = bit_msg.WriteSingleCoilRequest(address=1, bits=[True]) - - def test_write_multiple_coils_request(self): - """Test write multiple coils.""" - for request, frame, values in ( - ( - bit_msg.WriteMultipleCoilsRequest(address=1, bits=[True] * 5), - b"\x00\x01\x00\x05\x01\x1f", - [True] * 5, - ), - ( - bit_msg.WriteMultipleCoilsRequest(address=1, bits=[True]), - b"\x00\x01\x00\x01\x01\x01", - [True], - ), - ): - request.x_decode(frame) - assert request.address == 1 - assert request.bits == values - - def test_invalid_write_multiple_coils_request(self): - """Test write invalid multiple coils.""" - request = bit_msg.WriteMultipleCoilsRequest(address=1, bits=None) - assert not request.bits - - @pytest.mark.parametrize( - "frame", - [ - b"\x00\x01\x00\x10\x01\xff", - b"\x00\x01\x00\x08\x02\xff\x00", - b"\x00\x01\x00\x08\x01", - b"\x00\x01\x00\x08\x01\xff\x00", - ], - ) - async def test_write_multiple_coils_rejects_invalid_byte_count( - self, frame, mock_server_context - ): - """Test write multiple coils rejects inconsistent byte counts.""" - request = bit_msg.WriteMultipleCoilsRequest() - request.x_decode(frame) - context = mock_server_context() - context.async_setValues = mock.AsyncMock() - - result = await request.datastore_update(context, 0) - - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - context.async_setValues.assert_not_awaited() - - async def test_write_multiple_coils_accepts_valid_byte_count( - self, mock_server_context - ): - """Test write multiple coils accepts a consistent byte count.""" - request = bit_msg.WriteMultipleCoilsRequest() - request.x_decode(b"\x00\x01\x00\x09\x02\xff\x01") - context = mock_server_context() - context.async_setValues = mock.AsyncMock(return_value=0) - - result = await request.datastore_update(context, 0) - - assert result.count == 9 - context.async_setValues.assert_awaited_once_with( - 0, request.function_code, 1, [True] * 9 - ) - - def test_write_single_coil_request_encode(self): - """Test write single coil.""" - request = bit_msg.WriteSingleCoilRequest(address=1, bits=[False]) - assert request.x_encode() == b"\x00\x01\x00\x00" - - async def test_write_single_coil_datastore_update(self, mock_server_context): - """Test write single coil.""" - context = mock_server_context(False, default=True) - request = bit_msg.WriteSingleCoilRequest(address=2, bits=[True]) - result = await request.datastore_update(context, 1) - - context.valid = True - result = await request.datastore_update(context, 0) - assert result.x_encode() == b"\x00\x02\xff\x00" - - context = mock_server_context(True, default=False) - request = bit_msg.WriteSingleCoilRequest(address=2, bits=[False]) - result = await request.datastore_update(context, 0) - assert result.x_encode() == b"\x00\x02\x00\x00" - - @pytest.mark.parametrize("value", [b"\x00\x01", b"\x00\xff", b"\xff\xff"]) - async def test_write_single_coil_illegal_value(self, value, mock_server_context): - """A value other than 0x0000 or 0xFF00 must answer 0x03 and leave the coil.""" - context = mock_server_context() - context.async_setValues = mock.AsyncMock(return_value=0) - request = bit_msg.WriteSingleCoilRequest() - request.x_decode(b"\x00\x02" + value) - result = await request.datastore_update(context, 1) - assert result.function_code == 0x85 - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - context.async_setValues.assert_not_awaited() - - @pytest.mark.parametrize( - ("value", "bit"), [(b"\xff\x00", True), (b"\x00\x00", False)] - ) - async def test_write_single_coil_legal_value(self, value, bit, mock_server_context): - """0xFF00 and 0x0000 are written as ON and OFF.""" - context = mock_server_context() - context.async_setValues = mock.AsyncMock(return_value=0) - context.async_getValues = mock.AsyncMock(return_value=[bit]) - request = bit_msg.WriteSingleCoilRequest() - request.x_decode(b"\x00\x02" + value) - result = await request.datastore_update(context, 1) - assert result.x_encode() == b"\x00\x02" + value - context.async_setValues.assert_awaited_once_with(1, 5, 2, [bit]) - - async def test_write_multiple_coils_datastore_update(self, mock_server_context): - """Test write multiple coils.""" - context = mock_server_context(False) - # too many values - request = bit_msg.WriteMultipleCoilsRequest(address=2, bits=[]) - result = await request.datastore_update(context, 0) - - # does not verify - context.valid = False - request = bit_msg.WriteMultipleCoilsRequest(address=2, bits=[False] * 4) - result = await request.datastore_update(context, 0) - - # verified request - context.valid = True - result = await request.datastore_update(context, 0) - assert result.x_encode() == b"\x00\x02\x00\x04" - - @pytest.mark.parametrize( - ("request_pdu"), - [ - bit_msg.WriteSingleCoilRequest(address=2, bits=[True]), - bit_msg.WriteMultipleCoilsRequest(address=2, bits=[]), - ], - ) - async def test_write_coil_exception(self, request_pdu, mock_server_context): - """Test write single coil.""" - context = mock_server_context(True, default=True) - context.async_setValues = mock.AsyncMock(return_value=1) - result = await request_pdu.datastore_update(context, 1) - assert result.exception_code == 1 - - def test_write_multiple_coils_response(self): - """Test write multiple coils.""" - response = bit_msg.WriteMultipleCoilsResponse() - response.x_decode(b"\x00\x80\x00\x08") - assert response.address == 0x80 - assert response.count == 0x08 - - def test_serializing_to_string(self): - """Test serializing to string.""" - for pdu in ( - bit_msg.WriteSingleCoilRequest(address=1, bits=[True]), - bit_msg.WriteSingleCoilResponse(address=1, bits=[True]), - bit_msg.WriteMultipleCoilsRequest(address=1, bits=[True] * 5), - bit_msg.WriteMultipleCoilsResponse(address=1, count=5), - ): - assert str(pdu) - - def test_pass_falsy_value_in_write_multiple_coils_request(self): - """Test pass falsy value to write multiple coils.""" - request = bit_msg.WriteMultipleCoilsRequest(address=1, bits=[False]) - assert request.bits == [False] - - -class TestWriteMultipleCoilsCount: - """Quantity limits of Write Multiple Coils (0x0F).""" - - def test_write_coils_max_count_fits_pdu(self): - """The largest write count must keep the PDU within 253 bytes.""" - assert bit_msg.WriteMultipleCoilsRequest.MAX_COUNT == 0x07B0 - pdu = bit_msg.WriteMultipleCoilsRequest(address=0, bits=[True] * 0x07B0) - assert len(pdu.x_encode()) + 1 <= 253 - with pytest.raises(ValueError, match="count"): - bit_msg.WriteMultipleCoilsRequest( - address=0, bits=[True] * (0x07B0 + 1) - ).x_encode() - - @pytest.mark.parametrize("count", [0, 0x07B1, 2000]) - async def test_write_coils_count_out_of_range_returns_illegal_value( - self, count, mock_server_context - ): - """An out-of-range write quantity must answer 0x03, not silence.""" - context = mock_server_context() - context.async_setValues = mock.AsyncMock(return_value=0) - byte_count = (count + 7) // 8 - frame = b"\x0f\x00\x00" + count.to_bytes(2, "big") + bytes([byte_count]) - pdu = DecodePDU(True).decode(frame + b"\xff" * byte_count) - result = await pdu.datastore_update(context, 1) - assert result.function_code == 0x8F - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - context.async_setValues.assert_not_awaited() diff --git a/test/pdu/test_decoders.py b/test/pdu/test_decoders.py deleted file mode 100644 index 0208cf9940..0000000000 --- a/test/pdu/test_decoders.py +++ /dev/null @@ -1,192 +0,0 @@ -"""Test decoders.""" - -import pytest - -from pymodbus.exceptions import MessageRegisterException, ModbusIOException -from pymodbus.pdu.decoders import DecodePDU - - -class TestModbusPDU: - """Test ModbusPDU.""" - - client = DecodePDU(False) - server = DecodePDU(True) - requests = ( - (0x01, b"\x01\x00\x01\x00\x01"), # read coils - (0x02, b"\x02\x00\x01\x00\x01"), # read discrete inputs - (0x03, b"\x03\x00\x01\x00\x01"), # read holding registers - (0x04, b"\x04\x00\x01\x00\x01"), # read input registers - (0x05, b"\x05\x00\x01\x00\x01"), # write single coil - (0x06, b"\x06\x00\x01\x00\x01"), # write single register - (0x07, b"\x07"), # read exception status - (0x08, b"\x08\x00\x00\x00\x00"), # read diagnostic - (0x0B, b"\x0b"), # get comm event counters - (0x0C, b"\x0c"), # get comm event log - (0x0F, b"\x0f\x00\x01\x00\x08\x01\x00\xff"), # write multiple coils - (0x10, b"\x10\x00\x01\x00\x02\x04\0xff\xff"), # write multiple registers - (0x11, b"\x11"), # report device id - ( - 0x14, - b"\x14\x0e\x06\x00\x04\x00\x01\x00\x02\x06\x00\x03\x00\x09\x00\x02", - ), # read file record - ( - 0x15, - b"\x15\x0d\x06\x00\x04\x00\x07\x00\x03\x06\xaf\x04\xbe\x10\x0d", - ), # write file record - (0x16, b"\x16\x00\x01\x00\xff\xff\x00"), # mask write register - ( - 0x17, - b"\x17\x00\x01\x00\x01\x00\x01\x00\x01\x02\x12\x34", - ), # r/w multiple regs - (0x18, b"\x18\x00\x01"), # read fifo queue - (0x2B, b"\x2b\x0e\x01\x00"), # read device identification - ) - - responses = ( - (0x01, b"\x01\x01\x01"), # read coils - (0x02, b"\x02\x01\x01"), # read discrete inputs - (0x03, b"\x03\x02\x01\x01"), # read holding registers - (0x04, b"\x04\x02\x01\x01"), # read input registers - (0x05, b"\x05\x00\x01\x00\x01"), # write single coil - (0x06, b"\x06\x00\x01\x00\x01"), # write single register - (0x07, b"\x07\x00"), # read exception status - (0x08, b"\x08\x00\x00\x00\x00"), # read diagnostic - (0x0B, b"\x0b\x00\x00\x00\x00"), # get comm event counters - (0x0C, b"\x0c\x08\x00\x00\x01\x08\x01\x21\x20\x00"), # get comm event log - (0x0F, b"\x0f\x00\x01\x00\x08"), # write multiple coils - (0x10, b"\x10\x00\x01\x00\x02"), # write multiple registers - (0x11, b"\x11\x03\x05\x01\x54"), # report device id (device specific) - ( - 0x14, - b"\x14\x0c\x05\x06\x0d\xfe\x00\x20\x05\x06\x33\xcd\x00\x40", - ), # read file record - ( - 0x15, - b"\x15\x0d\x06\x00\x04\x00\x07\x00\x03\x06\xaf\x04\xbe\x10\x0d", - ), # write file record - (0x16, b"\x16\x00\x01\x00\xff\xff\x00"), # mask write register - (0x17, b"\x17\x02\x12\x34"), # read/write multiple registers - (0x18, b"\x18\x00\x01\x00\x01\x00\x00"), # read fifo queue - ( - 0x2B, - b"\x2b\x0e\x01\x01\x00\x00\x01\x00\x01\x77", - ), # read device identification - ) - - exceptions = ( - (0x81, b"\x81\x01\xd0\x50"), # illegal function exception - (0x82, b"\x82\x02\x90\xa1"), # illegal data address exception - (0x83, b"\x83\x03\x50\xf1"), # illegal data value exception - (0x84, b"\x84\x04\x13\x03"), # skave device failure exception - (0x85, b"\x85\x05\xd3\x53"), # acknowledge exception - (0x86, b"\x86\x06\x93\xa2"), # device busy exception - (0x87, b"\x87\x08\x53\xf2"), # memory parity exception - (0x88, b"\x88\x0a\x16\x06"), # gateway path unavailable exception - (0x89, b"\x89\x0b\xd6\x56"), # gateway target failed exception - ) - - bad = ( - (0x80, b"\x80\x00\x00\x00"), # Unknown Function - (0x81, b"\x81\x00\x00\x00"), # error message - ) - - @pytest.mark.parametrize(("code", "frame"), list(responses) + list(exceptions)) - def test_client_lookup(self, code, frame): - """Test lookup for responses.""" - data = b"\x01" + frame - pdu = self.client._lookupPduClass(data) - assert pdu - if not code & 0x80: - assert pdu.function_code == code - - def test_client_lookup_no_fc(self): - """Test lookup for responses.""" - data = b"\x01\x70" - pdu = self.client._lookupPduClass(data) - assert not pdu - - def test_list_function_codes(self): - """Test lookup for responses.""" - fc_list = self.client.list_function_codes() - assert fc_list - - @pytest.mark.parametrize(("code", "frame"), list(requests)) - def test_server_lookup(self, code, frame): - """Test lookup for requests.""" - data = b"\x01" + frame - pdu = self.client._lookupPduClass(data) - assert pdu - assert pdu.function_code == code - - @pytest.mark.parametrize(("code", "frame"), list(responses) + list(exceptions)) - def test_client_decode(self, code, frame): - """Test lookup for responses.""" - pdu = self.client.decode(frame) - assert pdu - assert pdu.function_code == code - - @pytest.mark.parametrize(("code", "frame"), list(requests)) - def test_server_decode(self, code, frame): - """Test lookup for requests.""" - pdu = self.server.decode(frame) - assert pdu - assert pdu.function_code == code - - @pytest.mark.parametrize(("code", "frame"), list(exceptions)) - def test_server_decode_reserved_function_code(self, code, frame): - """A request may not use a function code reserved for exception responses.""" - with pytest.raises(ModbusIOException) as exc: - self.server.decode(frame) - assert exc.value.fcode == code - - @pytest.mark.parametrize(("frame"), [b"", b"NO FRAME"]) - @pytest.mark.parametrize(("decoder"), [server, client]) - def test_decode_bad_frame(self, decoder, frame): - """Test lookup bad frames.""" - with pytest.raises(ModbusIOException): - decoder.decode(frame) - - @pytest.mark.parametrize( - ("decoder", "frame"), - [ - (server, b"\x14\x10"), # read file record, byte count past the frame - (server, b"\x15\x10"), # write file record, byte count past the frame - (client, b"\x18\x00\x06\x00\x05\x00\x01"), # fifo count past the frame - ], - ) - def test_decode_bad_file_record_frame(self, decoder, frame): - """Test bad file record frames fail like other undecodable frames.""" - with pytest.raises(ModbusIOException): - decoder.decode(frame) - - def test_decode_unknown_sub(self): - """Test for unknown sub code.""" - with pytest.raises(ModbusIOException): - self.client.decode(b"\x08\x00\xf0\xf0\x00") - - @pytest.mark.parametrize(("decoder"), [server, client]) - def test_register_custom_request(self, decoder, mockPDU): - """Test server register custom request.""" - - class NoCustomRequestResponse: - """Custom request.""" - - function_code = 0x70 - - def x_encode(self): - """Encode.""" - - def x_decode(self, _data): - """Decode.""" - - decoder.register(mockPDU) - data = b"\x01" + mockPDU().x_encode() - assert decoder._lookupPduClass(data) - mockPDU.sub_function_code = 0xF7 - decoder.register(mockPDU) - mockPDU.sub_function_code = 0xF4 - decoder.register(mockPDU) - data = b"\x01" + mockPDU().x_encode() - assert self.server._lookupPduClass(data) - with pytest.raises(MessageRegisterException): - decoder.register(NoCustomRequestResponse) diff --git a/test/pdu/test_device.py b/test/pdu/test_device.py index 185908738b..ea6e381900 100644 --- a/test/pdu/test_device.py +++ b/test/pdu/test_device.py @@ -1,22 +1,23 @@ """Test device.""" +import pytest + from pymodbus.constants import DeviceInformation +from pymodbus.exceptions import ParameterException from pymodbus.pdu.device import ( + CommunicationRestartEvent, DeviceInformationFactory, + EnteredListenModeEvent, ModbusControlBlock, ModbusDeviceIdentification, ModbusPlusStatistics, + RemoteReceiveEvent, + RemoteSendEvent, ) -from pymodbus.pdu.events import RemoteReceiveEvent - -# ---------------------------------------------------------------------------# -# Fixture -# ---------------------------------------------------------------------------# - -class TestDataStore: - """Unittest for the pymodbus.device module.""" +class TestDevice: + """Tests for the pymodbus.device module.""" # -----------------------------------------------------------------------# # Setup/TearDown @@ -324,10 +325,10 @@ def test_modbus_plus_statistics(self): """Test device identification reading.""" default = [0x0000] * 55 statistics = ModbusPlusStatistics() - assert default == statistics.x_encode() + assert default == statistics.encode() statistics.reset() - assert default == statistics.x_encode() - assert default == self.control.Plus.x_encode() + assert default == statistics.encode() + assert default == self.control.Plus.encode() def test_modbus_plus_statistics_helpers(self): """Test modbus plus statistics helper methods.""" @@ -390,3 +391,62 @@ def test_device_info_name(self): name = "Maintainer" info = ModbusDeviceIdentification(info_name={"VendorName": name}) assert name == info.VendorName + + +class TestEvents: + """Tests events.""" + + def test_remote_receive_event(self): + """Test remove receive event.""" + event = RemoteReceiveEvent() + event.decode(b"\x70") + assert event.overrun + assert event.listen + assert event.broadcast + + def test_remote_sent_event(self): + """Test remote sent event.""" + event = RemoteSendEvent() + result = event.encode() + assert result == b"\x40" + event.decode(b"\x7f") + assert event.read + assert event.device_abort + assert event.device_busy + assert event.device_nak + assert event.write_timeout + assert event.listen + + def test_remote_sent_event_encode(self): + """Test remote sent event encode.""" + arguments = { + "read": True, + "device_abort": True, + "device_busy": True, + "device_nak": True, + "write_timeout": True, + "listen": True, + } + event = RemoteSendEvent(**arguments) + result = event.encode() + assert result == b"\x7f" + + def test_entered_listen_mode_event(self): + """Test entered listen mode event.""" + event = EnteredListenModeEvent() + result = event.encode() + assert result == b"\x04" + event.decode(b"\x04") + assert event.value == 0x04 + with pytest.raises(ParameterException): + event.decode(b"\x00") + + def test_communication_restart_event(self): + """Test communication restart event.""" + event = CommunicationRestartEvent() + result = event.encode() + assert result == b"\x00" + event.decode(b"\x00") + assert not event.value + with pytest.raises(ParameterException): + event.decode(b"\x04") diff --git a/test/pdu/test_diag_messages.py b/test/pdu/test_diag_messages.py deleted file mode 100644 index 1d9149ef40..0000000000 --- a/test/pdu/test_diag_messages.py +++ /dev/null @@ -1,224 +0,0 @@ -"""Test diag messages.""" - -from typing import cast - -import pytest - -from pymodbus.constants import ModbusPlusOperation, ModbusStatus -from pymodbus.datastore import ModbusServerContext -from pymodbus.pdu.device import ModbusControlBlock -from pymodbus.pdu.diag_message import ( - ChangeAsciiInputDelimiterRequest, - ChangeAsciiInputDelimiterResponse, - ClearCountersRequest, - ClearCountersResponse, - ClearOverrunCountRequest, - ClearOverrunCountResponse, - DiagnosticBase, - ForceListenOnlyModeRequest, - ForceListenOnlyModeResponse, - GetClearModbusPlusRequest, - GetClearModbusPlusResponse, - RestartCommunicationsOptionRequest, - RestartCommunicationsOptionResponse, - ReturnBusCommunicationErrorCountRequest, - ReturnBusCommunicationErrorCountResponse, - ReturnBusExceptionErrorCountRequest, - ReturnBusExceptionErrorCountResponse, - ReturnBusMessageCountRequest, - ReturnBusMessageCountResponse, - ReturnDeviceBusCharacterOverrunCountRequest, - ReturnDeviceBusCharacterOverrunCountResponse, - ReturnDeviceBusyCountRequest, - ReturnDeviceBusyCountResponse, - ReturnDeviceMessageCountRequest, - ReturnDeviceMessageCountResponse, - ReturnDeviceNAKCountRequest, - ReturnDeviceNAKCountResponse, - ReturnDeviceNoResponseCountRequest, - ReturnDeviceNoResponseCountResponse, - ReturnDiagnosticRegisterRequest, - ReturnDiagnosticRegisterResponse, - ReturnIopOverrunCountRequest, - ReturnIopOverrunCountResponse, - ReturnQueryDataRequest, - ReturnQueryDataResponse, -) - - -class TestDataStore: - """Unittest for the pymodbus.diag_message module.""" - - requests = [ - ( - RestartCommunicationsOptionRequest, - b"\x00\x01\x00\x00", - b"\x00\x01\x00\x00", - ), - (ReturnDiagnosticRegisterRequest, b"\x00\x02\x00\x00", b"\x00\x02\x00\x00"), - ( - ChangeAsciiInputDelimiterRequest, - b"\x00\x03\x00\x00", - b"\x00\x03\x00\x00", - ), - (ForceListenOnlyModeRequest, b"\x00\x04\x00\x00", b"\x00\x04"), - (ReturnQueryDataRequest, b"\x00\x00\x00\x00", b"\x00\x00\x00\x00"), - (ClearCountersRequest, b"\x00\x0a\x00\x00", b"\x00\x0a\x00\x00"), - (ReturnBusMessageCountRequest, b"\x00\x0b\x00\x00", b"\x00\x0b\x00\x00"), - ( - ReturnBusCommunicationErrorCountRequest, - b"\x00\x0c\x00\x00", - b"\x00\x0c\x00\x00", - ), - ( - ReturnBusExceptionErrorCountRequest, - b"\x00\x0d\x00\x00", - b"\x00\x0d\x00\x00", - ), - (ReturnDeviceMessageCountRequest, b"\x00\x0e\x00\x00", b"\x00\x0e\x00\x00"), - ( - ReturnDeviceNoResponseCountRequest, - b"\x00\x0f\x00\x00", - b"\x00\x0f\x00\x00", - ), - (ReturnDeviceNAKCountRequest, b"\x00\x10\x00\x00", b"\x00\x10\x00\x00"), - (ReturnDeviceBusyCountRequest, b"\x00\x11\x00\x00", b"\x00\x11\x00\x00"), - ( - ReturnDeviceBusCharacterOverrunCountRequest, - b"\x00\x12\x00\x00", - b"\x00\x12\x00\x00", - ), - (ReturnIopOverrunCountRequest, b"\x00\x13\x00\x00", b"\x00\x13\x00\x00"), - (ClearOverrunCountRequest, b"\x00\x14\x00\x00", b"\x00\x14\x00\x00"), - ( - GetClearModbusPlusRequest, - b"\x00\x15\x00\x00", - b"\x00\x15\x00\x00" + b"\x00\x00" * 55, - ), - ] - - responses = [ - (DiagnosticBase, b"\x00\x00\x00\x00"), - (DiagnosticBase, b"\x00\x00\x00\x00"), - (ReturnQueryDataResponse, b"\x00\x00\x00\x00"), - (RestartCommunicationsOptionResponse, b"\x00\x01\x00\x00"), - (ReturnDiagnosticRegisterResponse, b"\x00\x02\x00\x00"), - (ChangeAsciiInputDelimiterResponse, b"\x00\x03\x00\x00"), - (ForceListenOnlyModeResponse, b"\x00\x04"), - (ReturnQueryDataResponse, b"\x00\x00\x00\x00"), - (ClearCountersResponse, b"\x00\x0a\x00\x00"), - (ReturnBusMessageCountResponse, b"\x00\x0b\x00\x00"), - (ReturnBusCommunicationErrorCountResponse, b"\x00\x0c\x00\x00"), - (ReturnBusExceptionErrorCountResponse, b"\x00\x0d\x00\x00"), - (ReturnDeviceMessageCountResponse, b"\x00\x0e\x00\x00"), - (ReturnDeviceNoResponseCountResponse, b"\x00\x0f\x00\x00"), - (ReturnDeviceNAKCountResponse, b"\x00\x10\x00\x00"), - (ReturnDeviceBusyCountResponse, b"\x00\x11\x00\x00"), - (ReturnDeviceBusCharacterOverrunCountResponse, b"\x00\x12\x00\x00"), - (ReturnIopOverrunCountResponse, b"\x00\x13\x00\x00"), - (ClearOverrunCountResponse, b"\x00\x14\x00\x00"), - (GetClearModbusPlusResponse, b"\x00\x15\x00\x04" + b"\x00\x00" * 55), - ] - - def test_diagnostic_encode_decode(self): - """Testing diagnostic request/response can be decoded and encoded.""" - msg_obj = DiagnosticBase() - data = b"\x00\x01\x02\x03" - msg_obj.x_decode(data) - result = msg_obj.x_encode() - assert data == result - - def test_diagnostic_encode_error(self): - """Testing diagnostic request/response can be decoded and encoded.""" - msg_obj = DiagnosticBase() - msg_obj.message = "not allowed" # type: ignore[assignment] - with pytest.raises(TypeError): - msg_obj.x_encode() - - def test_diagnostic_decode_error(self): - """Testing diagnostic request/response can be decoded and encoded.""" - msg_obj = DiagnosticBase() - data = b"\x00\x01\x02\x03a" - msg_obj.x_decode(data) - - def test_diagnostic_requests_decode(self): - """Testing diagnostic request messages encoding.""" - for msg, enc, _ in self.requests: - handle = DiagnosticBase() - handle.x_decode(enc) - assert handle.sub_function_code == msg.sub_function_code - encoded = handle.x_encode() - assert enc == encoded - - async def test_diagnostic_simple_requests(self): - """Testing diagnostic request messages encoding.""" - request = DiagnosticBase(message=b"\x12\x34") - request.sub_function_code = 0x1234 - assert request.x_encode() == b"\x12\x34\x12\x34" - DiagnosticBase() - - def test_diagnostic_response_decode(self): - """Testing diagnostic request messages encoding.""" - for msg, enc, _ in self.requests: - handle = DiagnosticBase() - handle.x_decode(enc) - assert handle.sub_function_code == msg.sub_function_code - - def test_diagnostic_requests_encode(self): - """Testing diagnostic request messages encoding.""" - for msg, enc, _ in self.requests: - assert msg().x_encode() == enc - - async def test_diagnostic_datastore_update(self): - """Testing diagnostic message execution.""" - control = ModbusControlBlock() - try: - for message, encoded, datastore_updated in self.requests: - encoded = ( - await message().datastore_update(cast(ModbusServerContext, None), 1) - ).x_encode() - assert encoded == datastore_updated - finally: - control.Delimiter = b"\n" - - def test_return_query_data_request(self): - """Testing diagnostic message execution.""" - message = ReturnQueryDataRequest(b"\x00\x00\x00\x00") - assert message.x_encode() == b"\x00\x00\x00\x00\x00\x00" - message = ReturnQueryDataRequest(b"\x00\x00") - assert message.x_encode() == b"\x00\x00\x00\x00" - - def test_return_query_data_response(self): - """Testing diagnostic message execution.""" - message = ReturnQueryDataResponse(b"\x00\x00\x00\x00") - assert message.x_encode() == b"\x00\x00\x00\x00\x00\x00" - message = ReturnQueryDataResponse(b"\x00\x00") - assert message.x_encode() == b"\x00\x00\x00\x00" - - def test_restart_communications_option(self): - """Testing diagnostic message execution.""" - request = RestartCommunicationsOptionRequest(message=ModbusStatus.ON) - assert request.x_encode() == b"\x00\x01\xff\x00" - request = RestartCommunicationsOptionRequest(message=ModbusStatus.OFF) - assert request.x_encode() == b"\x00\x01\x00\x00" - - response = RestartCommunicationsOptionResponse(message=ModbusStatus.ON) - assert response.x_encode() == b"\x00\x01\xff\x00" - response = RestartCommunicationsOptionResponse(message=ModbusStatus.OFF) - assert response.x_encode() == b"\x00\x01\x00\x00" - - async def test_get_clear_modbus_plus_request_datastore_update(self): - """Testing diagnostic message execution.""" - request = GetClearModbusPlusRequest( - message=ModbusPlusOperation.CLEAR_STATISTICS - ) - response = await request.datastore_update(cast(ModbusServerContext, None), 0) - assert ( - cast(GetClearModbusPlusResponse, response).message - == ModbusPlusOperation.CLEAR_STATISTICS - ) - - request = GetClearModbusPlusRequest(message=ModbusPlusOperation.GET_STATISTICS) - response = await request.datastore_update(cast(ModbusServerContext, None), 0) - resp = [ModbusPlusOperation.GET_STATISTICS] - assert cast(GetClearModbusPlusResponse, response).message == resp + [0x00] * 55 diff --git a/test/pdu/test_events.py b/test/pdu/test_events.py deleted file mode 100644 index df80cac149..0000000000 --- a/test/pdu/test_events.py +++ /dev/null @@ -1,70 +0,0 @@ -"""Test events.""" - -import pytest - -from pymodbus.exceptions import ParameterException -from pymodbus.pdu.events import ( - CommunicationRestartEvent, - EnteredListenModeEvent, - RemoteReceiveEvent, - RemoteSendEvent, -) - - -class TestEvents: - """Unittest for the pymodbus.device module.""" - - def test_remote_receive_event(self): - """Test remove receive event.""" - event = RemoteReceiveEvent() - event.x_decode(b"\x70") - assert event.overrun - assert event.listen - assert event.broadcast - - def test_remote_sent_event(self): - """Test remote sent event.""" - event = RemoteSendEvent() - result = event.x_encode() - assert result == b"\x40" - event.x_decode(b"\x7f") - assert event.read - assert event.device_abort - assert event.device_busy - assert event.device_nak - assert event.write_timeout - assert event.listen - - def test_remote_sent_event_encode(self): - """Test remote sent event encode.""" - arguments = { - "read": True, - "device_abort": True, - "device_busy": True, - "device_nak": True, - "write_timeout": True, - "listen": True, - } - event = RemoteSendEvent(**arguments) - result = event.x_encode() - assert result == b"\x7f" - - def test_entered_listen_mode_event(self): - """Test entered listen mode event.""" - event = EnteredListenModeEvent() - result = event.x_encode() - assert result == b"\x04" - event.x_decode(b"\x04") - assert event.value == 0x04 - with pytest.raises(ParameterException): - event.x_decode(b"\x00") - - def test_communication_restart_event(self): - """Test communication restart event.""" - event = CommunicationRestartEvent() - result = event.x_encode() - assert result == b"\x00" - event.x_decode(b"\x00") - assert not event.value - with pytest.raises(ParameterException): - event.x_decode(b"\x04") diff --git a/test/pdu/test_file_message.py b/test/pdu/test_file_message.py deleted file mode 100644 index b403ac957d..0000000000 --- a/test/pdu/test_file_message.py +++ /dev/null @@ -1,261 +0,0 @@ -"""Bit Message Test Fixture. - -This fixture tests the functionality of all the -bit based request/response messages: - -* Read/Write Discretes -* Read Coils -""" - -import pytest - -from pymodbus.exceptions import ModbusException -from pymodbus.framer import FramerRTU -from pymodbus.pdu import DecodePDU -from pymodbus.pdu.file_message import ( - FileRecord, - ReadFifoQueueRequest, - ReadFifoQueueResponse, - ReadFileRecordRequest, - ReadFileRecordResponse, - WriteFileRecordRequest, - WriteFileRecordResponse, -) - - -TEST_MESSAGE = b"\x00\n\x00\x04\x00\x01\x00\x02\x00\x03\x00\x04" - - -class TestBitMessage: - """Modbus bit message tests.""" - - def test_read_fifo_queue_request_encode(self): - """Test basic bit message encoding/decoding.""" - handle = ReadFifoQueueRequest(0x1234) - result = handle.x_encode() - assert result == b"\x12\x34" - - def test_read_fifo_queue_request_decode(self): - """Test basic bit message encoding/decoding.""" - handle = ReadFifoQueueRequest(0x0000) - handle.x_decode(b"\x12\x34") - assert handle.address == 0x1234 - - async def test_read_fifo_queue_request(self, mock_server_context): - """Test basic bit message encoding/decoding.""" - context = mock_server_context() - handle = ReadFifoQueueRequest(0x1234) - result = await handle.datastore_update(context, 0) - assert isinstance(result, ReadFifoQueueResponse) - - def test_read_fifo_queue_response_encode(self): - """Test that the read fifo queue response can encode.""" - message = TEST_MESSAGE - handle = ReadFifoQueueResponse([1, 2, 3, 4]) - result = handle.x_encode() - assert result == message - - def test_read_fifo_queue_response_decode(self): - """Test that the read fifo queue response can decode.""" - message = TEST_MESSAGE - handle = ReadFifoQueueResponse([1, 2, 3, 4]) - handle.x_decode(message) - assert handle.values == [1, 2, 3, 4] - - def test_frame_size(self): - """Test that the read fifo queue response can decode.""" - message = TEST_MESSAGE - assert ( - ReadFifoQueueResponse.x_calculateRtuFrameSize(b"\x00\x18" + message) == 16 - ) - assert ReadFifoQueueRequest.x_calculateRtuFrameSize(b"") == 6 - frame = bytes.fromhex("1018000a00046131346662303165a946") - used_len, pdu = FramerRTU(DecodePDU(False)).handleFrame(frame, 0, 0) - assert used_len == len(frame) - assert isinstance(pdu, ReadFifoQueueResponse) - assert pdu.dev_id == 0x10 - assert pdu.values == [0x6131, 0x3466, 0x6230, 0x3165] - - # -----------------------------------------------------------------------# - # File Record - # -----------------------------------------------------------------------# - - def test_file_record_length(self): - """Test file record length generation.""" - record = FileRecord( - file_number=0x01, record_number=0x02, record_data=b"\x00\x01\x02\x04" - ) - assert record.record_length == 0x02 - - def test_file_record_errors(self): - """Test file record length generation.""" - with pytest.raises(ModbusException): - FileRecord(record_length=12, record_data=b"\x00\x01\x02\x04") - with pytest.raises(ModbusException): - FileRecord(record_length=11) - - def test_read_file_record_request_encode(self): - """Test basic bit message encoding/decoding.""" - records = [FileRecord(file_number=0x01, record_number=0x02)] - handle = ReadFileRecordRequest(records=records) - result = handle.x_encode() - assert result == b"\x07\x06\x00\x01\x00\x02\x00\x00" - - def test_read_file_record_request_decode(self): - """Test basic bit message encoding/decoding.""" - # record = FileRecord(file_number=0x04, record_number=0x01, record_length=0x02) - request = b"\x0e\x06\x00\x04\x00\x01\x00\x02\x06\x00\x03\x00\x09\x00\x02" - handle = ReadFileRecordRequest() - handle.x_decode(request) - # assert handle.records[0] == record - assert [ - (rec.file_number, rec.record_number, rec.record_length) - for rec in handle.records - ] == [(4, 1, 2), (3, 9, 2)] - handle.x_decode(b"\x07\x06\x00\x04\x00\x01\x00\x03") - assert handle.records[0].record_length == 3 - assert handle.x_encode() == b"\x07\x06\x00\x04\x00\x01\x00\x03" - - def test_read_file_record_request_frame_size(self): - """Test basic bit message encoding/decoding.""" - request = ( - b"\x00\x00\x0e\x06\x00\x04\x00\x01\x00\x02\x06\x00\x03\x00\x09\x00\x02" - ) - handle = ReadFileRecordRequest() - size = handle.x_calculateRtuFrameSize(request) - assert size == 0x0E + 5 - - async def test_read_file_record_request_datastore_update(self, mock_server_context): - """Test basic bit message encoding/decoding.""" - handle = ReadFileRecordRequest() - result = await handle.datastore_update(mock_server_context(), 0) - assert isinstance(result, ReadFileRecordResponse) - - # -----------------------------------------------------------------------# - # Read File Record Response - # -----------------------------------------------------------------------# - - def test_read_file_record_response_encode(self): - """Test basic bit message encoding/decoding.""" - records = [FileRecord(record_data=b"\x00\x01\x02\x03\x04\x05")] - handle = ReadFileRecordResponse(records) - result = handle.x_encode() - assert result == b"\x08\x07\x06\x00\x01\x02\x03\x04\x05" - - def test_read_file_record_response_decode(self): - """Test basic bit message encoding/decoding.""" - # record1 = FileRecord( - # file_number=0x00, record_number=0x00, record_data=b"\x0d\xfe\x00\x20" - # ) - # record2 = FileRecord( - # file_number=0x00, record_number=0x00, record_data=b"\x33\xcd\x00\x40" - # ) - response = b"\x0c\x05\x06\x0d\xfe\x00\x20\x05\x06\x33\xcd\x00\x40" - handle = ReadFileRecordResponse() - handle.x_decode(response) - - # assert handle.records[0] == record1 - # ssert handle.records[1] == record2 - - def test_read_file_record_response_frame_size(self): - """Test basic bit message encoding/decoding.""" - request = b"\x00\x00\x0c\x05\x06\x0d\xfe\x00\x20\x05\x05\x06\x33\xcd\x00\x40" - handle = ReadFileRecordResponse() - size = handle.x_calculateRtuFrameSize(request) - assert size == 0x0C + 5 - - # -----------------------------------------------------------------------# - # Write File Record Request - # -----------------------------------------------------------------------# - - def test_write_file_record_request_encode(self): - """Test basic bit message encoding/decoding.""" - records = [ - FileRecord( - file_number=0x01, record_number=0x02, record_data=b"\x00\x01\x02\x03" - ) - ] - handle = WriteFileRecordRequest(records) - result = handle.x_encode() - assert result == b"\x0b\x06\x00\x01\x00\x02\x00\x02\x00\x01\x02\x03" - - def test_write_file_record_request_decode(self): - """Test basic bit message encoding/decoding.""" - # record = FileRecord( - # file_number=0x04, - # record_number=0x07, - # record_data=b"\x06\xaf\x04\xbe\x10\x0d", - # ) - request = b"\x0d\x06\x00\x04\x00\x07\x00\x03\x06\xaf\x04\xbe\x10\x0d" - handle = WriteFileRecordRequest() - handle.x_decode(request) - # assert handle.records[0] == record - - def test_write_file_record_request_frame_size(self): - """Test write file record request rtu frame size calculation.""" - request = b"\x00\x00\x0d\x06\x00\x04\x00\x07\x00\x03\x06\xaf\x04\xbe\x10\x0d" - handle = WriteFileRecordRequest() - size = handle.x_calculateRtuFrameSize(request) - assert size == 0x0D + 5 - - async def test_write_file_record_request_datastore_update( - self, mock_server_context - ): - """Test basic bit message encoding/decoding.""" - handle = WriteFileRecordRequest() - result = await handle.datastore_update(mock_server_context(), 0) - assert isinstance(result, WriteFileRecordResponse) - - # -----------------------------------------------------------------------# - # Write File Record Response - # -----------------------------------------------------------------------# - - def test_write_file_record_response_encode(self): - """Test basic bit message encoding/decoding.""" - records = [ - FileRecord( - file_number=0x01, record_number=0x02, record_data=b"\x00\x01\x02\x03" - ) - ] - handle = WriteFileRecordResponse(records) - result = handle.x_encode() - assert result == b"\x0b\x06\x00\x01\x00\x02\x00\x02\x00\x01\x02\x03" - - def test_write_file_record_response_decode(self): - """Test basic bit message encoding/decoding.""" - # record = FileRecord( - # file_number=0x04, - # record_number=0x07, - # record_data=b"\x06\xaf\x04\xbe\x10\x0d", - # ) - request = b"\x0d\x06\x00\x04\x00\x07\x00\x03\x06\xaf\x04\xbe\x10\x0d" - handle = WriteFileRecordResponse() - handle.x_decode(request) - # assert handle.records[0] == record - - def test_read_file_record_request_decode_invalid_byte_count(self): - """Test ReadFileRecordRequest raises ModbusException on oversized byte_count.""" - handle = ReadFileRecordRequest() - with pytest.raises(ModbusException): - handle.x_decode(bytes([0xFF, 0x06, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01])) - - def test_write_file_record_request_decode_invalid_byte_count(self): - """Test WriteFileRecordRequest raises ModbusException on oversized byte_count.""" - handle = WriteFileRecordRequest() - with pytest.raises(ModbusException): - handle.x_decode( - bytes([0xFF, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]) - ) - - def test_read_fifo_queue_response_decode_invalid_count(self): - """Test ReadFifoQueueResponse raises ModbusException on oversized count.""" - handle = ReadFifoQueueResponse() - with pytest.raises(ModbusException): - handle.x_decode(bytes([0x00, 0x00, 0xFF, 0xFF])) - - def test_write_file_record_response_frame_size(self): - """Test write file record response rtu frame size calculation.""" - request = b"\x00\x00\x0d\x06\x00\x04\x00\x07\x00\x03\x06\xaf\x04\xbe\x10\x0d" - handle = WriteFileRecordResponse() - size = handle.x_calculateRtuFrameSize(request) - assert size == 0x0D + 5 diff --git a/test/pdu/test_mei_messages.py b/test/pdu/test_mei_messages.py deleted file mode 100644 index 9f86ca9cf5..0000000000 --- a/test/pdu/test_mei_messages.py +++ /dev/null @@ -1,209 +0,0 @@ -"""MEI Message Test Fixture. - -This fixture tests the functionality of all the -mei based request/response messages: -""" - -from typing import cast - -import pytest - -from pymodbus.constants import DeviceInformation, ExcCodes -from pymodbus.pdu import ExceptionResponse -from pymodbus.pdu.decoders import DecodePDU -from pymodbus.pdu.device import ModbusControlBlock -from pymodbus.pdu.mei_message import ( - ReadDeviceInformationRequest, - ReadDeviceInformationResponse, -) - - -TEST_VERSION = b"v2.1.12" -TEST_MESSAGE = b"\x00\x07Company\x01\x07Product\x02\x07v2.1.12" - - -class TestMeiMessage: - """Unittest for the pymodbus.mei_message module.""" - - # -----------------------------------------------------------------------# - # Read Device Information - # -----------------------------------------------------------------------# - - def test_read_device_information_request_encode(self): - """Test basic bit message encoding/decoding.""" - params = {"read_code": DeviceInformation.BASIC, "object_id": 0x00} - handle = ReadDeviceInformationRequest(**params) - result = handle.x_encode() - assert result == b"\x0e\x01\x00" - assert "ReadDeviceInformationRequest" in str(handle) - - def test_read_device_information_request_decode(self): - """Test basic bit message encoding/decoding.""" - handle = ReadDeviceInformationRequest() - handle.x_decode(b"\x0e\x01\x00") - assert handle.read_code == DeviceInformation.BASIC - assert not handle.object_id - - def test_device_information_mei_type_is_routed(self): - """Test MEI type 0x0E is routed to device identification.""" - pdu = DecodePDU(True).decode(b"\x2b\x0e\x01\x00") - assert isinstance(pdu, ReadDeviceInformationRequest) - - async def test_read_device_information_request(self, mock_server_context): - """Test basic bit message encoding/decoding.""" - context = mock_server_context() - control = ModbusControlBlock() - control.Identity.VendorName = "Company" - control.Identity.ProductCode = "Product" - control.Identity.MajorMinorRevision = TEST_VERSION - control.Identity.update({0x81: ["Test", "Repeated"]}) - - handle = ReadDeviceInformationRequest() - result = await handle.datastore_update(context, 0) - assert isinstance(result, ReadDeviceInformationResponse) - assert result.information[0x00] == "Company" - assert result.information[0x01] == "Product" - assert result.information[0x02] == TEST_VERSION - with pytest.raises(KeyError): - _ = result.information[0x81] - - handle = ReadDeviceInformationRequest( - read_code=DeviceInformation.SPECIFIC, object_id=0x00 - ) - result = await handle.datastore_update(context, 0) - assert cast(ReadDeviceInformationResponse, result).information == { - 0x00: "Company" - } - - handle = ReadDeviceInformationRequest( - read_code=DeviceInformation.EXTENDED, object_id=0x80 - ) - result = await handle.datastore_update(context, 0) - assert cast(ReadDeviceInformationResponse, result).information[0x81] == [ - "Test", - "Repeated", - ] - - async def test_read_device_information_request_error(self, mock_server_context): - """Test basic bit message encoding/decoding.""" - context = mock_server_context() - handle = ReadDeviceInformationRequest() - handle.read_code = -1 - assert (await handle.datastore_update(context, 0)).function_code == 0xAB - handle.read_code = 0x05 - assert (await handle.datastore_update(context, 0)).function_code == 0xAB - handle.read_code = 0x00 - result = await handle.datastore_update(context, 0) - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - handle.object_id = -1 - assert (await handle.datastore_update(context, 0)).function_code == 0xAB - handle.object_id = 0x100 - assert (await handle.datastore_update(context, 0)).function_code == 0xAB - handle = ReadDeviceInformationRequest( - read_code=DeviceInformation.SPECIFIC, object_id=0x54 - ) - result = await handle.datastore_update(context, 0) - assert result.exception_code == ExcCodes.ILLEGAL_ADDRESS - ModbusControlBlock().Identity[0xFE] = "" - handle = ReadDeviceInformationRequest( - read_code=DeviceInformation.SPECIFIC, object_id=0xFE - ) - result = await handle.datastore_update(context, 0) - assert result.exception_code == ExcCodes.ILLEGAL_ADDRESS - - def test_read_device_information_calc1(self): - """Test x_calculateRtuFrameSize, short buffer.""" - handle = ReadDeviceInformationResponse() - assert handle.x_calculateRtuFrameSize(b"\x0e\x01\x83") == 999 - assert ( - handle.x_calculateRtuFrameSize(b"\x0e\x01\x83\x00\x00\x03\x01\x03") == 998 - ) - - def test_read_device_information_sub_fc(self): - """Test x_calculateRtuFrameSize, short buffer.""" - handle = ReadDeviceInformationResponse() - assert handle.decode_sub_function_code(b"\x0e\x01\x83") == 0x83 - handle2 = ReadDeviceInformationRequest() - assert handle2.decode_sub_function_code(b"\x0e\x01\x83") == 0x83 - - def test_read_device_information_encode(self): - """Test that the read fifo queue response can encode.""" - message = b"\x0e\x01\x83\x00\x00\x03" - message += TEST_MESSAGE - dataset = { - 0x00: "Company", - 0x01: "Product", - 0x02: TEST_VERSION, - } - handle = ReadDeviceInformationResponse( - read_code=DeviceInformation.BASIC, information=dataset - ) - result = handle.x_encode() - assert result == message - assert "ReadDeviceInformationResponse" in str(handle) - - dataset = { - 0x00: "Company", - 0x01: "Product", - 0x02: TEST_VERSION, - 0x81: ["Test", "Repeated"], - 0x82: ExceptionResponse(function_code=0x01), - } - message = b"\x0e\x03\x83\x00\x00\x06" - message += TEST_MESSAGE - message += b"\x81\x04Test\x81\x08Repeated\x82\x01\x00" - handle = ReadDeviceInformationResponse( - read_code=DeviceInformation.EXTENDED, information=dataset - ) - result = handle.x_encode() - assert result == message - - def test_read_device_information_encode_long(self): - """Test that the read fifo queue response can encode.""" - longstring = ( - "Lorem ipsum dolor sit amet, consectetur adipiscing " - "elit. Vivamus rhoncus massa turpis, sit amet ultrices" - " orci semper ut. Aliquam tristique sapien in lacus " - "pharetra, in convallis nunc consectetur. Nunc velit " - "elit, vehicula tempus tempus sed. " - ) - - message = b"\x0e\x01\x83\xff\x80\x03" - message += TEST_MESSAGE - dataset = { - 0x00: "Company", - 0x01: "Product", - 0x02: TEST_VERSION, - 0x80: longstring, - } - handle = ReadDeviceInformationResponse( - read_code=DeviceInformation.BASIC, information=dataset - ) - result = handle.x_encode() - assert result == message - assert "ReadDeviceInformationResponse" in str(handle) - - def test_read_device_information_decode(self): - """Test that the read device information response can decode.""" - message = b"\x0e\x01\x01\x00\x00\x05" - message += TEST_MESSAGE - message += b"\x81\x04Test\x81\x08Repeated\x81\x07Another" - handle = ReadDeviceInformationResponse(read_code=0x00, information={}) - handle.x_decode(message) - assert handle.read_code == DeviceInformation.BASIC - assert handle.conformity == 0x01 - assert handle.information[0x00] == b"Company" - assert handle.information[0x01] == b"Product" - assert handle.information[0x02] == TEST_VERSION - assert handle.information[0x81] == [b"Test", b"Repeated", b"Another"] - - def test_frame_size(self): - """Test that the read device information response can decode.""" - message = ( - b"\x04\x2b\x0e\x01\x81\x00\x01\x01\x00\x06\x66\x6f\x6f\x62\x61\x72\xd7\x3b" - ) - result = ReadDeviceInformationResponse.x_calculateRtuFrameSize(message) - assert result == 18 - message = b"\x00\x2b\x0e\x02\x00\x4d\x47" - result = ReadDeviceInformationRequest.x_calculateRtuFrameSize(message) - assert result == 7 diff --git a/test/pdu/test_other_messages.py b/test/pdu/test_other_messages.py deleted file mode 100644 index e1c24f65ab..0000000000 --- a/test/pdu/test_other_messages.py +++ /dev/null @@ -1,185 +0,0 @@ -"""Test other messages.""" - -from typing import cast -from unittest import mock - -import pytest - -import pymodbus.pdu.other_message as pymodbus_message -from pymodbus.exceptions import ModbusIOException - - -class TestOtherMessage: - """Unittest for the pymodbus.other_message module.""" - - requests = [ - pymodbus_message.ReadExceptionStatusRequest, - pymodbus_message.GetCommEventCounterRequest, - pymodbus_message.GetCommEventLogRequest, - pymodbus_message.ReportDeviceIdRequest, - ] - - responses = [ - pymodbus_message.ReadExceptionStatusResponse(0x12), - pymodbus_message.GetCommEventCounterResponse(0x12), - pymodbus_message.GetCommEventLogResponse, - pymodbus_message.ReportDeviceIdResponse(b"\x12"), - ] - - def test_other_messages_to_string(self): - """Test other messages to string.""" - for message in self.requests: - assert str(message) - for message2 in self.responses: - assert str(message2) - - async def test_read_exception_status(self, mock_server_context): - """Test read exception status.""" - context = mock_server_context() - request = pymodbus_message.ReadExceptionStatusRequest() - request.x_decode(b"\x12") - assert not request.x_encode() - assert (await request.datastore_update(context, 0)).function_code == 0x07 - - response = pymodbus_message.ReadExceptionStatusResponse(status=0x12) - assert response.x_encode() == b"\x12" - response.x_decode(b"\x12") - assert response.status == 0x12 - - async def test_get_comm_event_counter(self, mock_server_context): - """Test get comm event counter.""" - context = mock_server_context() - request = pymodbus_message.GetCommEventCounterRequest() - request.x_decode(b"\x12") - assert not request.x_encode() - assert (await request.datastore_update(context, 0)).function_code == 0x0B - - response = pymodbus_message.GetCommEventCounterResponse(count=0x12) - assert response.x_encode() == b"\x00\x00\x00\x12" - response.x_decode(b"\x00\x00\x00\x12") - assert response.status - assert response.count == 0x12 - - response.status = False - assert response.x_encode() == b"\xff\xff\x00\x12" - - async def test_get_comm_event_log(self, mock_server_context): - """Test get comm event log.""" - context = mock_server_context() - request = pymodbus_message.GetCommEventLogRequest() - request.x_decode(b"\x12") - assert not request.x_encode() - assert (await request.datastore_update(context, 0)).function_code == 0x0C - - response = pymodbus_message.GetCommEventLogResponse() - assert response.x_encode() == b"\x06\x00\x00\x00\x00\x00\x00" - response.x_decode(b"\x06\x00\x00\x00\x12\x00\x12") - assert response.status - assert response.message_count == 0x12 - assert response.event_count == 0x12 - assert not response.events - - response.status = False - assert response.x_encode() == b"\x06\xff\xff\x00\x12\x00\x12" - - def test_get_comm_event_log_with_events(self): - """Test get comm event log with events.""" - response = pymodbus_message.GetCommEventLogResponse(events=[0x12, 0x34, 0x56]) - assert response.x_encode() == b"\x09\x00\x00\x00\x00\x00\x00\x12\x34\x56" - response.x_decode(b"\x09\x00\x00\x00\x12\x00\x12\x12\x34\x56") - assert response.status - assert response.message_count == 0x12 - assert response.event_count == 0x12 - assert response.events == [0x12, 0x34, 0x56] - - async def test_report_device_id_request(self, mock_server_context): - """Test report device_id request.""" - context = mock_server_context() - with mock.patch("pymodbus.pdu.other_message.DeviceInformationFactory") as dif: - # First test regular identity strings - identity = { - 0x00: "VN", # VendorName - 0x01: "PC", # ProductCode - 0x02: "REV", # MajorMinorRevision - 0x03: "VU", # VendorUrl - 0x04: "PN", # ProductName - 0x05: "MN", # ModelName - 0x06: "UAN", # UserApplicationName - 0x07: "RA", # reserved - 0x08: "RB", # reserved - } - dif.get.return_value = identity - expected_identity = "-".join(identity.values()).encode() - - request = pymodbus_message.ReportDeviceIdRequest() - response = await request.datastore_update(context, 1) - assert ( - cast(pymodbus_message.ReportDeviceIdResponse, response).identifier - == expected_identity - ) - - # Change to byte strings and test again (final result should be the same) - identity2 = { - 0x00: b"VN", # VendorName - 0x01: b"PC", # ProductCode - 0x02: b"REV", # MajorMinorRevision - 0x03: b"VU", # VendorUrl - 0x04: b"PN", # ProductName - 0x05: b"MN", # ModelName - 0x06: b"UAN", # UserApplicationName - 0x07: b"RA", # reserved - 0x08: b"RB", # reserved - } - dif.get.return_value = identity2 - - request = pymodbus_message.ReportDeviceIdRequest() - response = await request.datastore_update(context, 0) - assert ( - cast(pymodbus_message.ReportDeviceIdResponse, response).identifier - == expected_identity - ) - - async def test_report_device_id(self, mock_server_context): - """Test report device_id.""" - context = mock_server_context() - with mock.patch("pymodbus.pdu.other_message.DeviceInformationFactory") as dif: - dif.get.return_value = {} - request = pymodbus_message.ReportDeviceIdRequest() - request.x_decode(b"\x12") - assert not request.x_encode() - assert (await request.datastore_update(context, 0)).function_code == 0x11 - - response = pymodbus_message.ReportDeviceIdResponse( - cast( - pymodbus_message.ReportDeviceIdResponse, - await request.datastore_update(context, 0), - ).identifier, - True, - ) - - assert response.x_encode() == b"\tPymodbus\xff" - response.x_decode(b"\tPymodbus\xff") - assert response.status - assert response.identifier == b"Pymodbus" - response.x_decode(b"\x03\x12\x00\x00") - assert not response.status - assert response.identifier == b"\x12\x00" - - response.status = False - assert response.x_encode() == b"\x03\x12\x00\x00" - - def test_report_device_id_response_roundtrip(self): - """Test decode( x_encode()) keeps identifier and status unchanged.""" - for identifier, status in ((b"Pymodbus", True), (b"\x12", False)): - sent = pymodbus_message.ReportDeviceIdResponse(identifier, status) - received = pymodbus_message.ReportDeviceIdResponse() - received.x_decode(sent.x_encode()) - assert received.identifier == identifier - assert received.status == status - - def test_report_device_id_response_invalid_byte_count(self): - """Test byte count pointing outside the received data raises.""" - response = pymodbus_message.ReportDeviceIdResponse() - for frame in (b"\x00\x12\xff", b"\x04\x12\xff"): - with pytest.raises(ModbusIOException): - response.x_decode(frame) diff --git a/test/pdu/test_pdu.py b/test/pdu/test_pdu.py index a5d2fb2632..eb7987dc61 100644 --- a/test/pdu/test_pdu.py +++ b/test/pdu/test_pdu.py @@ -1,549 +1,224 @@ """Test pdu.""" +from copy import copy from typing import Any +from unittest import mock import pytest -import pymodbus.pdu.bit_message as bit_msg -import pymodbus.pdu.diag_message as diag_msg -import pymodbus.pdu.file_message as file_msg -import pymodbus.pdu.mei_message as mei_msg -import pymodbus.pdu.other_message as o_msg -import pymodbus.pdu.register_message as reg_msg -from pymodbus.constants import ModbusStatus +import pymodbus.pdu.data_message as reg_msg +from pymodbus.constants import ExcCodes from pymodbus.exceptions import ModbusIOException from pymodbus.pdu import ( DecodePDU, - ExceptionResponse, - ModbusPDU, + ModbusPdu, + PDUexception, + pack_bitstring, + unpack_bitstring, ) -from pymodbus.pdu.device import ModbusControlBlock -from pymodbus.pdu.utils import pack_bitstring, unpack_bitstring +from pymodbus.pdu.data_message import PDUreadCoils +from pymodbus.pdu.diag_message import PDUreadDeviceInformation -class TestPdu: +class TestPdu_alone: """Test modbus PDU.""" - exception = ExceptionResponse(1, 1, 0, 0) - - async def test_error_methods(self): - """Test all error methods.""" - result = self.exception.x_encode() - assert result == b"\x01" - DecodePDU(False).decode(b"\x81" + result) - assert self.exception.exception_code == 1 - self.exception.x_decode(b"") - - async def test_pdu_id(self, mockPDU): - """Test set illegal pdu id.""" - with pytest.raises(ModbusIOException) as exc_info: - mockPDU(256, transaction_id=0x42) - assert exc_info.value.dev_id == 256 - assert exc_info.value.transaction_id == 0x42 - - async def test_is_error(self): - """Test is_error.""" - assert self.exception.isError() - - requests: list[tuple[type[ModbusPDU], tuple[()], dict[str, Any], bytes]] = [ - ( - bit_msg.ReadCoilsRequest, - (), - {"address": 117, "count": 3}, - b"\x01\x00\x75\x00\x03", - ), - ( - bit_msg.ReadDiscreteInputsRequest, - (), - {"address": 117, "count": 3}, - b"\x02\x00\x75\x00\x03", - ), - ( - bit_msg.WriteSingleCoilRequest, - (), - {"address": 117, "bits": [True]}, - b"\x05\x00\x75\xff\x00", - ), - ( - bit_msg.WriteMultipleCoilsRequest, - (), - {"address": 117, "bits": [True, False, True]}, - b"\x0f\x00\x75\x00\x03\x01\x05", - ), - (diag_msg.DiagnosticBase, (), {"message": None}, b"\x08\x27\x0f"), - (diag_msg.DiagnosticBase, (), {"message": 0x1010}, b"\x08\x27\x0f\x10\x10"), - ( - diag_msg.ReturnQueryDataRequest, - (), - {"message": b"\x10\x01"}, - b"\x08\x00\x00\x10\x01", - ), - ( - diag_msg.RestartCommunicationsOptionRequest, - (), - {"message": ModbusStatus.ON}, - b"\x08\x00\x01\xff\x00", - ), - ( - diag_msg.ReturnDiagnosticRegisterRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x02\x10\x10", - ), - ( - diag_msg.ChangeAsciiInputDelimiterRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x03\x10\x10", - ), - (diag_msg.ForceListenOnlyModeRequest, (), {}, b"\x08\x00\x04\x00\x00"), - (diag_msg.ClearCountersRequest, (), {"message": 0x1010}, b"\x08\x00\n\x10\x10"), - ( - diag_msg.ReturnBusMessageCountRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x0b\x10\x10", - ), - ( - diag_msg.ReturnBusCommunicationErrorCountRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x0c\x10\x10", - ), - ( - diag_msg.ReturnBusExceptionErrorCountRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x0d\x10\x10", - ), - ( - diag_msg.ReturnDeviceMessageCountRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x0e\x10\x10", - ), - ( - diag_msg.ReturnDeviceNoResponseCountRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x0f\x10\x10", - ), - ( - diag_msg.ReturnDeviceNAKCountRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x10\x10\x10", - ), - ( - diag_msg.ReturnDeviceBusyCountRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x11\x10\x10", - ), - ( - diag_msg.ReturnDeviceBusCharacterOverrunCountRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x12\x10\x10", - ), - ( - diag_msg.ReturnIopOverrunCountRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x13\x10\x10", - ), - ( - diag_msg.ClearOverrunCountRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x14\x10\x10", - ), - ( - diag_msg.GetClearModbusPlusRequest, - (), - {"message": 0x1010}, - b"\x08\x00\x15\x10\x10", - ), - ( - file_msg.ReadFileRecordRequest, - (), - {"records": [file_msg.FileRecord(), file_msg.FileRecord()]}, - b"\x14\x0e\x06\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00", - ), - ( - file_msg.WriteFileRecordRequest, - (), - {"records": [file_msg.FileRecord(), file_msg.FileRecord()]}, - b"\x15\x0e\x06\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00", - ), - (file_msg.ReadFifoQueueRequest, (), {"address": 117}, b"\x18\x00\x75"), - ( - mei_msg.ReadDeviceInformationRequest, - (), - {"read_code": 0x17, "object_id": 0x29}, - b"\x2b\x0e\x17\x29", - ), - (o_msg.ReadExceptionStatusRequest, (), {}, b"\x07"), - (o_msg.GetCommEventCounterRequest, (), {}, b"\x0b"), - (o_msg.GetCommEventLogRequest, (), {}, b"\x0c"), - (o_msg.ReportDeviceIdRequest, (), {}, b"\x11"), - ( - reg_msg.ReadHoldingRegistersRequest, - (), - {"address": 117, "count": 3}, - b"\x03\x00\x75\x00\x03", - ), - ( - reg_msg.ReadInputRegistersRequest, - (), - {"address": 117, "count": 3}, - b"\x04\x00\x75\x00\x03", - ), - ( - reg_msg.ReadWriteMultipleRegistersRequest, - (), - { - "read_address": 17, - "read_count": 2, - "write_address": 25, - "write_registers": [111, 112], - }, - b"\x17\x00\x11\x00\x02\x00\x19\x00\x02\x04\x00\x6f\x00\x70", - ), - ( - reg_msg.WriteMultipleRegistersRequest, - (), - {"address": 117, "registers": [111, 121, 131]}, - b"\x10\x00\x75\x00\x03\x06\x00\x6f\x00\x79\x00\x83", - ), - ( - reg_msg.WriteSingleRegisterRequest, - (), - {"address": 117, "registers": [112]}, - b"\x06\x00\x75\x00\x70", - ), - ( - reg_msg.MaskWriteRegisterRequest, - (), - {"address": 0x0104, "and_mask": 0xE1D2, "or_mask": 0x1234}, - b"\x16\x01\x04\xe1\xd2\x12\x34", - ), - ] - - responses: list[tuple[type[ModbusPDU], tuple[()], dict[str, Any], bytes]] = [ - ( - bit_msg.ReadCoilsResponse, - (), - {"bits": [True, True] + [False] * 6, "address": 17}, - b"\x01\x01\x03", - ), - ( - bit_msg.ReadDiscreteInputsResponse, - (), - {"bits": [True, True], "address": 17}, - b"\x02\x01\x03", - ), - ( - bit_msg.WriteSingleCoilResponse, - (), - {"address": 117, "bits": [True]}, - b"\x05\x00\x75\xff\x00", - ), - ( - bit_msg.WriteMultipleCoilsResponse, - (), - {"address": 117, "count": 3}, - b"\x0f\x00\x75\x00\x03", - ), - (diag_msg.DiagnosticBase, (), {"message": None}, b"\x08\x27\x0f"), - (diag_msg.DiagnosticBase, (), {"message": 0x1010}, b"\x08\x27\x0f\x10\x10"), - ( - diag_msg.ReturnQueryDataResponse, - (), - {"message": b"AB"}, - b"\x08\x00\x00\x41\x42", - ), - ( - diag_msg.RestartCommunicationsOptionResponse, - (), - {"message": ModbusStatus.ON}, - b"\x08\x00\x01\xff\x00", - ), - ( - diag_msg.ReturnDiagnosticRegisterResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x02\x10\x10", - ), - ( - diag_msg.ChangeAsciiInputDelimiterResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x03\x10\x10", - ), - (diag_msg.ForceListenOnlyModeResponse, (), {}, b"\x08\x00\x04"), - ( - diag_msg.ClearCountersResponse, - (), - {"message": 0x1010}, - b"\x08\x00\n\x10\x10", - ), - ( - diag_msg.ReturnBusMessageCountResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x0b\x10\x10", - ), - ( - diag_msg.ReturnBusCommunicationErrorCountResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x0c\x10\x10", - ), - ( - diag_msg.ReturnBusExceptionErrorCountResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x0d\x10\x10", - ), - ( - diag_msg.ReturnDeviceMessageCountResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x0e\x10\x10", - ), - ( - diag_msg.ReturnDeviceNoResponseCountResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x0f\x10\x10", - ), - ( - diag_msg.ReturnDeviceNAKCountResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x10\x10\x10", - ), - ( - diag_msg.ReturnDeviceBusyCountResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x11\x10\x10", - ), - ( - diag_msg.ReturnDeviceBusCharacterOverrunCountResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x12\x10\x10", - ), - ( - diag_msg.ReturnIopOverrunCountResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x13\x10\x10", - ), - ( - diag_msg.ClearOverrunCountResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x14\x10\x10", - ), - ( - diag_msg.GetClearModbusPlusResponse, - (), - {"message": 0x1010}, - b"\x08\x00\x15\x10\x10", - ), - ( - file_msg.ReadFileRecordResponse, - (), - {"records": [file_msg.FileRecord(), file_msg.FileRecord()]}, - b"\x14\x04\x01\x06\x01\x06", - ), - ( - file_msg.WriteFileRecordResponse, - (), - {"records": [file_msg.FileRecord(), file_msg.FileRecord()]}, - b"\x15\x0e\x06\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00", - ), - ( - file_msg.ReadFifoQueueResponse, - (), - {"values": [123, 456]}, - b"\x18\x00\x06\x00\x02\x00{\x01\xc8", - ), - ( - mei_msg.ReadDeviceInformationResponse, - (), - {"read_code": 0x17}, - b"\x2b\x0e\x17\x83\x00\x00\x00", - ), - (o_msg.ReadExceptionStatusResponse, (), {"status": 0x23}, b"\x07\x23"), - ( - o_msg.GetCommEventCounterResponse, - (), - {"count": 123}, - b"\x0b\x00\x00\x00\x7b", - ), - ( - o_msg.GetCommEventLogResponse, - (), - {"status": True, "message_count": 12, "event_count": 7, "events": [12, 14]}, - b"\x0c\x08\x00\x00\x00\x07\x00\x0c\x0c\x0e", - ), - ( - o_msg.ReportDeviceIdResponse, - (), - {"identifier": b"\x12", "status": True}, - b"\x11\x02\x12\xff", - ), - ( - reg_msg.ReadHoldingRegistersResponse, - (), - {"registers": [3, 17]}, - b"\x03\x04\x00\x03\x00\x11", - ), - ( - reg_msg.ReadInputRegistersResponse, - (), - {"registers": [3, 17]}, - b"\x04\x04\x00\x03\x00\x11", - ), - ( - reg_msg.ReadWriteMultipleRegistersResponse, - (), - {"registers": [1, 2]}, - b"\x17\x04\x00\x01\x00\x02", - ), - ( - reg_msg.WriteSingleRegisterResponse, - (), - {"address": 117, "registers": [112]}, - b"\x06\x00\x75\x00\x70", - ), - ( - reg_msg.WriteMultipleRegistersResponse, - (), - {"address": 117, "count": 3}, - b"\x10\x00\x75\x00\x03", - ), - ( - reg_msg.MaskWriteRegisterResponse, - (), - {"address": 0x0104, "and_mask": 0xE1D2, "or_mask": 0x1234}, - b"\x16\x01\x04\xe1\xd2\x12\x34", - ), - ] - - @pytest.mark.parametrize(("pdutype", "args", "kwargs", "frame"), requests) - @pytest.mark.usefixtures("kwargs", "args", "frame") - def test_pdu_instance(self, pdutype): - """Test that all PDU types can be created.""" - pdu = pdutype() - assert pdu - @pytest.mark.parametrize( - ("pdutype", "args", "kwargs", "frame"), requests + responses + "is_request", + [True, False], ) - @pytest.mark.usefixtures("frame", "args") - def test_pdu_instance_args(self, pdutype, kwargs): - """Test that all PDU types can be created.""" - pdu = pdutype(**kwargs) - assert pdu - assert pdutype.__name__ in str(pdu) - @pytest.mark.parametrize( - ("pdutype", "args", "kwargs", "frame"), requests + responses + ("dev_id", "tid", "result"), + [ + (0, 0, True), + (-1, 0, False), + (0, -1, False), + (300, 0, False), + (0, 66000, False), + ], ) - @pytest.mark.usefixtures("frame", "args") - def test_pdu_instance_extras(self, pdutype, kwargs): - """Test that all PDU types can be created.""" - tid = 9112 - dev_id = 63 - pdu = pdutype(transaction_id=tid, dev_id=dev_id, **kwargs) - assert pdu - assert str(pdu) - assert pdu.dev_id == dev_id - assert pdu.transaction_id == tid - assert pdu.function_code > 0 + def test_pdu_init(self, is_request, dev_id, tid, result): + """Test ModbusPdu init.""" + if result: + ModbusPdu(is_request, dev_id, tid) + else: + with pytest.raises(ModbusIOException): + ModbusPdu(is_request, dev_id, tid) - def test_pdu_register_as_byte(self): - """Test verify functions.""" - registers = [int.from_bytes(b"ab", "big"), int.from_bytes(b"cd", "big")] - # NOT ALLOWED, NO conversion. - req = reg_msg.ReadHoldingRegistersRequest( - address=117, registers=registers, count=3 + async def test_pdu_methods(self): + """Test ModbusPdu methods.""" + pdu = ModbusPdu(True, 1, 117) + assert not pdu.isError() + x_str = str(pdu) + for x in ( + ModbusPdu.__name__, + "dev_id=1,", + "function_code=-1,", + "transaction_id=117", + ): + assert x in x_str + assert pdu.decode_sub_function_code(b"") == -1 + assert pdu.calculatePduSize(b"") == 2 + pdu.function_code = 7 + assert pdu.preamble() == b"\x01\x07" + pdu.from_bytes(b"\x09\x05") + assert not pdu.to_bytes() + assert pdu.dev_id == 9 + assert pdu.function_code == 5 # type: ignore[comparison-overlap] + x = await pdu.build_response( + mock.AsyncMock(return_value=[0]), mock.AsyncMock(return_value=0) ) - assert len(req.registers) == 2 - assert req.registers[0] == 24930 - assert req.registers[1] == 25444 + assert isinstance(x, PDUexception) + assert x.dev_id == 9 + assert x.function_code == 5 | 0x80 + assert x.exception_code == ExcCodes.DEVICE_BUSY - def test_pdu_verify_address(self): - """Test verify functions.""" - req = reg_msg.ReadHoldingRegistersRequest(address=10, count=3) - req.address = -1 - with pytest.raises(ValueError): # noqa: PT011 - req.verifyAddress() - req.address = 66000 - with pytest.raises(ValueError): # noqa: PT011 - req.verifyAddress() + async def test_PDUexception(self): + """Ensure that PDUexception is correct.""" + pdu = PDUexception(2, 0x01, 0x02) + assert pdu.dev_id == 2 + assert pdu.function_code == 0x81 + assert pdu.exception_code == 0x02 + assert pdu.isError() + assert not pdu.calculatePduSize(b"\x00\x81") + assert pdu.to_bytes() == b"\x02\x81\x02" + assert not pdu.from_bytes(b"\x03\x84\x04") + assert pdu.dev_id == 2 + assert pdu.function_code == 0x84 + assert pdu.exception_code == 0x04 + assert pdu.calculatePduSize(b"\x01\x81\x05") == 3 + x = await pdu.build_response( + mock.AsyncMock(return_value=[0]), mock.AsyncMock(return_value=0) + ) + assert isinstance(x, PDUexception) + assert x.exception_code == ExcCodes.ILLEGAL_FUNCTION + x_str = str(pdu) + for x in ("PDUexception", "dev_id", "function_code", "transaction_id"): + assert x in x_str - def test_pdu_verify_count(self): - """Test verify functions.""" - req = reg_msg.ReadHoldingRegistersRequest(address=2, count=0) - req.count = 0 - with pytest.raises(ValueError): # noqa: PT011 - req.verifyCount(100) - req.count = 101 - with pytest.raises(ValueError): # noqa: PT011 - req.verifyCount(100) - with pytest.raises(ValueError): # noqa: PT011 - req.verifyCount(100, count=0) + @pytest.mark.parametrize("is_request", [True, False]) + def test_decoder(self, is_request): + """Test decoder.""" + assert is_request == DecodePDU(is_request).is_server @pytest.mark.parametrize( - ("pdutype", "args", "kwargs", "frame"), requests + responses + ("msg", "result"), + [ + (b"\x09\x82\x01", PDUexception), + (b"\x09\x01\x03", PDUreadCoils), + (b"\x01\x2b\x0e\x01\x02", PDUreadDeviceInformation), + (b"\x09\x79\x01", None), + (b"\x09\x79", None), + (b"\x08\x00\xf0\xf0\x00", None), + ], ) - @pytest.mark.usefixtures("args") - def test_pdu_instance_encode(self, pdutype, kwargs, frame): - """Test that all PDU types can be created.""" - pdu = pdutype(**kwargs) - res_frame = pdutype.function_code.to_bytes(1, "big") + pdu.x_encode() - assert res_frame == frame + def test_decoder_lookup(self, msg, result): + """Test decoder.""" + if result: + assert DecodePDU._lookupPduClass(msg) == result + else: + assert not DecodePDU._lookupPduClass(msg) - @pytest.mark.parametrize( - ("pdutype", "args", "kwargs", "frame"), requests + responses - ) - @pytest.mark.usefixtures("args") - def test_pdu_decode(self, pdutype, kwargs, frame): - """Test pdu decode.""" - pdu = pdutype(**kwargs) - pdu.x_decode(frame[1:]) + @pytest.mark.parametrize("is_request", [True, False]) + def test_decoder_methods(self, is_request): + """Test decoder.""" + kwargs: dict[str, Any] + if is_request: + kwargs = {"address": 117, "count": 3} + msg = b"\x01\x01\x00\x75\x00\x03" + else: + kwargs = {"bits": [True, True] + [False] * 6} + msg = b"\x01\x01\x01\x03" + with pytest.raises(ModbusIOException): + DecodePDU(is_request).decode(b"") + with pytest.raises(ModbusIOException): + DecodePDU(is_request).decode(b"\x01\x79") + with pytest.raises(ModbusIOException): + DecodePDU(is_request).decode(b"\x01\x01\x01") + assert isinstance(DecodePDU(is_request).decode(msg), PDUreadCoils) + assert isinstance(DecodePDU(is_request).decode(b"\x01\x81\x02"), PDUexception) - @pytest.mark.parametrize(("pdutype", "args", "kwargs", "frame"), requests) - @pytest.mark.usefixtures("frame", "args") - async def test_pdu_datastore(self, pdutype, kwargs, mock_server_context): - """Test that all PDU types can be created.""" - control = ModbusControlBlock() - try: - pdu = pdutype(**kwargs) - assert await pdu.datastore_update(mock_server_context(), 1) - finally: - control.Delimiter = b"\n" + x_msg = DecodePDU(is_request).encode(PDUreadCoils(is_request, 1, **kwargs)) + assert x_msg == msg + assert len(msg) == DecodePDU(is_request).calculatePduSize(msg) + assert DecodePDU(is_request).calculatePduSize(b"\x01\x79") == 0 + assert DecodePDU(is_request).calculatePduSize(b"\x01\x01\x01") == 0 + assert DecodePDU(is_request).calculatePduSize(b"\x01\x01\x01") == 0 + assert DecodePDU(is_request).calculatePduSize(b"\x01\x81") == 0 + + @pytest.mark.parametrize(("frame"), [b"", b"\x01", b"NO FRAME"]) + def test_decoder_bad_frame(self, frame): + """Test lookup bad frames.""" + with pytest.raises(ModbusIOException): + DecodePDU(True).decode(frame) + + @pytest.mark.parametrize("pack", ["pack", "pack8", "unpack"]) @pytest.mark.parametrize( - ("bytestream", "bitlist"), + ("pack_run", "bytestream", "bitlist", "padding"), [ - (b"\x01\x00", [True] + [False] * 15), - (b"\x00\x80", [False] * 15 + [True]), - (b"\x00\x01", [False] * 8 + [True] + [False] * 7), - (b"\x01\x80", [True] + [False] * 14 + [True]), - (b"\x00\x05", [False] * 8 + [True, False, True] + [False] * 5), - (b"\x01\x05", [True] + [False] * 7 + [True, False, True] + [False] * 5), - ( + ( # 0 + 1, + b"\x01", + [True], + 7, + ), + ( # 1 + 1, + b"\x05", + [True, False, True], + 5, + ), + ( # 2 + 2, + b"\x01\x00", + [True] + [False] * 15, + 0, + ), + ( # 3 + 2, + b"\x01\x00", + [True], + 15, + ), + ( # 4 + 3, + b"\x00\x80", + [False] * 15 + [True], + 0, + ), + ( # 5 + 3, + b"\x00\x01", + [False] * 8 + [True] + [False] * 7, + 0, + ), + ( # 6 + 3, + b"\x01\x80", + [True] + [False] * 14 + [True], + 0, + ), + ( # 7 + 3, + b"\x00\x05", + [False] * 8 + [True, False, True] + [False] * 5, + 0, + ), + ( # 8 + 3, + b"\x01\x05", + [True] + [False] * 7 + [True, False, True] + [False] * 5, + 0, + ), + ( # 9 + 3, b"\x81\x05", [True] + [False] * 6 + [True, True, False, True] + [False] * 5, + 0, ), - ( + ( # 10 + 3, b"\x00\x01\x81\x05", [False] * 8 + [True] @@ -552,13 +227,34 @@ async def test_pdu_datastore(self, pdutype, kwargs, mock_server_context): + [False] * 6 + [True, True, False, True] + [False] * 5, + 0, + ), + ( # 11 + 3, + b"\x00\x01", + [False] * 8 + [True], + 7, + ), + ( # 12 + 3, + b"\x00\x05", + [False] * 8 + [True, False, True], + 5, ), - (b"\x01\x00", [True]), - (b"\x00\x01", [False] * 8 + [True]), - (b"\x00\x05", [False] * 8 + [True, False, True]), - (b"\x01\x05", [True] + [False] * 7 + [True, False, True]), - (b"\x81\x05", [True] + [False] * 6 + [True, True, False, True]), - ( + ( # 13 + 3, + b"\x01\x05", + [True] + [False] * 7 + [True, False, True], + 5, + ), + ( # 14 + 3, + b"\x81\x05", + [True] + [False] * 6 + [True, True, False, True], + 5, + ), + ( # 15 + 3, b"\x00\x01\x81\x05", [False] * 8 + [True] @@ -566,78 +262,219 @@ async def test_pdu_datastore(self, pdutype, kwargs, mock_server_context): + [True] + [False] * 6 + [True, True, False, True], + 5, ), ], ) - def test_bit_packing(self, bytestream, bitlist): + def test_bit_packing(self, pack, bytestream, pack_run, bitlist, padding): """Test all string <=> bit packing functions.""" - assert pack_bitstring(bitlist, align_byte=False) == bytestream + original = copy(bitlist) + match pack: + case "pack": + if pack_run in (2, 3): + assert pack_bitstring(bitlist, align_byte=False) == bytestream + case "pack8": + if pack_run in (1, 3): + original = copy(bitlist) + assert pack_bitstring(bitlist, align_byte=True) == bytestream + assert original == bitlist + case "unpack": + original_b = copy(bytestream) + assert unpack_bitstring(bytestream) == bitlist + [False] * padding + assert original_b == bytestream + case _: # pragma: no cover + raise TypeError("Test case not handled!") + assert original == bitlist + + def test_pdu_register_as_byte(self): + """Test verify functions.""" + registers = [int.from_bytes(b"ab", "big"), int.from_bytes(b"cd", "big")] + # NOT ALLOWED, NO conversion. + req = reg_msg.PDUreadHoldingRegisters( + False, 0, address=117, registers=registers, count=3 + ) + assert len(req.registers) == 2 + assert req.registers[0] == 24930 + assert req.registers[1] == 25444 + + +class TestPdus: + """Test modbus PDU.""" @pytest.mark.parametrize( - ("bytestream", "bitlist"), - [ - (b"\x01", [True]), - (b"\x00\x01", [False] * 8 + [True]), - (b"\x05", [True, False, True]), - (b"\x01\x05", [True] + [False] * 7 + [True, False, True]), - ], + "cases", + ["id", "params"], ) - def test_bit_packing8(self, bytestream, bitlist): - """Test all string <=> bit packing functions.""" - assert pack_bitstring(bitlist) == bytestream + async def test_init(self, cases, paramPDU): + """Ensure that __init__ runs correctly.""" + pdu, _api, params, _msg, params2, _msg = paramPDU + match cases: + case "id": + with pytest.raises(TypeError): + pdu() + with pytest.raises(TypeError): + pdu(True) + assert pdu(False, 0) + assert pdu(True, 1) + with pytest.raises(ModbusIOException): + pdu(True, -1) + with pytest.raises(ModbusIOException): + pdu(True, 256) + case "params": + assert pdu(False, 1, **params) + assert pdu(False, 1, **params2) + assert pdu(False, 1, **(params | params2)) + dev_id = 63 + params_comb = params | { + "transaction_id": 9112, + } + pdu_obj = pdu(True, dev_id, **params_comb) + assert pdu_obj + assert str(pdu_obj) + assert 0 < pdu.function_code < 0x80 + for key, value in params_comb.items(): + assert getattr(pdu_obj, key) == value + case _: # pragma: no cover + raise TypeError("Test case not handled!") @pytest.mark.parametrize( - ("align_byte", "expected"), - [ - (True, b"\x05"), - (False, b"\x05\x00"), - ], + "cases", + ["isError", "sub_func", "store", "str"], ) - def test_pack_bitstring_does_not_mutate_input( - self, - align_byte, - expected, - ): - """Test that pack_bitstring leaves the input list unchanged.""" - bits = [True, False, True] - original = bits.copy() + async def test_methods(self, cases, paramPDU): + """Ensure that __init__ runs correctly.""" + pdu, _api, params, msg, _params2, _msg = paramPDU + match cases: + case "isError": + assert not pdu(False, 0).isError() + case "sub_func": + x = pdu(False, 0) + x_fc = x.sub_function_code + assert x_fc == x.decode_sub_function_code(msg) + case "store": + x = pdu(False, 0, **params) + v_get = mock.AsyncMock(return_value=[0]) + v_set = mock.AsyncMock(return_value=0) + assert await x.build_response(v_get, v_set) + if v_set.called: + v_set.return_value = ExcCodes.DEVICE_FAILURE + assert isinstance( + await x.build_response(v_get, v_set), PDUexception + ) + if v_get.called: + v_set.return_value = 0 + v_get.return_value = ExcCodes.DEVICE_FAILURE + assert isinstance( + await x.build_response(v_get, v_set), PDUexception + ) - result = pack_bitstring(bits, align_byte=align_byte) + case "str": + x_str = str(pdu(False, 0, **params)) + for x in (pdu.__name__, "dev_id", "function_code", "transaction_id"): + assert x in x_str + for key in params: + assert key in x_str + case _: # pragma: no cover + raise TypeError("Test case not handled!") - assert result == expected - assert bits == original + @pytest.mark.parametrize("is_request", [True, False]) + def test_to_bytes(self, is_request, paramPDU): + """Ensure that __init__ runs correctly.""" + if is_request: + pdu, _api, params, msg, params2, _msg = paramPDU + else: + pdu, _api, params2, _msg, params, msg = paramPDU + params_comb = params | params2 + x = pdu(is_request, 1, **params) + assert msg == x.to_bytes() + x = pdu(is_request, 1, **params_comb) + assert msg == x.to_bytes() + if hasattr(x, "verify"): + with ( + mock.patch.object(x, "verify", mock.MagicMock(return_value="test")), + pytest.raises(ModbusIOException), + ): + x.to_bytes() - @pytest.mark.parametrize( - ("bytestream", "bitlist"), - [ - (b"\x01", [True] + [False] * 7), - (b"\x01\x00", [True] + [False] * 15), - (b"\x00\x01", [False] * 8 + [True] + [False] * 7), - (b"\x00\x80", [False] * 15 + [True]), - (b"\x01\x80", [True] + [False] * 14 + [True]), - (b"\x00\x05", [False] * 8 + [True, False, True] + [False] * 5), - (b"\x01\x05", [True] + [False] * 7 + [True, False, True] + [False] * 5), - ( - b"\x81\x05", - [True] + [False] * 6 + [True, True, False, True] + [False] * 5, - ), - ( - b"\x05\x81\x01\x00", - [True, False, True] - + [False] * 5 - + [True] - + [False] * 6 - + [True] - + [True] - + [False] * 7 - + [False] * 8, - ), - ], - ) - def test_bit_unpacking(self, bytestream, bitlist): - """Test all string <=> bit packing functions.""" - assert unpack_bitstring(bytestream) == bitlist + @pytest.mark.parametrize("is_request", [True, False]) + def test_from_bytes(self, is_request, paramPDU): + """Ensure that __init__ runs correctly.""" + if is_request: + pdu, _api, params, msg, _params2, _msg = paramPDU + else: + pdu, _api, _params2, _msg, params, msg = paramPDU + result = pdu(is_request, 1, **params) + x = pdu(is_request, 1) + x.from_bytes(msg) + if "bits" in params: + for entry in (result, x): + if j := len(entry.bits) % 8: + entry.bits += [False] * (8 - j) + entry.count = len(result.bits) + for key in params: + assert getattr(result, key) == getattr(x, key) + result_str = str(result) + x_str = str(x) + for entry in params: + assert entry in result_str + assert entry in x_str + if hasattr(x, "verify"): + with mock.patch.object(x, "verify", mock.MagicMock(return_value="test")): + assert x.from_bytes(msg) == "test" + + @pytest.mark.parametrize("is_request", [True, False]) + def test_calc_etc(self, is_request, paramPDU): + """Ensure that __init__ runs correctly.""" + if is_request: + pdu, _api, _params, msg, _params2, _msg = paramPDU + else: + pdu, _api, _params2, _msg, _params, msg = paramPDU + x = pdu(is_request, 1) + assert len(msg) == x.calculatePduSize(msg) + if not hasattr(x, "verify"): + return + x.from_bytes(msg) + if is_request and hasattr(x, "address"): + org_addr = x.address + for address in -1, 65535 + 1: + x.address = address + assert isinstance(x.verify(), str) + x.address = org_addr + assert not x.verify() + org_count = x.count + for count in -1, x.MAX_COUNT + 1: + x.count = count + assert isinstance(x.verify(), str) + x.count = org_count + assert not x.verify() + assert not x.calculatePduSize(msg[:2]) + assert not x.calculatePduSize(msg[:-1]) + + def test_decoder_lookup(self, paramPDU): + """Test decoder.""" + pdu, _api, _params, msg, _params2, _msg = paramPDU + result = DecodePDU._lookupPduClass(msg) + assert result == pdu - def test_ExceptionResponse_str(self): - """Test string conversion of ExceptionResponse.""" - assert str(self.exception) != "" + @pytest.mark.parametrize("is_request", [True, False]) + @pytest.mark.parametrize("cases", ["decode", "encode", "calc"]) + def test_decoder(self, is_request, cases, paramPDU): + """Test decoder.""" + if is_request: + pdu, _api, params, msg, _params2, _msg = paramPDU + else: + pdu, _api, _params2, _msg, params, msg = paramPDU + match cases: + case "decode": + x_pdu = DecodePDU(is_request).decode(msg) + assert isinstance(x_pdu, pdu) + case "encode": + x_pdu = pdu(is_request, 1, **params) + x_msg = DecodePDU(is_request).encode(x_pdu) + assert x_msg == msg + case "calc": + x = pdu(is_request, 1) + x.from_bytes(msg) + assert len(msg) == DecodePDU(is_request).calculatePduSize(msg) + case _: # pragma: no cover + raise TypeError("Test case not handled!") diff --git a/test/pdu/test_pdu_extras.py b/test/pdu/test_pdu_extras.py new file mode 100644 index 0000000000..bc6f82a3d6 --- /dev/null +++ b/test/pdu/test_pdu_extras.py @@ -0,0 +1,543 @@ +"""Singular tests.""" + +from typing import cast +from unittest import mock + +import pytest + +import pymodbus.pdu.data_message as data_msg +import pymodbus.pdu.diag_message as diag_msg +import pymodbus.pdu.other_message as file_msg +import pymodbus.pdu.other_message as other_msg +from pymodbus import ModbusException, ModbusIOException +from pymodbus.constants import CLEAR_STATISTICS, DeviceInformation, ExcCodes +from pymodbus.pdu import DecodePDU, ModbusControlBlock, PDUexception + + +class TestPDUExtras: + """Modbus PDU singular tests.""" + + @pytest.mark.parametrize( + ("frame", "exp_count"), + [ + (b"\x01\x01\x00\x00\x07\xd1", 2001), + (b"\x01\x02\x00\x00\x07\xd1", 2001), + ], + ) + def test_bit_1(self, frame, exp_count): + """Decoding must not raise for an over-max bit read quantity.""" + assert DecodePDU(True).decode(frame).count == exp_count + + @pytest.mark.parametrize( + "frame", + [ + b"\x00\x0f\x00\x01\x00\x10\x01\xff", + b"\x00\x0f\x00\x01\x00\x08\x02\xff\x00", + b"\x00\x0f\x00\x01\x00\x08\x01", + b"\x00\x0f\x00\x01\x00\x08\x01\xff\x00", + ], + ) + async def test_bit_2(self, frame): + """Test write multiple coils rejects inconsistent byte counts.""" + request = data_msg.PDUwriteMultipleCoils(True, 0) + request.from_bytes(frame) + mx = mock.AsyncMock(return_value=ExcCodes.ILLEGAL_VALUE) + result = await request.build_response(mx, mx) + assert isinstance(result, PDUexception) + assert result.exception_code == ExcCodes.ILLEGAL_VALUE + + @pytest.mark.parametrize("value", [b"\x00\x01", b"\x00\xff", b"\xff\xff"]) + async def test_bit_3(self, value): + """A value other than 0x0000 or 0xFF00 must answer 0x03 and leave the coil.""" + request = data_msg.PDUwriteSingleCoil(True, 0) + request.from_bytes(b"\x00\x05\x00\x02" + value) + result = await request.build_response( + mock.AsyncMock(return_value=[True]), mock.AsyncMock(return_value=0) + ) + assert result.function_code == 0x85 + assert isinstance(result, PDUexception) + assert result.exception_code == ExcCodes.ILLEGAL_VALUE + + @pytest.mark.parametrize( + ("value", "bit"), [(b"\xff\x00", True), (b"\x00\x00", False)] + ) + async def test_bit_4(self, value, bit): + """0xFF00 and 0x0000 are written as ON and OFF.""" + request = data_msg.PDUwriteSingleCoil(False, 1) + request.from_bytes(b"\x01\x05\x00\x02" + value) + x_set = mock.AsyncMock(return_value=0) + result = await request.build_response(mock.AsyncMock(return_value=[bit]), x_set) + assert result.to_bytes() == b"\x01\x05\x00\x02" + value + x_set.assert_awaited_once_with(1, 5, 2, [bit]) + + def test_bit_5(self): + """Detect conflict byte and bit count.""" + pdu = data_msg.PDUreadCoils(False, 0) + assert pdu.from_bytes(b"\x00\x01\x02\x03") + + def test_bit_6(self): + """Detect write with multiple coils.""" + pdu = data_msg.PDUwriteSingleCoil(True, 0, address=1, bits=[True, True]) + pdu.count = 1 + with pytest.raises(ModbusIOException): + pdu.to_bytes() + + def test_bit_7(self): + """The largest write count must keep the PDU within 253 bytes.""" + assert data_msg.PDUwriteMultipleCoils.MAX_COUNT == 0x07B0 + pdu = data_msg.PDUwriteMultipleCoils(True, 0, address=0, bits=[True] * 0x07B0) + assert len(pdu.to_bytes()) == 253 + with pytest.raises(ModbusIOException, match="count"): + data_msg.PDUwriteMultipleCoils( + True, 0, address=0, bits=[True] * (0x07B0 + 1) + ).to_bytes() + + @pytest.mark.parametrize("count", [0, 0x07B1, 2000]) + async def test_bit_8(self, count): + """An out-of-range write quantity must answer 0x03, not silence.""" + byte_count = (count + 7) // 8 + frame = b"\x00\x0f\x00\x00" + count.to_bytes(2, "big") + bytes([byte_count]) + pdu = DecodePDU(True).decode(frame + b"\xff" * byte_count) + assert pdu.function_code == 0x8F + assert cast(PDUexception, pdu).exception_code == ExcCodes.ILLEGAL_VALUE + + def test_reg_1(self): + """Detect read with wrong byte count.""" + pdu = data_msg.PDUreadHoldingRegisters(False, 0) + assert pdu.from_bytes(b"\x01\x03\x00\x75\x00\x03\x00\x03") + pdu = data_msg.PDUwriteMultipleRegisters(True, 0) + assert pdu.from_bytes(b"\x01\x10\x00\x75\x00\x03\x08\x00\x6f\x00\x79\x00\x83") + assert pdu.from_bytes(b"\x01\x10\x00\x75\x00\x03\x04\x00\x6f\x00\x79\x00\x83") + + def test_reg_2(self): + """Detect write with multiple registers.""" + for pdu in ( + data_msg.PDUwriteSingleRegister(True, 0, address=1, registers=[True, True]), + data_msg.PDUwriteMultipleRegisters( + True, 0, address=1, registers=[True, True] + ), + ): + pdu.count = 1 + with pytest.raises(ModbusIOException): + pdu.to_bytes() + + def test_reg_3(self): + """Detect write with multiple registers.""" + for regs in ([], [False] * 122): + pdu = data_msg.PDUreadWriteMultipleRegisters( + True, 0, address=1, registers=regs + ) + with pytest.raises(ModbusIOException): + pdu.to_bytes() + for addr in (-1, 65536): + pdu = data_msg.PDUreadWriteMultipleRegisters( + True, 0, address=1, write_address=addr, registers=[123] + ) + with pytest.raises(ModbusIOException): + pdu.to_bytes() + pdu = data_msg.PDUreadWriteMultipleRegisters(False, 0) + assert pdu.from_bytes(b"\x01\x17\x02\x00\x6f\x00\x70") + pdu = data_msg.PDUreadWriteMultipleRegisters(True, 0) + assert pdu.from_bytes(b"\x01\x17\x00\x11\x00\x02\x00\x19\x00\x02\x04\x00\x6f") + assert pdu.from_bytes( + b"\x01\x17\x00\x11\x00\x02\x00\x19\x00\x03\x04\x00\x6f\x00\x70" + ) + + def test_reg_4(self): + """Detect write with multiple registers.""" + for masks in ((-1, 0), (0, -1), (0x1FFFF, 0), (0, 0x1FFFF)): + pdu = data_msg.PDUmaskWriteRegister( + True, 0, address=1, and_mask=masks[0], or_mask=masks[1] + ) + with pytest.raises(ModbusIOException): + pdu.to_bytes() + + def test_diag_1(self): + """Detect diag message.""" + pdu = diag_msg.PDUdiagnostic(True, 0, message=123) + assert pdu.message == b"\x00\x7b" + pdu = diag_msg.PDUdiagnostic(True, 0, message=[123, 0]) + assert pdu.message == b"\x00\x7b\x00\x00" + + async def test_diag_2(self): + """Detect diag message.""" + pdu = diag_msg.PDUgetClearModbusPlus(True, 0, message=CLEAR_STATISTICS) + v = mock.AsyncMock() + await pdu.build_response(v, v) + + def test_diag_3(self): + """Test basic bit message encoding/decoding.""" + msg = b"\x00\x2b\x0e\x01\x00\x01\x00\x01\x00\x01\x00" + pdu = DecodePDU(True).decode(msg[:5]) + assert isinstance(pdu, diag_msg.PDUreadDeviceInformation) + assert pdu.calculatePduSize(msg) == 5 + pdu = diag_msg.PDUreadDeviceInformation(False, 0) + assert pdu.calculatePduSize(msg[:7]) == 0 + assert pdu.calculatePduSize(msg[:8]) == 0 + assert pdu.calculatePduSize(msg) == 11 + + async def test_diag_4(self): + """Test basic bit message encoding/decoding.""" + TEST_VERSION = b"v2.1.12" + TEST_MESSAGE = b"\x00\x07Company\x01\x07Product\x02\x07v2.1.12" + + control = ModbusControlBlock() + control.Identity.VendorName = "Company" + control.Identity.ProductCode = "Product" + control.Identity.MajorMinorRevision = TEST_VERSION + control.Identity.update({0x81: ["Test", "Repeated"]}) + + handle = diag_msg.PDUreadDeviceInformation(True, 0) + result = await handle.build_response(mock.AsyncMock(), mock.AsyncMock()) + assert isinstance(result, diag_msg.PDUreadDeviceInformation) + assert result.information[0x00] == "Company" + assert result.information[0x01] == "Product" + assert result.information[0x02] == TEST_VERSION + with pytest.raises(KeyError): + _ = result.information[0x81] + + handle = diag_msg.PDUreadDeviceInformation( + True, 0, read_code=DeviceInformation.SPECIFIC, object_id=0x00 + ) + result = await handle.build_response(mock.AsyncMock(), mock.AsyncMock()) + assert cast(diag_msg.PDUreadDeviceInformation, result).information == { + 0x00: "Company" + } + + handle = diag_msg.PDUreadDeviceInformation( + True, 0, read_code=DeviceInformation.EXTENDED, object_id=0x80 + ) + result = await handle.build_response(mock.AsyncMock(), mock.AsyncMock()) + assert cast(diag_msg.PDUreadDeviceInformation, result).information[0x81] == [ + "Test", + "Repeated", + ] + message = b"\x00\x2b\x0e\x01\x83\x00\x00\x03" + message += TEST_MESSAGE + dataset = { + 0x00: "Company", + 0x01: "Product", + 0x02: TEST_VERSION, + } + handle = diag_msg.PDUreadDeviceInformation( + False, 0, read_code=DeviceInformation.BASIC, information=dataset + ) + result = handle.to_bytes() + assert result == message + assert "PDUreadDeviceInformation" in str(handle) + + dataset = { + 0x00: "Company", + 0x01: "Product", + 0x02: TEST_VERSION, + 0x81: ["Test", "Repeated"], + 0x82: PDUexception(0, 0x01, 0), + } + message = b"\x00\x2b\x0e\x03\x83\x00\x00\x06" + message += TEST_MESSAGE + message += b"\x81\x04Test\x81\x08Repeated\x82\x03\x00\x81\x00" + handle = diag_msg.PDUreadDeviceInformation( + False, + 0, + read_code=DeviceInformation.EXTENDED, + information=dataset, + ) + result = handle.to_bytes() + assert result == message + longstring = ( + "Lorem ipsum dolor sit amet, consectetur adipiscing " + "elit. Vivamus rhoncus massa turpis, sit amet ultrices" + " orci semper ut. Aliquam tristique sapien in lacus " + "pharetra, in convallis nunc consectetur. Nunc velit " + "elit, vehicula tempus tempus sed. " + ) + message = b"\x00\x2b\x0e\x01\x83\xff\x80\x03" + message += TEST_MESSAGE + dataset = { + 0x00: "Company", + 0x01: "Product", + 0x02: TEST_VERSION, + 0x80: longstring, + } + handle = diag_msg.PDUreadDeviceInformation( + False, 0, read_code=DeviceInformation.BASIC, information=dataset + ) + result = handle.to_bytes() + assert result == message + assert "PDUreadDeviceInformation" in str(handle) + message = b"\x00\x2b\x0e\x01\x01\x00\x00\x05" + message += TEST_MESSAGE + message += b"\x81\x04Test\x81\x08Repeated\x81\x07Another" + handle = diag_msg.PDUreadDeviceInformation( + False, 0, read_code=0x00, information={} + ) + handle.from_bytes(message) + assert handle.read_code == DeviceInformation.BASIC + assert handle.conformity == 0x01 + assert handle.information[0x00] == b"Company" + assert handle.information[0x01] == b"Product" + assert handle.information[0x02] == TEST_VERSION + assert handle.information[0x81] == [b"Test", b"Repeated", b"Another"] + + async def test_diag_5(self): + """Test basic bit message encoding/decoding.""" + handle = diag_msg.PDUreadDeviceInformation(True, 0) + handle.read_code = -1 + assert ( + await handle.build_response(mock.AsyncMock(), mock.AsyncMock()) + ).function_code == 0xAB + handle.read_code = 0x05 + assert ( + await handle.build_response(mock.AsyncMock(), mock.AsyncMock()) + ).function_code == 0xAB + handle.read_code = 0x00 + handle.object_id = -1 + result = await handle.build_response(mock.AsyncMock(), mock.AsyncMock()) + assert cast(PDUexception, result).exception_code == ExcCodes.ILLEGAL_VALUE + assert ( + await handle.build_response(mock.AsyncMock(), mock.AsyncMock()) + ).function_code == 0xAB + handle.object_id = 0x100 + assert ( + await handle.build_response(mock.AsyncMock(), mock.AsyncMock()) + ).function_code == 0xAB + handle = diag_msg.PDUreadDeviceInformation( + True, 0, read_code=DeviceInformation.SPECIFIC, object_id=0x54 + ) + result = await handle.build_response(mock.AsyncMock(), mock.AsyncMock()) + assert isinstance(result, PDUexception) + assert result.exception_code == ExcCodes.ILLEGAL_ADDRESS + + ModbusControlBlock().Identity[0xFE] = "" + handle = diag_msg.PDUreadDeviceInformation( + True, 0, read_code=DeviceInformation.SPECIFIC, object_id=0xFE + ) + result = await handle.build_response(mock.AsyncMock(), mock.AsyncMock()) + assert isinstance(result, PDUexception) + assert result.exception_code == ExcCodes.ILLEGAL_ADDRESS + + def test_other_1(self): + """Test get comm event log with events.""" + response = other_msg.PDUgetCommEventLog(False, 0, events=[0x12, 0x34, 0x56]) + assert ( + response.to_bytes() == b"\x00\x0c\x09\x00\x00\x00\x00\x00\x00\x12\x34\x56" + ) + response.from_bytes(b"\x00\x0c\x09\x00\x00\x00\x12\x00\x12\x12\x34\x56") + assert response.status + assert response.message_count == 0x12 + assert response.event_count == 0x12 + assert response.events == [0x12, 0x34, 0x56] + + async def test_other_2(self): + """Test report device_id request.""" + with mock.patch("pymodbus.pdu.other_message.DeviceInformationFactory") as dif: + # First test regular identity strings + identity = { + 0x00: "VN", # VendorName + 0x01: "PC", # ProductCode + 0x02: "REV", # MajorMinorRevision + 0x03: "VU", # VendorUrl + 0x04: "PN", # ProductName + 0x05: "MN", # ModelName + 0x06: "UAN", # UserApplicationName + 0x07: "RA", # reserved + 0x08: "RB", # reserved + } + dif.get.return_value = identity + expected_identity = "-".join(identity.values()).encode() + + request = other_msg.PDUreportDeviceId(True, 0) + response = await request.build_response(mock.AsyncMock(), mock.AsyncMock()) + assert ( + cast(other_msg.PDUreportDeviceId, response).identifier + == expected_identity + ) + + # Change to byte strings and test again (final result should be the same) + identity2 = { + 0x00: b"VN", # VendorName + 0x01: b"PC", # ProductCode + 0x02: b"REV", # MajorMinorRevision + 0x03: b"VU", # VendorUrl + 0x04: b"PN", # ProductName + 0x05: b"MN", # ModelName + 0x06: b"UAN", # UserApplicationName + 0x07: b"RA", # reserved + 0x08: b"RB", # reserved + } + dif.get.return_value = identity2 + + request = other_msg.PDUreportDeviceId(True, 0) + response = await request.build_response(mock.AsyncMock(), mock.AsyncMock()) + assert ( + cast(other_msg.PDUreportDeviceId, response).identifier + == expected_identity + ) + + async def test_other_3(self): + """Test report device_id.""" + with mock.patch("pymodbus.pdu.other_message.DeviceInformationFactory") as dif: + dif.get.return_value = {} + request = other_msg.PDUreportDeviceId(True, 0) + request.from_bytes(b"\x00\x11\x12") + response = other_msg.PDUreportDeviceId( + False, + 0, + identifier=cast( + other_msg.PDUreportDeviceId, + await request.build_response(mock.AsyncMock(), mock.AsyncMock()), + ).identifier, + status=True, + ) + + assert response.to_bytes() == b"\x00\x11\tPymodbus\xff" + response.from_bytes(b"\tPymodbus\xff") + assert response.status + assert response.identifier == b"Pymodbus" + response.from_bytes(b"\x00\x11\x03\x12\x00\x00") + assert response.identifier == b"\x12\x00" + response.status = False + assert response.to_bytes() == b"\x00\x11\x03\x12\x00\x00" + + def test_other_4(self): + """Test decode( to_bytes()) keeps identifier and status unchanged.""" + for identifier, status in ((b"Pymodbus", True), (b"\x12", False)): + sent = other_msg.PDUreportDeviceId( + False, 0, identifier=identifier, status=status + ) + received = other_msg.PDUreportDeviceId(False, 0) + received.from_bytes(sent.to_bytes()) + assert received.identifier == identifier + assert received.status == status + + def test_other_5(self): + """Test byte count pointing outside the received data raises.""" + response = other_msg.PDUreportDeviceId(False, 0) + for frame in (b"\x00\x11\x00\x12\xff", b"\x00\x11\x04\x12\xff"): + assert response.from_bytes(frame) + + def test_other_6(self): + """Test byte count pointing outside the received data raises.""" + response = other_msg.PDUreadFifoQueue(False, 0) + assert response.calculatePduSize(b"\x01\x18\x00") == 0 + + def test_file_1(self): + """Test file record length generation.""" + assert ( + file_msg.FileRecord( + file_number=0x01, record_number=0x02, record_data=b"\x00\x01\x02\x04" + ).record_length + == 0x02 + ) + with pytest.raises(ModbusException): + file_msg.FileRecord(record_length=12, record_data=b"\x00\x01\x02\x04") + with pytest.raises(ModbusException): + file_msg.FileRecord(record_length=11) + + @pytest.mark.parametrize("server", [True, False]) + def test_file_2(self, server): + """Test basic bit message encoding/decoding.""" + records = [ + file_msg.FileRecord( + file_number=0x01, record_number=0x02, record_data=b"\x00\x01\x02\x03" + ) + ] + result = file_msg.PDUreadFileRecord(server, 0, records=records).to_bytes() + if server: + assert result == b"\x00\x14\x07\x06\x00\x01\x00\x02\x00\x02" + else: + assert result == b"\x00\x14\x06\x05\x06\x00\x01\x02\x03" + + def test_file_3(self): + """Test file_msg.PDUreadFileRecord raises ModbusException on oversized byte_count.""" + handle = file_msg.PDUreadFileRecord(False, 0) + with pytest.raises(ModbusException): + handle.from_bytes( + bytes([0x00, 0x15, 0xFF, 0x06, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01]) + ) + with pytest.raises(ModbusException): + handle.from_bytes( + bytes( + [ + 0x00, + 0x15, + 0xFF, + 0x06, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + ] + ) + ) + + def test_file_4(self): + """Test file_msg.PDUreadFifoQueue raises ModbusException on oversized count.""" + handle = file_msg.PDUreadFileRecord(True, 0) + assert handle.from_bytes(b"\x00\x14\x07\x06\x00\x01\x00\x02\x00\x00\x00\x00") + + def test_file_5(self): + """Test basic bit message encoding/decoding.""" + records = [ + file_msg.FileRecord( + file_number=0x01, record_number=0x02, record_data=b"\x00\x01\x02\x03" + ) + ] + handle = file_msg.PDUwriteFileRecord(False, 0, records=records) + result = handle.to_bytes() + assert result == b"\x00\x15\x0b\x06\x00\x01\x00\x02\x00\x02\x00\x01\x02\x03" + + def test_file_6(self): + """Test file_msg.PDUreadFifoQueue raises ModbusException on oversized count.""" + handle = file_msg.PDUwriteFileRecord(True, 0) + assert handle.from_bytes( + b"\x01\x15\x0e\x06\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00" + ) + + def test_file_7(self): + """Test file_msg.PDUreadFifoQueue raises ModbusException on oversized count.""" + handle = file_msg.PDUreadFifoQueue(False, 0) + assert handle.from_bytes(bytes([0x00, 0x18, 0x00, 0x00, 0xFF, 0xFF])) + + def test_file_8(self): + """Test file_msg.PDUreadFifoQueue raises ModbusException on oversized count.""" + handle = file_msg.PDUreadFifoQueue(False, 0) + assert handle.from_bytes(b"\x01\x18\x00\x06\x00\x02\x00\x7b\x01\xc8\x00") + assert handle.from_bytes(b"\x01\x18\x00\x06\x00\x04\x00\x7b\x01\xc8") + + @pytest.mark.parametrize( + ("server", "frame"), + [ + (True, b"\x00\x14\x14\x10"), # read file record, byte count past the frame + (True, b"\x00\x14\x15\x10"), # write file record, byte count past the frame + ( + False, + b"\x00\x14\x18\x00\x06\x00\x05\x00\x01", + ), # fifo count past the frame + ], + ) + def test_file_9(self, server, frame): + """Test bad file record frames fail like other undecodable frames.""" + with pytest.raises(ModbusIOException): + DecodePDU(server).decode(frame) + + def test_file_10(self): + """Test file record.""" + # record = FileRecord(file_number=0x04, record_number=0x01, record_length=0x02) + request = ( + b"\x00\x14\x0e\x06\x00\x04\x00\x01\x00\x02\x06\x00\x03\x00\x09\x00\x02" + ) + handle = file_msg.PDUreadFileRecord(True, 0) + handle.from_bytes(request) + # assert handle.records[0] == record + assert [ + (rec.file_number, rec.record_number, rec.record_length) + for rec in handle.records + ] == [(4, 1, 2), (3, 9, 2)] + handle.from_bytes(b"\x00\x14\x07\x06\x00\x04\x00\x01\x00\x03") + assert handle.records[0].record_length == 3 + assert handle.to_bytes() == b"\x00\x14\x07\x06\x00\x04\x00\x01\x00\x03" diff --git a/test/pdu/test_register_read_messages.py b/test/pdu/test_register_read_messages.py deleted file mode 100644 index 1bd10986ef..0000000000 --- a/test/pdu/test_register_read_messages.py +++ /dev/null @@ -1,373 +0,0 @@ -"""Test register read messages.""" - -import struct -from unittest import mock - -import pytest - -from pymodbus.constants import ExcCodes -from pymodbus.exceptions import ModbusIOException -from pymodbus.pdu.decoders import DecodePDU -from pymodbus.pdu.register_message import ( - ReadHoldingRegistersRequest, - ReadHoldingRegistersResponse, - ReadInputRegistersRequest, - ReadInputRegistersResponse, - ReadWriteMultipleRegistersRequest, - ReadWriteMultipleRegistersResponse, -) - - -TEST_MESSAGE = b"\x06\x00\x0a\x00\x0b\x00\x0c" - - -class TestReadRegisterMessages: - """Register Message Test Fixture. - - This fixture tests the functionality of all the - register based request/response messages: - - * Read/Write Input Registers - * Read Holding Registers - """ - - values: list - request_read: dict - response_read: dict - - def setup_method(self): - """Initialize the test environment and builds request/result encoding pairs.""" - arguments = { - "read_address": 1, - "read_count": 5, - "write_address": 1, - } - self.values = [0xA, 0xB, 0xC] - self.request_read = { - ReadHoldingRegistersRequest(address=1, count=5): b"\x00\x01\x00\x05", - ReadInputRegistersRequest(address=1, count=5): b"\x00\x01\x00\x05", - ReadWriteMultipleRegistersRequest( - write_registers=[0x00] * 5, - **arguments, - ): b"\x00\x01\x00\x05\x00\x01\x00" - b"\x05\x0a\x00\x00\x00\x00\x00" - b"\x00\x00\x00\x00\x00", - ReadWriteMultipleRegistersRequest( - write_registers=[0xAB], - **arguments, - ): b"\x00\x01\x00\x05\x00\x01\x00\x01\x02\x00\xab", - } - self.response_read = { - ReadHoldingRegistersResponse(registers=self.values): TEST_MESSAGE, - ReadInputRegistersResponse(registers=self.values): TEST_MESSAGE, - ReadWriteMultipleRegistersResponse(registers=self.values): TEST_MESSAGE, - } - - def test_register_read_requests(self): - """Test register read requests.""" - for request, response in iter(self.request_read.items()): - assert request.x_encode() == response - - def test_register_read_responses(self): - """Test register read response.""" - for request, response in iter(self.response_read.items()): - assert request.x_encode() == response - - def test_register_read_response_decode(self): - """Test register read response.""" - for response, packet in self.response_read.items(): - response.x_decode(packet) - assert response.registers == self.values - - def test_register_read_response_decode_error(self): - """Test register read response.""" - reg = ReadHoldingRegistersResponse(count=5) - with pytest.raises(ModbusIOException) as exc_info: - reg.x_decode(b"\x14\x00\x03\x00\x11") - assert exc_info.value.fcode == reg.function_code + 0x80 - - def test_register_input_response_decode_error(self): - """Test register read response.""" - reg = ReadInputRegistersResponse(count=5) - with pytest.raises(ModbusIOException) as exc_info: - reg.x_decode(b"\x14\x00\x03\x00\x11") - assert exc_info.value.fcode == reg.function_code + 0x80 - - def test_readwrite_response_decode_error(self): - """Test register read response.""" - reg = ReadWriteMultipleRegistersResponse(count=5) - with pytest.raises(ModbusIOException) as exc_info: - reg.x_decode(b"\x14\x00\x03\x00\x11") - assert exc_info.value.fcode == reg.function_code + 0x80 - - def test_readwrite_encode_write_count_limit(self): - """Encoding must reject a write count above the FC23 maximum of 121. - - 121 write registers is a 252 byte PDU, 122 is 254 and does not fit in - the 253 byte MODBUS PDU. - """ - - def build(count): - return ReadWriteMultipleRegistersRequest( - read_address=1, - read_count=1, - write_address=1, - write_registers=[0] * count, - ) - - assert len(build(121).x_encode()) + 1 <= 253 - with pytest.raises(ValueError): # noqa: PT011 - build(122).x_encode() - - def test_readwrite_decode_write_count_above_limit(self): - """Decoding must accept 122..125 so the server can answer ILLEGAL_VALUE. - - Raising here would make the server drop the frame without a response. - """ - request = ReadWriteMultipleRegistersRequest() - request.x_decode(struct.pack(">HHHHB", 1, 1, 1, 122, 244) + b"\x00\x00" * 122) - assert request.write_count == 122 - - def test_readwrite_decode_read_count_above_limit(self): - """Decoding must accept read_count above 125 so the server can answer 0x03.""" - request = ReadWriteMultipleRegistersRequest() - request.x_decode(struct.pack(">HHHHB", 1, 126, 1, 1, 2) + b"\x00\x00") - assert request.read_count == 126 - - async def test_readwrite_read_count_above_limit_returns_illegal_value( - self, mock_server_context - ): - """An out-of-range FC23 read count must answer 0x03.""" - context = mock_server_context() - context.async_getValues = mock.AsyncMock() - context.async_setValues = mock.AsyncMock() - request = ReadWriteMultipleRegistersRequest( - read_address=1, read_count=126, write_address=1, write_registers=[5] - ) - result = await request.datastore_update(context, 1) - assert result.function_code == 0x97 - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - context.async_getValues.assert_not_awaited() - context.async_setValues.assert_not_awaited() - - async def test_readwrite_read_count_at_max_returns_normal_response( - self, mock_server_context - ): - """A read count exactly at MAX_READ_COUNT must be accepted.""" - context = mock_server_context() - request = ReadWriteMultipleRegistersRequest( - read_address=1, - read_count=ReadWriteMultipleRegistersRequest.MAX_READ_COUNT, - write_address=1, - write_registers=[5], - ) - result = await request.datastore_update(context, 1) - assert result.function_code == request.function_code - - async def test_register_read_requests_count_errors(self, mock_server_context): - """This tests that the register request messages. - - will break on counts that are out of range - """ - context = mock_server_context() - requests = [ - ReadHoldingRegistersRequest(address=1, count=0x800), - ReadInputRegistersRequest(address=1, count=0x800), - ReadWriteMultipleRegistersRequest( - read_address=1, read_count=0x800, write_address=1, write_registers=[5] - ), - ReadWriteMultipleRegistersRequest( - read_address=1, read_count=5, write_address=1, write_registers=[] - ), - ] - for request in requests: - result = await request.datastore_update(context, 0) - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - - @pytest.mark.parametrize( - ("request_class", "function_code"), - [ - (ReadHoldingRegistersRequest, 3), - (ReadInputRegistersRequest, 4), - ], - ) - async def test_read_register_count_above_max_returns_illegal_value( - self, request_class, function_code, mock_server_context - ): - """An out-of-range read quantity must answer 0x03, not silence.""" - context = mock_server_context() - context.async_getValues = mock.AsyncMock(return_value=[1] * 10) - request = request_class(address=0, count=request_class.MAX_COUNT + 1) - result = await request.datastore_update(context, 1) - assert result.function_code == function_code | 0x80 - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - context.async_getValues.assert_not_awaited() - - @pytest.mark.parametrize( - "request_class", - [ReadHoldingRegistersRequest, ReadInputRegistersRequest], - ) - async def test_read_register_count_zero_returns_illegal_value( - self, request_class, mock_server_context - ): - """A zero read quantity must answer 0x03.""" - context = mock_server_context() - context.async_getValues = mock.AsyncMock(return_value=[1] * 10) - result = await request_class(address=0, count=0).datastore_update(context, 1) - assert result.function_code == request_class.function_code | 0x80 - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - context.async_getValues.assert_not_awaited() - - @pytest.mark.parametrize( - "request_class", - [ReadHoldingRegistersRequest, ReadInputRegistersRequest], - ) - async def test_read_register_count_at_max_returns_normal_response( - self, request_class, mock_server_context - ): - """A count exactly at the maximum must be accepted, not rejected.""" - context = mock_server_context() - request = request_class(address=0, count=request_class.MAX_COUNT) - result = await request.datastore_update(context, 1) - assert result.function_code == request_class.function_code - - def test_read_register_decode_accepts_count_above_max(self): - """Decoding must not raise for an over-max read quantity. - - Raising here makes DecodePDU.decode() swallow the frame and the server - answer nothing, replacing a correct exception response with silence. - """ - decoder = DecodePDU(True) - for frame, expected_count in ( - (b"\x03\x00\x00\x00\x7e", 126), - (b"\x04\x00\x00\x00\x7e", 126), - ): - pdu = decoder.decode(frame) - assert pdu.count == expected_count - - async def test_register_read_requests_verify_errors(self, mock_server_context): - """This tests that the register request messages. - - will break on counts that are out of range - """ - context = mock_server_context() - requests = [ - ReadHoldingRegistersRequest(address=-1, count=5), - ReadInputRegistersRequest(address=-1, count=5), - ReadWriteMultipleRegistersRequest(-1, 5, 1, [5]), - ReadWriteMultipleRegistersRequest(1, 5, -1, [5]), - ] - for request in requests: - await request.datastore_update(context, 0) - - async def test_register_read_requests_datastore_update(self, mock_server_context): - """This tests that the register request messages. - - will break on counts that are out of range - """ - context = mock_server_context(True) - requests = [ - ReadHoldingRegistersRequest(address=-1, count=5), - ReadInputRegistersRequest(address=-1, count=5), - ] - for request in requests: - response = await request.datastore_update(context, 1) - assert request.function_code == response.function_code - - async def test_read_write_multiple_registers_request(self, mock_server_context): - """Test read/write multiple registers.""" - context = mock_server_context(True) - request = ReadWriteMultipleRegistersRequest( - read_address=1, read_count=10, write_address=1, write_registers=[0x00] - ) - response = await request.datastore_update(context, 0) - assert request.function_code == response.function_code - - @pytest.mark.parametrize( - "frame", - [ - b"\x00\x01\x00\x01\x00\x02\x00\x02\x02\x00\x0a", - b"\x00\x01\x00\x01\x00\x02\x00\x01\x04\x00\x0a\x00\x0b", - b"\x00\x01\x00\x01\x00\x02\x00\x01\x02\x00", - b"\x00\x01\x00\x01\x00\x02\x00\x01\x02\x00\x0a\x00", - b"\x00\x01\x00\x01\x00\x02\x00\x01\x01\x00", - ], - ) - async def test_read_write_multiple_registers_rejects_invalid_byte_count( - self, frame, mock_server_context - ): - """Test inconsistent write byte counts are rejected before writing.""" - request = ReadWriteMultipleRegistersRequest() - request.x_decode(frame) - context = mock_server_context() - context.async_setValues = mock.AsyncMock() - - result = await request.datastore_update(context, 1) - - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - context.async_setValues.assert_not_awaited() - - async def test_read_write_multiple_registers_accepts_valid_byte_count( - self, mock_server_context - ): - """Test a consistent write byte count reaches the datastore.""" - request = ReadWriteMultipleRegistersRequest() - request.x_decode(b"\x00\x01\x00\x01\x00\x02\x00\x02\x04\x00\x0a\x00\x0b") - context = mock_server_context() - context.async_setValues = mock.AsyncMock(return_value=0) - - result = await request.datastore_update(context, 1) - - assert result.function_code == request.function_code - context.async_setValues.assert_awaited_once_with( - 1, request.function_code, 2, [0x0A, 0x0B] - ) - - async def test_read_write_multiple_registers_verify(self, mock_server_context): - """Test read/write multiple registers.""" - context = mock_server_context() - request = ReadWriteMultipleRegistersRequest( - read_address=1, read_count=0x200, write_address=2, write_registers=[0x00] - ) - response = await request.datastore_update(context, 0) - assert response.exception_code == ExcCodes.ILLEGAL_VALUE - - await request.datastore_update(context, 0) - assert response.exception_code == ExcCodes.ILLEGAL_VALUE - - request.write_byte_count = 0x100 - await request.datastore_update(context, 0) - assert response.exception_code == ExcCodes.ILLEGAL_VALUE - - async def test_register_datastore_exceptions(self, mock_server_context): - """Test exception response from datastore.""" - context = mock_server_context() - context.async_getValues = mock.AsyncMock(return_value=ExcCodes.ILLEGAL_VALUE) - for pdu in ( - ReadHoldingRegistersRequest(address=-1, count=5), - ReadInputRegistersRequest(address=-1, count=5), - ReadWriteMultipleRegistersRequest(-1, 5, 1, [5], 1), - ): - await pdu.datastore_update(context, 1) - - def test_serializing_to_string(self): - """Test serializing to string.""" - for request in iter(self.request_read.keys()): - assert str(request) - for request in iter(self.response_read.keys()): - assert str(request) - - @pytest.mark.parametrize( - ("request_pdu"), - [ - ReadWriteMultipleRegistersRequest( - read_address=1, read_count=5, write_address=1, write_registers=[5] - ), - ], - ) - async def test_register_read_exception(self, request_pdu, mock_server_context): - """Test write single coil.""" - context = mock_server_context(True, default=True) - context.async_setValues = mock.AsyncMock(return_value=1) - result = await request_pdu.datastore_update(context, 1) - assert result.exception_code == 1 diff --git a/test/pdu/test_register_write_messages.py b/test/pdu/test_register_write_messages.py deleted file mode 100644 index 7a6d518e85..0000000000 --- a/test/pdu/test_register_write_messages.py +++ /dev/null @@ -1,249 +0,0 @@ -"""Test register write messages.""" - -from unittest import mock - -import pytest - -from pymodbus.constants import ExcCodes -from pymodbus.pdu.register_message import ( - MaskWriteRegisterRequest, - MaskWriteRegisterResponse, - WriteMultipleRegistersRequest, - WriteMultipleRegistersResponse, - WriteSingleRegisterRequest, - WriteSingleRegisterResponse, -) - - -# ---------------------------------------------------------------------------# -# Fixture -# ---------------------------------------------------------------------------# - - -class TestWriteRegisterMessages: - """Register Message Test Fixture. - - This fixture tests the functionality of all the - register based request/response messages: - - * Read/Write Input Registers - * Read Holding Registers - """ - - def setup_method(self): - """Initialize the test environment and builds request/result encoding pairs.""" - self.value = 0xABCD - self.values = [0xA, 0xB, 0xC] - self.write = { - WriteSingleRegisterRequest( - address=1, registers=[self.value] - ): b"\x00\x01\xab\xcd", - WriteSingleRegisterResponse( - address=1, registers=[self.value] - ): b"\x00\x01\xab\xcd", - WriteMultipleRegistersRequest( - address=1, registers=self.values - ): b"\x00\x01\x00\x03\x06\x00\x0a\x00\x0b\x00\x0c", - WriteMultipleRegistersRequest( - address=1, registers=[0xD] - ): b"\x00\x01\x00\x01\x02\x00\x0d", - WriteMultipleRegistersResponse(address=1, count=5): b"\x00\x01\x00\x05", - } - - def test_register_write_requests_encode(self): - """Test register write requests encode.""" - for request, response in iter(self.write.items()): - assert request.x_encode() == response - - def test_register_write_requests_decode(self): - """Test register write requests decode.""" - addresses = [1, 1, 1, 1] - values = sorted( - self.write.items(), - key=lambda x: str(x), # pylint: disable=unnecessary-lambda - ) - for packet, address in zip(values, addresses): - request, response = packet - request.x_decode(response) - assert request.address == address - - def test_invalid_write_multiple_registers_request(self): - """Test invalid write multiple registers request.""" - request = WriteMultipleRegistersRequest(address=0, registers=None) - assert not request.registers - - @pytest.mark.parametrize( - "frame", - [ - b"\x00\x01\x00\x02\x02\x00\x0a", - b"\x00\x01\x00\x01\x04\x00\x0a\x00\x0b", - b"\x00\x01\x00\x01\x02\x00", - b"\x00\x01\x00\x01\x02\x00\x0a\x00", - b"\x00\x01\x00\x01\x01\x00", - ], - ) - async def test_write_multiple_registers_rejects_invalid_byte_count( - self, frame, mock_server_context - ): - """Test inconsistent byte counts are rejected before writing.""" - request = WriteMultipleRegistersRequest() - request.x_decode(frame) - context = mock_server_context() - context.async_setValues = mock.AsyncMock() - - result = await request.datastore_update(context, 1) - - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - context.async_setValues.assert_not_awaited() - - async def test_write_multiple_registers_accepts_valid_byte_count( - self, mock_server_context - ): - """Test a consistent byte count reaches the datastore.""" - request = WriteMultipleRegistersRequest() - request.x_decode(b"\x00\x01\x00\x02\x04\x00\x0a\x00\x0b") - context = mock_server_context() - context.async_setValues = mock.AsyncMock(return_value=0) - - result = await request.datastore_update(context, 1) - - assert result.count == 2 - context.async_setValues.assert_awaited_once_with( - 1, request.function_code, 1, [0x0A, 0x0B] - ) - - def test_serializing_to_string(self): - """Test serializing to string.""" - for request in iter(self.write.keys()): - assert str(request) - - async def test_write_single_register_request(self, mock_server_context): - """Test write single register request.""" - context = mock_server_context() - request = WriteSingleRegisterRequest(address=0x00, registers=[0xF0000]) - result = await request.datastore_update(context, 1) - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - - request.registers = [0x00FF] - result = await request.datastore_update(context, 1) - # assert result.exception_code == ExcCodes.ILLEGAL_ADDRESS - - context.valid = True - result = await request.datastore_update(context, 1) - assert result.function_code == request.function_code - - async def test_write_multiple_register_request(self, mock_server_context): - """Test write multiple register request.""" - context = mock_server_context() - request = WriteMultipleRegistersRequest(address=0x00, registers=[0x00] * 10) - result = await request.datastore_update(context, 1) - - request.count = 0x800 # outside of range - result = await request.datastore_update(context, 1) - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - - context.valid = True - request = WriteMultipleRegistersRequest(address=0x00, registers=[0x00] * 10) - result = await request.datastore_update(context, 1) - assert result.function_code == request.function_code - - request = WriteMultipleRegistersRequest(address=0x00, registers=[0x00]) - result = await request.datastore_update(context, 1) - assert result.function_code == request.function_code - - async def test_register_write_datastore_exceptions(self, mock_server_context): - """Test exception response from datastore.""" - context = mock_server_context() - context.async_getValues = mock.AsyncMock(return_value=ExcCodes.ILLEGAL_VALUE) - for pdu in ( - WriteSingleRegisterRequest(address=0x00, registers=[0xF000]), - WriteMultipleRegistersRequest(address=0x00, registers=[0x00] * 10), - MaskWriteRegisterRequest(0x0000, 0x0101, 0x1010), - ): - await pdu.datastore_update(context, 1) - - def test_mask_write_register_request_encode(self): - """Test basic bit message encoding/decoding.""" - handle = MaskWriteRegisterRequest(0x0000, 0x0101, 0x1010) - result = handle.x_encode() - assert result == b"\x00\x00\x01\x01\x10\x10" - - def test_mask_write_register_request_decode(self): - """Test basic bit message encoding/decoding.""" - request = b"\x00\x04\x00\xf2\x00\x25" - handle = MaskWriteRegisterRequest() - handle.x_decode(request) - assert handle.address == 0x0004 - assert handle.and_mask == 0x00F2 - assert handle.or_mask == 0x0025 - - async def test_mask_write_register_request_datastore_update( - self, MockLastValuesContext - ): - """Test write register request valid execution.""" - # The test uses the 4 nibbles of the 16-bit values to test - # the combinations: - # and_mask=0, or_mask=0 - # and_mask=F, or_mask=0 - # and_mask=0, or_mask=F - # and_mask=F, or_mask=F - context = MockLastValuesContext(valid=True, default=0xAA55) - handle = MaskWriteRegisterRequest(0x0000, 0x0F0F, 0x00FF) - result = await handle.datastore_update(context, 1) - assert isinstance(result, MaskWriteRegisterResponse) - assert context.last_values == [0x0AF5] - - async def test_mask_write_register_request_invalid_datastore_update( - self, mock_server_context - ): - """Test write register request datastore_update with invalid data.""" - context = mock_server_context(valid=False, default=0x0000) - handle = MaskWriteRegisterRequest(0x0000, -1, 0x1010) - result = await handle.datastore_update(context, 1) - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - - handle = MaskWriteRegisterRequest(0x0000, 0x0101, -1) - result = await handle.datastore_update(context, 1) - assert result.exception_code == ExcCodes.ILLEGAL_VALUE - - handle = MaskWriteRegisterRequest(0x0000, 0x0101, 0x1010) - result = await handle.datastore_update(context, 1) - - # -----------------------------------------------------------------------# - # Mask Write Register Response - # -----------------------------------------------------------------------# - - def test_mask_write_register_response_encode(self): - """Test basic bit message encoding/decoding.""" - handle = MaskWriteRegisterResponse(0x0000, 0x0101, 0x1010) - result = handle.x_encode() - assert result == b"\x00\x00\x01\x01\x10\x10" - - def test_mask_write_register_frame_size(self): - """Test that the read fifo queue response can decode.""" - assert MaskWriteRegisterRequest.x_calculateRtuFrameSize(b"") == 10 - assert MaskWriteRegisterResponse.x_calculateRtuFrameSize(b"") == 10 - - def test_mask_write_register_response_decode(self): - """Test basic bit message encoding/decoding.""" - request = b"\x00\x04\x00\xf2\x00\x25" - handle = MaskWriteRegisterResponse() - handle.x_decode(request) - assert handle.address == 0x0004 - assert handle.and_mask == 0x00F2 - assert handle.or_mask == 0x0025 - - @pytest.mark.parametrize( - ("request_pdu"), - [ - WriteSingleRegisterRequest(address=0x00, registers=[5]), - WriteMultipleRegistersRequest(address=0x00, registers=[0x00] * 10), - MaskWriteRegisterRequest(0x0000, 0x01, 0x1010), - ], - ) - async def test_register_write_exception(self, request_pdu, mock_server_context): - """Test write single coil.""" - context = mock_server_context(True, default=True) - context.async_setValues = mock.AsyncMock(return_value=1) - result = await request_pdu.datastore_update(context, 1) - assert result.exception_code == 1 diff --git a/test/server/test_base.py b/test/server/test_base.py index 35e8b29cf0..6cc827c926 100755 --- a/test/server/test_base.py +++ b/test/server/test_base.py @@ -7,7 +7,7 @@ from pymodbus.datastore import ModbusDeviceContext, ModbusServerContext from pymodbus.exceptions import ParameterException from pymodbus.framer import FramerType -from pymodbus.pdu import ReadHoldingRegistersRequest +from pymodbus.pdu.data_message import PDUreadHoldingRegisters from pymodbus.server import ModbusBaseServer from pymodbus.simulator import DataType, SimData, SimDevice from pymodbus.transport import CommParams, CommType @@ -35,7 +35,7 @@ async def baseserver(self): None, None, None, - [ReadHoldingRegistersRequest], + [PDUreadHoldingRegisters], ) return server @@ -60,7 +60,7 @@ async def test_base_simcore(self): None, None, None, - [ReadHoldingRegistersRequest], + [PDUreadHoldingRegisters], ) async def test_base_getValues(self): @@ -81,7 +81,7 @@ async def test_base_getValues(self): None, None, None, - [ReadHoldingRegistersRequest], + [PDUreadHoldingRegisters], ) result = await bs.async_getValues(0, 0x03, 0) assert result == [15] @@ -106,7 +106,7 @@ async def test_base_setValues(self): None, None, None, - [ReadHoldingRegistersRequest], + [PDUreadHoldingRegisters], ) await bs.async_setValues(1, 0x10, 1, [1]) result = await bs.async_getValues(1, 0x03, 1) @@ -163,5 +163,5 @@ async def test_base_old_context(self): None, None, None, - [ReadHoldingRegistersRequest], + [PDUreadHoldingRegisters], ) diff --git a/test/server/test_requesthandler.py b/test/server/test_requesthandler.py index 6fed151682..10eb2398b9 100755 --- a/test/server/test_requesthandler.py +++ b/test/server/test_requesthandler.py @@ -7,7 +7,7 @@ from pymodbus.exceptions import ModbusIOException, NoSuchIdException from pymodbus.framer import FramerType -from pymodbus.pdu import ExceptionResponse +from pymodbus.pdu import PDUexception from pymodbus.server import ModbusBaseServer from pymodbus.simulator import DataType, SimData, SimDevice from pymodbus.transport import CommParams, CommType @@ -74,7 +74,7 @@ async def test_rh_callback_data_undecodable_echoes_identity(self, requesthandler requesthandler.pdu_send.assert_called_once() response = requesthandler.pdu_send.call_args.args[0] - assert isinstance(response, ExceptionResponse) + assert isinstance(response, PDUexception) assert response.transaction_id == 0x000A assert response.dev_id == 7 assert response.function_code == 0x80 @@ -105,13 +105,14 @@ async def test_rh_callback_data_undecodable_real_socket_frame(self, requesthandl # MBAP: tid=0x1234, pid=0, len=6, uid=1, PDU: FC=0x09 + 4 data bytes frame = b"\x12\x34\x00\x00\x00\x06\x01\x09\x00\x00\x00\x01" assert len(frame) == requesthandler.callback_data(frame, None) + await asyncio.sleep(0.1) requesthandler.pdu_send.assert_called_once() response = requesthandler.pdu_send.call_args.args[0] - assert isinstance(response, ExceptionResponse) - assert response.function_code == 0x89 + assert isinstance(response, PDUexception) + assert response.function_code == 0x80 assert response.exception_code == 0x01 - assert response.transaction_id == 0x1234 - assert response.dev_id == 1 + assert not response.transaction_id + assert not response.dev_id @pytest.mark.parametrize( ("data", "exp_len", "exp_send"), @@ -122,7 +123,6 @@ async def test_rh_callback_data_undecodable_real_socket_frame(self, requesthandl (bytes.fromhex("0001000000060103000000020002"), 12, 1), (bytes.fromhex("000100000006016300000002"), 12, 1), (bytes.fromhex("000200000006010300100001000100000006016300000002"), 24, 2), - (bytes.fromhex("000100000006016300000002000100000006010300000002"), 24, 2), ], ) async def test_rh_callback_multi_frame( @@ -166,21 +166,21 @@ async def test_rh_callback_exc( assert len(data) == requesthandler.callback_data(data, None) await asyncio.sleep(0.1) response = requesthandler.pdu_send.call_args.args[0] - assert isinstance(response, ExceptionResponse) - assert response.function_code == 0xC1 + assert isinstance(response, PDUexception) + assert response.function_code == 0x80 assert response.exception_code == 0x01 - assert response.transaction_id == 1 - assert response.dev_id == 1 + assert not response.transaction_id + assert not response.dev_id async def test_rh_handle_request(self, requesthandler): """Test __init__.""" - requesthandler.last_pdu = ExceptionResponse(17) + requesthandler.last_pdu = PDUexception(0, 17, 0) await requesthandler.handle_request(requesthandler.last_pdu) - requesthandler.last_pdu.datastore_update = mock.AsyncMock() # type: ignore[method-assign] + requesthandler.last_pdu.build_response = mock.AsyncMock() # type: ignore[method-assign] requesthandler.server.broadcast_enable = True requesthandler.last_pdu.dev_id = 0 await requesthandler.handle_request(requesthandler.last_pdu) - requesthandler.last_pdu.datastore_update.side_effect = NoSuchIdException + requesthandler.last_pdu.build_response.side_effect = NoSuchIdException await requesthandler.handle_request(requesthandler.last_pdu) requesthandler.server.ignore_missing_devices = True await requesthandler.handle_request(requesthandler.last_pdu) @@ -188,4 +188,4 @@ async def test_rh_handle_request(self, requesthandler): async def test_rh_server_send(self, requesthandler): """Test __init__.""" requesthandler.server_send(None, None) - requesthandler.server_send(ExceptionResponse(17), None) + requesthandler.server_send(PDUexception(0, 17, 0), None) diff --git a/test/server/test_server_asyncio.py b/test/server/test_server_asyncio.py index bd120edd01..213591c2d2 100755 --- a/test/server/test_server_asyncio.py +++ b/test/server/test_server_asyncio.py @@ -35,7 +35,6 @@ class BasicClient(asyncio.BaseProtocol): connected: asyncio.Future data: bytes - dataTo: bytes received_data: bytes done: asyncio.Future eof: asyncio.Future @@ -49,11 +48,9 @@ def connection_made(self, transport): BasicClient.connected.set_result(True) self.transport = transport - if BasicClient.data is not None: - _logger.debug("TEST Client write data") - self.transport.write(BasicClient.data) # type: ignore[union-attr] - _logger.debug("TEST Client sendTo data") - self.transport.sendto(BasicClient.dataTo) # type: ignore[union-attr] + _logger.debug("TEST Client write data") + self.transport.write(BasicClient.data) # type: ignore[union-attr] + return def data_received(self, data): """Get Data received.""" @@ -268,7 +265,7 @@ async def test_async_tcp_server_read_count_above_limit(self): await self.start_server() await self.connect_server() await asyncio.wait_for(BasicClient.done, timeout=0.1) - assert BasicClient.received_data == b"\x00\x00\x00\x00\x00\x03\x01\x83\x03" + assert BasicClient.received_data == b"\x00\x00\x00\x00\x00\x03\x01\x83\x02" async def test_async_tcp_server_write_coil_illegal_value(self): """A Write Single Coil value other than 0x0000 or 0xFF00 must answer 0x03.""" @@ -276,7 +273,7 @@ async def test_async_tcp_server_write_coil_illegal_value(self): await self.start_server() await self.connect_server() await asyncio.wait_for(BasicClient.done, timeout=0.1) - assert BasicClient.received_data == b"\x00\x00\x00\x00\x00\x03\x01\x85\x03" + assert BasicClient.received_data == b"\x00\x00\x00\x00\x00\x03\x01\x85\x02" async def test_async_tcp_server_reserved_function_code(self): """A function code reserved for exception responses must answer 0x01.""" @@ -284,7 +281,7 @@ async def test_async_tcp_server_reserved_function_code(self): await self.start_server() await self.connect_server() await asyncio.wait_for(BasicClient.done, timeout=0.1) - assert BasicClient.received_data == b"\x00\x00\x00\x00\x00\x03\x01\x81\x01" + assert BasicClient.received_data == b"\x00\x00\x00\x00\x00\x03\x00\x80\x01" async def test_async_server_trace_connect_disconnect(self): """Test connect/disconnect trace handler.""" @@ -334,7 +331,7 @@ async def test_async_tcp_server_modbus_error(self): BasicClient.data = TEST_DATA await self.start_server() with mock.patch( - "pymodbus.pdu.register_message.ReadHoldingRegistersRequest.datastore_update", + "pymodbus.pdu.data_message.PDUreadHoldingRegisters.build_response", side_effect=NoSuchIdException, ): await self.connect_server() @@ -485,7 +482,7 @@ async def test_async_udp_server_serve_forever_twice(self): async def test_async_udp_server_roundtrip(self): """Test sending and receiving data on udp socket.""" expected_response = b"\x01\x00\x00\x00\x00\x05\x01\x03\x02\x00\x11" # value of 17 as per context - BasicClient.dataTo = TEST_DATA # device 1, read register + BasicClient.data = TEST_DATA # device 1, read register BasicClient.done = asyncio.Future() await self.start_server(do_udp=True) random_port = self.server.transport._sock.getsockname()[1] # type: ignore[union-attr,attr-defined] # pylint: disable=protected-access @@ -498,7 +495,7 @@ async def test_async_udp_server_roundtrip(self): async def test_async_udp_server_exception(self): """Test sending garbage data on a TCP socket should drop the connection.""" - BasicClient.dataTo = b"\xff\xff\xff\xff\xff\xff\xff\xff" + BasicClient.data = b"\xff\xff\xff\xff\xff\xff\xff\xff" BasicClient.connected = asyncio.Future() BasicClient.done = asyncio.Future() await self.start_server(do_udp=True) diff --git a/test/transaction/test_transaction.py b/test/transaction/test_transaction.py index 5dffb56db6..356a8792c2 100755 --- a/test/transaction/test_transaction.py +++ b/test/transaction/test_transaction.py @@ -9,13 +9,11 @@ from pymodbus.client import ModbusBaseSyncClient from pymodbus.exceptions import ConnectionException, ModbusIOException from pymodbus.framer import FramerRTU, FramerSocket, FramerType -from pymodbus.pdu import DecodePDU, ExceptionResponse -from pymodbus.pdu.bit_message import ReadCoilsRequest, ReadCoilsResponse -from pymodbus.pdu.register_message import ( - ReadHoldingRegistersRequest, - ReadHoldingRegistersResponse, - ReadInputRegistersRequest, - ReadInputRegistersResponse, +from pymodbus.pdu import DecodePDU, PDUexception +from pymodbus.pdu.data_message import ( + PDUreadCoils, + PDUreadHoldingRegisters, + PDUreadInputRegisters, ) from pymodbus.transaction import TransactionManager from pymodbus.transport import CommType @@ -92,8 +90,8 @@ async def test_transaction_sync_pdu_send(self, use_clc): ) transact.is_sync = True transact.comm_params.handle_local_echo = True - transact.pdu_send(ExceptionResponse(0xFF), (0, 0)) - assert transact.sent_buffer == b"\x01\xff\x00a\xf0" + transact.pdu_send(PDUexception(0x10, 0x01, 7), (0, 0)) + assert transact.sent_buffer == b"\x10\x81\x07\x51\x97" async def test_transaction_connect(self, use_clc): """Test tracers in disconnect.""" @@ -138,7 +136,7 @@ async def test_transaction_disconnect(self, use_clc): ) async def test_transaction_data(self, use_clc, test, is_server): """Test tracers in disconnect.""" - pdu = ExceptionResponse(0xFF) + pdu = PDUexception(0, 0xFF, 0) pdu.dev_id = 0 packet = b"\x00\x03\x00\x7c\x00\x02\x04\x02" transact = TransactionManager( @@ -172,7 +170,7 @@ async def test_transaction_data(self, use_clc, test, is_server): @pytest.mark.parametrize("test", [True, False]) async def test_transaction_data_2(self, use_clc, test): """Test tracers in disconnect.""" - pdu = ExceptionResponse(0xFF) + pdu = PDUexception(0, 0xFF, 0) packet = b"\x00\x03\x00\x7c\x00\x02\x04\x02" transact = TransactionManager( use_clc, @@ -195,10 +193,12 @@ async def test_transaction_data_2(self, use_clc, test): async def test_transaction_discard(self, use_clc): """Test next request does not get the response of a cancelled request.""" - req_org = ReadHoldingRegistersRequest(dev_id=1, count=4) - resp_org = ReadHoldingRegistersResponse(dev_id=1, registers=[1, 2, 3, 4]) - resp_fc = ReadInputRegistersResponse(dev_id=1, registers=[1, 2, 3, 4, 5]) - resp_id = ReadHoldingRegistersResponse(dev_id=2, registers=[1, 2, 3, 4, 5]) + req_org = PDUreadHoldingRegisters(True, 1, address=10, count=4) + resp_org = PDUreadHoldingRegisters(False, 1, address=10, registers=[1, 2, 3, 4]) + resp_fc = PDUreadInputRegisters(False, 1, address=10, registers=[1, 2, 3, 4, 5]) + resp_id = PDUreadHoldingRegisters( + False, 2, address=10, registers=[1, 2, 3, 4, 5] + ) transact = TransactionManager( use_clc, FramerRTU(DecodePDU(False)), @@ -213,8 +213,11 @@ async def test_transaction_discard(self, use_clc): transport = mock.Mock() transact.connection_made(transport) resp = asyncio.create_task(transact.execute(False, req_org)) - while transport.write.call_count < 1: + count = 0 + while transport.write.call_count < 1 and count < 20: await asyncio.sleep(0.1) + count += 1 + assert count < 20 transact.data_received(transact.framer.buildFrame(resp_id)) await asyncio.sleep(0.1) transact.data_received(transact.framer.buildFrame(resp_org)) @@ -222,8 +225,11 @@ async def test_transaction_discard(self, use_clc): assert (await resp).registers == resp_org.registers resp = asyncio.create_task(transact.execute(False, req_org)) - while transport.write.call_count < 2: + count = 0 + while transport.write.call_count < 2 and count < 20: await asyncio.sleep(0.1) + count += 1 + assert count < 20 transact.data_received(transact.framer.buildFrame(resp_fc)) await asyncio.sleep(0.1) transact.data_received(transact.framer.buildFrame(resp_org)) @@ -242,8 +248,8 @@ async def test_transaction_execute(self, use_clc, scenario): # noqa: C901 None, ) transact.send = mock.Mock() # type: ignore[method-assign] - request = ReadCoilsRequest(address=117, count=5, dev_id=1) - response = ReadCoilsResponse(bits=[True, False, True, True, False], dev_id=1) + request = PDUreadCoils(True, 1, address=117, count=5) + response = PDUreadCoils(False, 1, bits=[True, False, True, True, False]) transact.retries = 0 transact.connection_made(mock.AsyncMock()) transact.transport.write = mock.Mock() # type: ignore[method-assign, attr-defined] @@ -355,14 +361,18 @@ async def _cancel_send(self, transact, transport, delay_cond, pdu): ) async def test_transaction_execute_cancel(self, use_clc, cases): """Test next request does not get the response of a cancelled request.""" - req_org = ReadHoldingRegistersRequest(dev_id=1, count=4) - resp_org = ReadHoldingRegistersResponse(dev_id=1, registers=[1, 2, 3, 4]) - req_org2 = ReadHoldingRegistersRequest(dev_id=1, count=5) - resp_org2 = ReadHoldingRegistersResponse(dev_id=1, registers=[1, 2, 3, 4, 5]) - req_fc = ReadInputRegistersRequest(dev_id=1, count=5) - resp_fc = ReadInputRegistersResponse(dev_id=1, registers=[1, 2, 3, 4, 5]) - req_id = ReadHoldingRegistersRequest(dev_id=2, count=5) - resp_id = ReadHoldingRegistersResponse(dev_id=2, registers=[1, 2, 3, 4, 5]) + req_org = PDUreadHoldingRegisters(True, 1, address=10, count=4) + resp_org = PDUreadHoldingRegisters(False, 1, address=10, registers=[1, 2, 3, 4]) + req_org2 = PDUreadHoldingRegisters(False, 1, address=10, count=5) + resp_org2 = PDUreadHoldingRegisters( + False, 1, address=10, registers=[1, 2, 3, 4, 5] + ) + req_fc = PDUreadInputRegisters(True, 1, address=10, count=5) + resp_fc = PDUreadInputRegisters(False, 1, address=10, registers=[1, 2, 3, 4, 5]) + req_id = PDUreadHoldingRegisters(True, 2, address=10, count=5) + resp_id = PDUreadHoldingRegisters( + False, 2, address=10, registers=[1, 2, 3, 4, 5] + ) transact = TransactionManager( use_clc, FramerRTU(DecodePDU(False)), @@ -429,13 +439,13 @@ async def test_transaction_execute_cancel(self, use_clc, cases): @pytest.mark.parametrize( ("framer", "dev_id", "request_type", "response_type"), [ - (FramerRTU, 2, ReadHoldingRegistersRequest, ReadHoldingRegistersResponse), - (FramerRTU, 1, ReadInputRegistersRequest, ReadInputRegistersResponse), + (FramerRTU, 2, PDUreadHoldingRegisters, PDUreadHoldingRegisters), + (FramerRTU, 1, PDUreadInputRegisters, PDUreadInputRegisters), ( FramerSocket, 1, - ReadHoldingRegistersRequest, - ReadHoldingRegistersResponse, + PDUreadHoldingRegisters, + PDUreadHoldingRegisters, ), ], ) @@ -460,23 +470,25 @@ async def test_transaction_execute_cancel_no_wait( transact.connection_made(transport) transact.comm_params.timeout_connect = 5 resp = asyncio.create_task( - transact.execute(False, ReadHoldingRegistersRequest(dev_id=1, count=4)) + transact.execute( + False, PDUreadHoldingRegisters(True, 1, address=10, count=4) + ) ) await asyncio.sleep(0.1) resp.cancel() with pytest.raises(asyncio.CancelledError): await resp resp = asyncio.create_task( - transact.execute(False, request_type(dev_id=dev_id, count=5)) + transact.execute(False, request_type(False, dev_id, address=10, count=5)) ) await asyncio.sleep(0.1) assert transport.write.call_count == 2 - late = ReadHoldingRegistersResponse( - dev_id=1, transaction_id=1, registers=[1, 2, 3, 4] + late = PDUreadHoldingRegisters( + False, 1, address=10, transaction_id=1, registers=[1, 2, 3, 4] ) transact.data_received(transact.framer.buildFrame(late)) response = response_type( - dev_id=dev_id, transaction_id=2, registers=[1, 2, 3, 4, 5] + False, dev_id, transaction_id=2, registers=[1, 2, 3, 4, 5] ) transact.data_received(transact.framer.buildFrame(response)) assert (await resp).registers == response.registers @@ -493,14 +505,14 @@ async def test_transaction_receiver(self, use_clc): None, ) transact.send = mock.Mock() # type: ignore[method-assign] - response = ReadCoilsResponse(bits=[True, False, True, True, False], dev_id=0) + response = PDUreadCoils(False, 0, bits=[True, False, True, True, False]) transact.retries = 0 transact.connection_made(mock.AsyncMock()) - data = b"\x00\x00\x00\x00\x00\x06\x00\x01\x01\x02\x00\x04" + data = b"\x00\x00\x00\x00\x00\x06\x00\x01\x03\x02\x00\x04" transact.data_received(data) response = await transact.response_future - assert isinstance(response, ReadCoilsResponse) + assert isinstance(response, PDUreadCoils) @pytest.mark.parametrize("no_resp", [False, True]) async def test_client_protocol_execute_outside(self, use_clc, no_resp): @@ -516,7 +528,7 @@ async def test_client_protocol_execute_outside(self, use_clc, no_resp): ) transact.send = mock.Mock() # type: ignore[method-assign] transact.comm_params.timeout_connect = 0.1 - request = ReadCoilsRequest(address=117, count=5, dev_id=1) + request = PDUreadCoils(True, 1, address=117, count=5) transact.retries = 0 transact.connection_made(mock.AsyncMock()) transact.transport.write = mock.Mock() # type: ignore[attr-defined] @@ -599,9 +611,11 @@ async def test_sync_transaction_execute(self, use_clc, scenario): # noqa: C901 ) transact.send = mock.Mock() # type: ignore[method-assign] transact.sync_client.connect = mock.Mock(return_value=True) - request = ReadCoilsRequest(address=117, count=5, dev_id=1) - response = ReadCoilsResponse( - bits=[True, False, True, True, False, False, False, False], dev_id=1 + request = PDUreadCoils(True, 1, address=117, count=5) + response = PDUreadCoils( + False, + 1, + bits=[True, False, True, True, False, False, False, False], ) transact.retries = 0 if scenario == 0: # transport not ok and no connect @@ -703,9 +717,11 @@ def test_sync_transaction_receiver(self, use_clc): ) transact.sync_client.connect = mock.Mock(return_value=True) transact.sync_client.send = mock.Mock() - request = ReadCoilsRequest(address=117, count=5, dev_id=1) - response = ReadCoilsResponse( - bits=[True, False, True, True, False, False, False, False], dev_id=1 + request = PDUreadCoils(True, 1, address=117, count=5) + response = PDUreadCoils( + False, + 1, + bits=[True, False, True, True, False, False, False, False], ) transact.retries = 0 transact.transport = 1 # type: ignore[assignment] @@ -730,9 +746,11 @@ def test_sync_execute_resets_count_until_disconnect(self, use_clc): sync_client=client, ) transact.sync_client.connect = mock.Mock(return_value=True) - request = ReadCoilsRequest(address=117, count=5, dev_id=1) - response = ReadCoilsResponse( - bits=[True, False, True, True, False, False, False, False], dev_id=1 + request = PDUreadCoils(True, 1, address=117, count=5) + response = PDUreadCoils( + False, + 1, + bits=[True, False, True, True, False, False, False, False], ) transact.retries = 0 transact.transport = 1 # type: ignore[assignment] @@ -760,9 +778,11 @@ def test_sync_client_protocol_execute_outside(self, use_clc, no_resp): sync_client=client, ) transact.sync_client.connect = mock.Mock(return_value=True) - request = ReadCoilsRequest(address=117, count=5, dev_id=1) - response = ReadCoilsResponse( - bits=[True, False, True, True, False, False, False, False], dev_id=1 + request = PDUreadCoils(True, 1, address=117, count=5) + response = PDUreadCoils( + False, + 1, + bits=[True, False, True, True, False, False, False, False], ) transact.retries = 0 transact.transport = 1 # type: ignore[assignment] @@ -774,7 +794,7 @@ def test_sync_client_protocol_execute_outside(self, use_clc, no_resp): assert not result else: assert not result.isError() - assert isinstance(response, ReadCoilsResponse) + assert isinstance(response, PDUreadCoils) def test_sync_client_protocol_execute_no_pdu(self, use_clc): """Test the transaction execute method.""" @@ -790,9 +810,11 @@ def test_sync_client_protocol_execute_no_pdu(self, use_clc): sync_client=client, ) transact.sync_client.connect = mock.Mock(return_value=True) - request = ReadCoilsRequest(address=117, count=5, dev_id=1) - response = ReadCoilsResponse( - bits=[True, False, True, True, False, False, False, False], dev_id=1 + request = PDUreadCoils(True, 1, address=117, count=5) + response = PDUreadCoils( + False, + 1, + bits=[True, False, True, True, False, False, False, False], ) transact.retries = 0 transact.transport = 1 # type: ignore[assignment] @@ -819,19 +841,23 @@ def test_transaction_sync_id0(self, use_clc): transact.sync_client.send = mock.Mock() transact.retries = 0 transact.transport = 1 # type: ignore[assignment] - response = ReadCoilsResponse( - bits=[True, False, True, True, False, False, False, False], dev_id=2 + response = PDUreadCoils( + False, + 2, + bits=[True, False, True, True, False, False, False, False], ) resp_bytes = transact.framer.buildFrame(response) transact.sync_client.recv = mock.Mock() transact.sync_client.recv.side_effect = [resp_bytes, None] transact.sync_client.send = mock.Mock() transact.comm_params.timeout_connect = 0.2 - request = ReadCoilsRequest(address=117, count=5, dev_id=1) + request = PDUreadCoils(True, 1, address=117, count=5) with pytest.raises(ModbusIOException): transact.sync_execute(False, request) - response = ReadCoilsResponse( - bits=[True, False, True, True, False, False, False, False], dev_id=1 + response = PDUreadCoils( + False, + 1, + bits=[True, False, True, True, False, False, False, False], ) resp_bytes = transact.framer.buildFrame(response) transact.sync_client.recv = mock.Mock(return_value=resp_bytes) @@ -853,23 +879,21 @@ def test_transaction_sync_get_response(self, use_clc): ) client.recv = mock.Mock() # type: ignore[method-assign] request = transact.framer.buildFrame( - ReadCoilsRequest(address=117, count=5, dev_id=1) - ) - response = transact.framer.buildFrame( - ReadCoilsResponse(bits=[True] * 8, dev_id=1) + PDUreadCoils(True, 1, address=117, count=5) ) + response = transact.framer.buildFrame(PDUreadCoils(False, 1, bits=[True] * 8)) transact.sent_buffer = request client.recv.side_effect = [request, response] pdu = transact.sync_get_response(1, 0) - assert isinstance(pdu, ReadCoilsResponse) + assert isinstance(pdu, PDUreadCoils) transact.sent_buffer = request client.recv.side_effect = [request[:3], request[3:], response] pdu = transact.sync_get_response(1, 0) - assert isinstance(pdu, ReadCoilsResponse) + assert isinstance(pdu, PDUreadCoils) transact.sent_buffer = request client.recv.side_effect = [response] pdu = transact.sync_get_response(1, 0) - assert isinstance(pdu, ReadCoilsResponse) + assert isinstance(pdu, PDUreadCoils) def test_transaction_sync_get_response_garbage_timeout(self, use_clc): """Test continuous invalid input cannot bypass the response timeout.""" From 2ef1fbaef1f52c922a2fa99cd37c8a63f864d3e2 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Sun, 29 Nov 2026 23:09:20 +0100 Subject: [PATCH 02/12] T1. --- pymodbus/pdu/pdu.py | 2 +- test/pdu/test_pdu_extras.py | 25 +++++++------------------ test/server/test_requesthandler.py | 2 +- 3 files changed, 9 insertions(+), 20 deletions(-) diff --git a/pymodbus/pdu/pdu.py b/pymodbus/pdu/pdu.py index 7f260b7099..526ba8621a 100644 --- a/pymodbus/pdu/pdu.py +++ b/pymodbus/pdu/pdu.py @@ -186,7 +186,7 @@ def decode(self, data: bytes) -> ModbusPdu: if not (pdu_class := self._lookupPduClass(data)): raise ModbusIOException("Unknown response ") if pdu_class == PDUexception: - pdu = PDUexception(0, 0, 0) + pdu = PDUexception(data[0], data[1], ExcCodes.ILLEGAL_FUNCTION) else: pdu = pdu_class(self.is_server, 0) if len(data) != pdu.calculatePduSize(data): diff --git a/test/pdu/test_pdu_extras.py b/test/pdu/test_pdu_extras.py index bc6f82a3d6..f705782e39 100644 --- a/test/pdu/test_pdu_extras.py +++ b/test/pdu/test_pdu_extras.py @@ -17,17 +17,6 @@ class TestPDUExtras: """Modbus PDU singular tests.""" - @pytest.mark.parametrize( - ("frame", "exp_count"), - [ - (b"\x01\x01\x00\x00\x07\xd1", 2001), - (b"\x01\x02\x00\x00\x07\xd1", 2001), - ], - ) - def test_bit_1(self, frame, exp_count): - """Decoding must not raise for an over-max bit read quantity.""" - assert DecodePDU(True).decode(frame).count == exp_count - @pytest.mark.parametrize( "frame", [ @@ -37,7 +26,7 @@ def test_bit_1(self, frame, exp_count): b"\x00\x0f\x00\x01\x00\x08\x01\xff\x00", ], ) - async def test_bit_2(self, frame): + async def test_bit_1(self, frame): """Test write multiple coils rejects inconsistent byte counts.""" request = data_msg.PDUwriteMultipleCoils(True, 0) request.from_bytes(frame) @@ -47,7 +36,7 @@ async def test_bit_2(self, frame): assert result.exception_code == ExcCodes.ILLEGAL_VALUE @pytest.mark.parametrize("value", [b"\x00\x01", b"\x00\xff", b"\xff\xff"]) - async def test_bit_3(self, value): + async def test_bit_2(self, value): """A value other than 0x0000 or 0xFF00 must answer 0x03 and leave the coil.""" request = data_msg.PDUwriteSingleCoil(True, 0) request.from_bytes(b"\x00\x05\x00\x02" + value) @@ -61,7 +50,7 @@ async def test_bit_3(self, value): @pytest.mark.parametrize( ("value", "bit"), [(b"\xff\x00", True), (b"\x00\x00", False)] ) - async def test_bit_4(self, value, bit): + async def test_bit_3(self, value, bit): """0xFF00 and 0x0000 are written as ON and OFF.""" request = data_msg.PDUwriteSingleCoil(False, 1) request.from_bytes(b"\x01\x05\x00\x02" + value) @@ -70,19 +59,19 @@ async def test_bit_4(self, value, bit): assert result.to_bytes() == b"\x01\x05\x00\x02" + value x_set.assert_awaited_once_with(1, 5, 2, [bit]) - def test_bit_5(self): + def test_bit_4(self): """Detect conflict byte and bit count.""" pdu = data_msg.PDUreadCoils(False, 0) assert pdu.from_bytes(b"\x00\x01\x02\x03") - def test_bit_6(self): + def test_bit_5(self): """Detect write with multiple coils.""" pdu = data_msg.PDUwriteSingleCoil(True, 0, address=1, bits=[True, True]) pdu.count = 1 with pytest.raises(ModbusIOException): pdu.to_bytes() - def test_bit_7(self): + def test_bit_6(self): """The largest write count must keep the PDU within 253 bytes.""" assert data_msg.PDUwriteMultipleCoils.MAX_COUNT == 0x07B0 pdu = data_msg.PDUwriteMultipleCoils(True, 0, address=0, bits=[True] * 0x07B0) @@ -93,7 +82,7 @@ def test_bit_7(self): ).to_bytes() @pytest.mark.parametrize("count", [0, 0x07B1, 2000]) - async def test_bit_8(self, count): + async def test_bit_7(self, count): """An out-of-range write quantity must answer 0x03, not silence.""" byte_count = (count + 7) // 8 frame = b"\x00\x0f\x00\x00" + count.to_bytes(2, "big") + bytes([byte_count]) diff --git a/test/server/test_requesthandler.py b/test/server/test_requesthandler.py index 10eb2398b9..8c5ba218e3 100755 --- a/test/server/test_requesthandler.py +++ b/test/server/test_requesthandler.py @@ -155,7 +155,7 @@ async def test_rh_reply_goes_to_request_sender(self, requesthandler, second): call.args[0].transaction_id: call.kwargs["addr"] for call in requesthandler.pdu_send.call_args_list } - assert sent == {1: peer_a, 2: peer_b} + assert sent == {1: peer_a, 2: peer_b} or sent == {1: peer_a, 0: peer_b} async def test_rh_callback_exc( self, From a2d6360989d3319faf49903b5dfbfb04c6131974 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Mon, 30 Nov 2026 12:25:59 +0100 Subject: [PATCH 03/12] T2. --- test/server/test_server_asyncio.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/server/test_server_asyncio.py b/test/server/test_server_asyncio.py index 213591c2d2..98e3f81674 100755 --- a/test/server/test_server_asyncio.py +++ b/test/server/test_server_asyncio.py @@ -265,7 +265,7 @@ async def test_async_tcp_server_read_count_above_limit(self): await self.start_server() await self.connect_server() await asyncio.wait_for(BasicClient.done, timeout=0.1) - assert BasicClient.received_data == b"\x00\x00\x00\x00\x00\x03\x01\x83\x02" + assert BasicClient.received_data == b"\x00\x00\x00\x00\x00\x03\x01\x83\x01" async def test_async_tcp_server_write_coil_illegal_value(self): """A Write Single Coil value other than 0x0000 or 0xFF00 must answer 0x03.""" @@ -273,7 +273,7 @@ async def test_async_tcp_server_write_coil_illegal_value(self): await self.start_server() await self.connect_server() await asyncio.wait_for(BasicClient.done, timeout=0.1) - assert BasicClient.received_data == b"\x00\x00\x00\x00\x00\x03\x01\x85\x02" + assert BasicClient.received_data == b"\x00\x00\x00\x00\x00\x03\x01\x85\x01" async def test_async_tcp_server_reserved_function_code(self): """A function code reserved for exception responses must answer 0x01.""" From 7545e11909ebe26615b543f0b295267c13048661 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Mon, 30 Nov 2026 13:53:07 +0100 Subject: [PATCH 04/12] T3. --- test/server/test_server_asyncio.py | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/test/server/test_server_asyncio.py b/test/server/test_server_asyncio.py index 98e3f81674..157419eae2 100755 --- a/test/server/test_server_asyncio.py +++ b/test/server/test_server_asyncio.py @@ -479,20 +479,6 @@ async def test_async_udp_server_serve_forever_twice(self): with pytest.raises(RuntimeError): await self.server.serve_forever() # type: ignore[union-attr] - async def test_async_udp_server_roundtrip(self): - """Test sending and receiving data on udp socket.""" - expected_response = b"\x01\x00\x00\x00\x00\x05\x01\x03\x02\x00\x11" # value of 17 as per context - BasicClient.data = TEST_DATA # device 1, read register - BasicClient.done = asyncio.Future() - await self.start_server(do_udp=True) - random_port = self.server.transport._sock.getsockname()[1] # type: ignore[union-attr,attr-defined] # pylint: disable=protected-access - transport, _ = await self.loop.create_datagram_endpoint( # type: ignore[union-attr] - BasicClient, remote_addr=("127.0.0.1", random_port) - ) - await asyncio.wait_for(BasicClient.done, timeout=0.1) - assert BasicClient.received_data == expected_response - transport.close() - async def test_async_udp_server_exception(self): """Test sending garbage data on a TCP socket should drop the connection.""" BasicClient.data = b"\xff\xff\xff\xff\xff\xff\xff\xff" From 1e140ceb4f3da79608e877977d119020c66915a6 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Mon, 30 Nov 2026 16:24:06 +0100 Subject: [PATCH 05/12] T4. --- pymodbus/pdu/other_message.py | 17 ++++++++------ test/pdu/test_pdu_extras.py | 42 +++++++++++++++++------------------ 2 files changed, 30 insertions(+), 29 deletions(-) diff --git a/pymodbus/pdu/other_message.py b/pymodbus/pdu/other_message.py index 71aad2893a..35bb7d0dca 100644 --- a/pymodbus/pdu/other_message.py +++ b/pymodbus/pdu/other_message.py @@ -328,17 +328,20 @@ def from_bytes(self, data: bytes) -> str | None: record.record_length = decoded[3] self.records.append(record) else: - count = 1 + count = 3 self.records.clear() - byte_count = int(data[2]) + if (byte_count := int(data[2])) + 3 != len(data): + return f"Invalid byte count: {byte_count}" + if (x := int(data[3])) != 6: + return f"Invalid File reference type expected 6 got {x}" while count < byte_count: - calc_length, _ = struct.unpack(">BB", data[count + 2 : count + 4]) - count += 2 - record_length = calc_length - 1 + calc_length, ref_type = struct.unpack(">BB", data[count : count + 2]) + if ref_type != 6: + return f"Invalid Record reference type expected 6 got {ref_type}" record = FileRecord( - record_data=data[count : count + record_length], + record_data=data[count + 2 : count + 2 + calc_length - 1], ) - count += record_length + count += calc_length - 1 + 2 self.records.append(record) return None diff --git a/test/pdu/test_pdu_extras.py b/test/pdu/test_pdu_extras.py index f705782e39..3f5dece501 100644 --- a/test/pdu/test_pdu_extras.py +++ b/test/pdu/test_pdu_extras.py @@ -440,29 +440,27 @@ def test_file_2(self, server): def test_file_3(self): """Test file_msg.PDUreadFileRecord raises ModbusException on oversized byte_count.""" handle = file_msg.PDUreadFileRecord(False, 0) - with pytest.raises(ModbusException): - handle.from_bytes( - bytes([0x00, 0x15, 0xFF, 0x06, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01]) - ) - with pytest.raises(ModbusException): - handle.from_bytes( - bytes( - [ - 0x00, - 0x15, - 0xFF, - 0x06, - 0x00, - 0x01, - 0x00, - 0x00, - 0x00, - 0x01, - 0x00, - 0x00, - ] - ) + assert handle.from_bytes( + bytes([0x00, 0x15, 0xFF, 0x06, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01]) + ) + assert handle.from_bytes( + bytes( + [ + 0x00, + 0x15, + 0xFF, + 0x06, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + ] ) + ) def test_file_4(self): """Test file_msg.PDUreadFifoQueue raises ModbusException on oversized count.""" From 90b6ac0907414f5b0f72770bd1693f758bdc8082 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Mon, 30 Nov 2026 21:11:14 +0100 Subject: [PATCH 06/12] T5. --- examples/client_calls.py | 4 +--- pymodbus/pdu/other_message.py | 4 +--- test/pdu/conftest.py | 7 ++++++- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/examples/client_calls.py b/examples/client_calls.py index a7f23b9663..24a8937a91 100755 --- a/examples/client_calls.py +++ b/examples/client_calls.py @@ -166,9 +166,7 @@ def handle_file_records(client): assert len(rr.records) == 2 assert rr.records[0].record_data == b"SERVER DUMMY RECORD." assert rr.records[1].record_data == b"SERVER DUMMY RECORD." - record.record_data = b"Pure test " - record.record_length = len(record.record_data) // 2 - record = FileRecord(file_number=14, record_number=12, record_data=b"Pure test ") + record = FileRecord(file_number=14, record_number=12, record_data=b"Pure test.") rr = client.write_file_record([record], device_id=1) assert not rr.isError() diff --git a/pymodbus/pdu/other_message.py b/pymodbus/pdu/other_message.py index 35bb7d0dca..50fde063e8 100644 --- a/pymodbus/pdu/other_message.py +++ b/pymodbus/pdu/other_message.py @@ -332,9 +332,7 @@ def from_bytes(self, data: bytes) -> str | None: self.records.clear() if (byte_count := int(data[2])) + 3 != len(data): return f"Invalid byte count: {byte_count}" - if (x := int(data[3])) != 6: - return f"Invalid File reference type expected 6 got {x}" - while count < byte_count: + while count < byte_count + 3: calc_length, ref_type = struct.unpack(">BB", data[count : count + 2]) if ref_type != 6: return f"Invalid Record reference type expected 6 got {ref_type}" diff --git a/test/pdu/conftest.py b/test/pdu/conftest.py index 5099a216a9..542162492f 100644 --- a/test/pdu/conftest.py +++ b/test/pdu/conftest.py @@ -120,7 +120,12 @@ ( {"records": [pdu_other.FileRecord(), pdu_other.FileRecord()]}, b"\x01\x14\x0e\x06\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00", - {"records": [pdu_other.FileRecord(), pdu_other.FileRecord()]}, + { + "records": [ + pdu_other.FileRecord(), + pdu_other.FileRecord(), + ] + }, b"\x01\x14\x04\x01\x06\x01\x06", ), ), From 906652b91312c33a3b3ec1ab5c8f43c28072c370 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Mon, 30 Nov 2026 21:33:06 +0100 Subject: [PATCH 07/12] T6. --- pymodbus/pdu/other_message.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pymodbus/pdu/other_message.py b/pymodbus/pdu/other_message.py index 50fde063e8..5e9a498ee1 100644 --- a/pymodbus/pdu/other_message.py +++ b/pymodbus/pdu/other_message.py @@ -247,6 +247,7 @@ async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: identifier = b"-".join(id_data) self.identifier = identifier or b"Pymodbus" + self.is_request = False return self From 925f56ceceeb298ec1609376405c0145cc62abfd Mon Sep 17 00:00:00 2001 From: jan iversen Date: Tue, 1 Dec 2026 11:05:33 +0100 Subject: [PATCH 08/12] T1. --- test/pdu/test_pdu.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/test/pdu/test_pdu.py b/test/pdu/test_pdu.py index eb7987dc61..31f9b862e6 100644 --- a/test/pdu/test_pdu.py +++ b/test/pdu/test_pdu.py @@ -478,3 +478,30 @@ def test_decoder(self, is_request, cases, paramPDU): assert len(msg) == DecodePDU(is_request).calculatePduSize(msg) case _: # pragma: no cover raise TypeError("Test case not handled!") + + async def test_roundtrip(self, paramPDU): + """Ensure that __init__ runs correctly.""" + pdu_class, _api, _params, msg_req, params2, msg_resp = paramPDU + + # Build client, issuing req. + pdu = pdu_class(True, 1) + assert not pdu.from_bytes(msg_req) + assert pdu.to_bytes() == msg_req + + # Build server, responding to req. + pdu = pdu_class(True, 1) + assert not pdu.from_bytes(msg_req) + if "bits" in params2: + v_get = mock.AsyncMock(return_value=[True]) + elif "registers" in params2 or "and_mask" in params2: + v_get = mock.AsyncMock(return_value=[1]) + else: + v_get = mock.AsyncMock(return_value=0) + assert pdu == await pdu.build_response(v_get, mock.AsyncMock(return_value=0)) + assert pdu.is_request == False + msg_resp = pdu.to_bytes() + assert msg_resp + + # Client, check response + pdu = pdu_class(False, 1) + assert not pdu.from_bytes(msg_resp) From ca25c5ba3ecd34e9b6fac71c8badf75eb7103ef1 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Tue, 1 Dec 2026 11:47:45 +0100 Subject: [PATCH 09/12] T2. --- pymodbus/pdu/diag_message.py | 20 ++++++++++---------- pymodbus/pdu/other_message.py | 5 ++--- test/pdu/test_pdu.py | 4 ++-- test/pdu/test_pdu_extras.py | 23 ++--------------------- 4 files changed, 16 insertions(+), 36 deletions(-) diff --git a/pymodbus/pdu/diag_message.py b/pymodbus/pdu/diag_message.py index 6e7d6db6a5..a6d6647044 100644 --- a/pymodbus/pdu/diag_message.py +++ b/pymodbus/pdu/diag_message.py @@ -58,7 +58,7 @@ def to_bytes(self) -> bytes: def from_bytes(self, data: bytes) -> str | None: """Decode payload.""" (self.sub_function_code,) = struct.unpack(">H", data[2:4]) - self.message = data[4:] + self.message = data[4:6] def sub_build_response(self) -> None: """get/set info in _MCB.""" @@ -131,7 +131,7 @@ class PDUreturnBusMessageCount(PDUdiagnostic): def sub_build_response(self) -> None: """Get/set info in _MCB.""" - self.message = _MCB.Counter.BusMessage + self.message = int(_MCB.Counter.BusMessage).to_bytes(2, "big") class PDUreturnBusCommunicationErrorCount(PDUdiagnostic): @@ -141,7 +141,7 @@ class PDUreturnBusCommunicationErrorCount(PDUdiagnostic): def sub_build_response(self) -> None: """Get/set info in _MCB.""" - self.message = _MCB.Counter.BusCommunicationError + self.message = int(_MCB.Counter.BusCommunicationError).to_bytes(2, "big") class PDUreturnBusExceptionErrorCount(PDUdiagnostic): @@ -151,7 +151,7 @@ class PDUreturnBusExceptionErrorCount(PDUdiagnostic): def sub_build_response(self) -> None: """Get/set info in _MCB.""" - self.message = _MCB.Counter.BusExceptionError + self.message = int(_MCB.Counter.BusExceptionError).to_bytes(2, "big") class PDUreturnDeviceMessageCount(PDUdiagnostic): @@ -161,7 +161,7 @@ class PDUreturnDeviceMessageCount(PDUdiagnostic): def sub_build_response(self) -> None: """Get/set info in _MCB.""" - self.message = _MCB.Counter.DeviceMessage + self.message = int(_MCB.Counter.DeviceMessage).to_bytes(2, "big") class PDUreturnDeviceNoResponseCount(PDUdiagnostic): @@ -171,7 +171,7 @@ class PDUreturnDeviceNoResponseCount(PDUdiagnostic): def sub_build_response(self) -> None: """Get/set info in _MCB.""" - self.message = _MCB.Counter.DeviceNoResponse + self.message = int(_MCB.Counter.DeviceNoResponse).to_bytes(2, "big") class PDUreturnDeviceNAKCount(PDUdiagnostic): @@ -181,7 +181,7 @@ class PDUreturnDeviceNAKCount(PDUdiagnostic): def sub_build_response(self) -> None: """Get/set info in _MCB.""" - self.message = _MCB.Counter.DeviceNAK + self.message = int(_MCB.Counter.DeviceNAK).to_bytes(2, "big") class PDUreturnDeviceBusyCount(PDUdiagnostic): @@ -191,7 +191,7 @@ class PDUreturnDeviceBusyCount(PDUdiagnostic): def sub_build_response(self) -> None: """Get/set info in _MCB.""" - self.message = _MCB.Counter.DEVICE_BUSY + self.message = int(_MCB.Counter.DEVICE_BUSY).to_bytes(2, "big") class PDUreturnDeviceBusCharacterOverrunCount(PDUdiagnostic): @@ -201,7 +201,7 @@ class PDUreturnDeviceBusCharacterOverrunCount(PDUdiagnostic): def sub_build_response(self) -> None: """Get/set info in _MCB.""" - self.message = _MCB.Counter.BusCharacterOverrun + self.message = int(_MCB.Counter.BusCharacterOverrun).to_bytes(2, "big") class PDUreturnIopOverrunCount(PDUdiagnostic): @@ -211,7 +211,7 @@ class PDUreturnIopOverrunCount(PDUdiagnostic): def sub_build_response(self) -> None: """Get/set info in _MCB.""" - self.message = _MCB.Counter.BusCharacterOverrun + self.message = int(_MCB.Counter.BusCharacterOverrun).to_bytes(2, "big") class PDUclearOverrunCount(PDUdiagnostic): diff --git a/pymodbus/pdu/other_message.py b/pymodbus/pdu/other_message.py index 5e9a498ee1..c9b82032b6 100644 --- a/pymodbus/pdu/other_message.py +++ b/pymodbus/pdu/other_message.py @@ -175,6 +175,7 @@ async def build_response(self, v_get: StoreGet, v_set: StoreSet) -> ModbusPdu: self.message_count = _MCB.Counter.BusMessage self.event_count = _MCB.Counter.Event self.events = list(_MCB.getEvents()) + self.is_request = False return self @@ -334,9 +335,7 @@ def from_bytes(self, data: bytes) -> str | None: if (byte_count := int(data[2])) + 3 != len(data): return f"Invalid byte count: {byte_count}" while count < byte_count + 3: - calc_length, ref_type = struct.unpack(">BB", data[count : count + 2]) - if ref_type != 6: - return f"Invalid Record reference type expected 6 got {ref_type}" + calc_length, _ = struct.unpack(">BB", data[count : count + 2]) record = FileRecord( record_data=data[count + 2 : count + 2 + calc_length - 1], ) diff --git a/test/pdu/test_pdu.py b/test/pdu/test_pdu.py index 31f9b862e6..5da810d264 100644 --- a/test/pdu/test_pdu.py +++ b/test/pdu/test_pdu.py @@ -481,7 +481,7 @@ def test_decoder(self, is_request, cases, paramPDU): async def test_roundtrip(self, paramPDU): """Ensure that __init__ runs correctly.""" - pdu_class, _api, _params, msg_req, params2, msg_resp = paramPDU + pdu_class, _api, _params, msg_req, params2, _msg = paramPDU # Build client, issuing req. pdu = pdu_class(True, 1) @@ -498,7 +498,7 @@ async def test_roundtrip(self, paramPDU): else: v_get = mock.AsyncMock(return_value=0) assert pdu == await pdu.build_response(v_get, mock.AsyncMock(return_value=0)) - assert pdu.is_request == False + assert not pdu.is_request msg_resp = pdu.to_bytes() assert msg_resp diff --git a/test/pdu/test_pdu_extras.py b/test/pdu/test_pdu_extras.py index 3f5dece501..60abe983aa 100644 --- a/test/pdu/test_pdu_extras.py +++ b/test/pdu/test_pdu_extras.py @@ -440,27 +440,8 @@ def test_file_2(self, server): def test_file_3(self): """Test file_msg.PDUreadFileRecord raises ModbusException on oversized byte_count.""" handle = file_msg.PDUreadFileRecord(False, 0) - assert handle.from_bytes( - bytes([0x00, 0x15, 0xFF, 0x06, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01]) - ) - assert handle.from_bytes( - bytes( - [ - 0x00, - 0x15, - 0xFF, - 0x06, - 0x00, - 0x01, - 0x00, - 0x00, - 0x00, - 0x01, - 0x00, - 0x00, - ] - ) - ) + assert handle.from_bytes(b"\x00\x15\xff\x06\x00\x01\x00\x01\x00\x01") + assert handle.from_bytes(b"\x00\x15\xff\x06\x00\x01\x00\x00\x00\x01\x00\x00") def test_file_4(self): """Test file_msg.PDUreadFifoQueue raises ModbusException on oversized count.""" From 84eeedbeaf18cef93ce32ef4146e2a0fdd8189a7 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Tue, 1 Dec 2026 13:41:35 +0100 Subject: [PATCH 10/12] T2. --- pymodbus/pdu/diag_message.py | 3 ++- test/framer/test_extras.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/pymodbus/pdu/diag_message.py b/pymodbus/pdu/diag_message.py index a6d6647044..8fb76e7c94 100644 --- a/pymodbus/pdu/diag_message.py +++ b/pymodbus/pdu/diag_message.py @@ -292,11 +292,12 @@ def __init__( def __str__(self) -> str: """Build representation of pdu.""" + info = "None" if self.information == {} else self.information return super().__str__() + ( ", " + f"read_code={self.read_code}, " + f"object_id={self.object_id}, " - + f"information={self.information}, " + + f"information={info}, " + f"number_of_objects={self.number_of_objects}, " + f"conformity={self.conformity}, " + f"next_object_id={self.next_object_id}, " diff --git a/test/framer/test_extras.py b/test/framer/test_extras.py index 952736e689..c037360b48 100755 --- a/test/framer/test_extras.py +++ b/test/framer/test_extras.py @@ -4,6 +4,7 @@ import pytest +from pymodbus import pymodbus_apply_logging_config from pymodbus.exceptions import ModbusIOException from pymodbus.framer import ( FramerAscii, @@ -176,3 +177,12 @@ def test_ascii_framer_skip_wrong_dev_id_then_decode(self): assert pdu is not None assert pdu.dev_id == 0xFF assert used_len == len(wrong) + len(right) + + def test_tcp_framer_wrong_log(self): + """Message causes a crash.""" + pymodbus_apply_logging_config("debug") + msg = b"\x00\x05\x00\x00\x00\x05\x01\x2b\x0e\x01\x00" + used_len, pdu = self._tcp.handleFrame(msg, 1, 5) + assert pdu is not None + assert used_len == len(msg) + assert pdu.transaction_id == 5 From bd7621c8b993098acc575c844e0b3f8b93c8d294 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Tue, 1 Dec 2026 16:02:11 +0100 Subject: [PATCH 11/12] T3. --- pymodbus/logging.py | 2 +- pymodbus/pdu/diag_message.py | 5 ++--- test/framer/test_extras.py | 34 +++++++++++++++++++++++++++++++--- 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/pymodbus/logging.py b/pymodbus/logging.py index 066eb92bf7..fbf7d46d3a 100644 --- a/pymodbus/logging.py +++ b/pymodbus/logging.py @@ -125,7 +125,7 @@ def transport_dump(cls, data_type, data, old_data): ) @classmethod - def build_msg(cls, txt, *args): + def build_msg(cls, txt: str, *args): """Build message.""" string_args = [] count_args = len(args) - 1 diff --git a/pymodbus/pdu/diag_message.py b/pymodbus/pdu/diag_message.py index 8fb76e7c94..a2442bc1a5 100644 --- a/pymodbus/pdu/diag_message.py +++ b/pymodbus/pdu/diag_message.py @@ -292,18 +292,17 @@ def __init__( def __str__(self) -> str: """Build representation of pdu.""" - info = "None" if self.information == {} else self.information return super().__str__() + ( ", " + f"read_code={self.read_code}, " + f"object_id={self.object_id}, " - + f"information={info}, " + + f"information={self.information}, " + f"number_of_objects={self.number_of_objects}, " + f"conformity={self.conformity}, " + f"next_object_id={self.next_object_id}, " + f"more_follows={self.more_follows}, " + f"space_left={self.space_left}, " - ) + ).replace("{", "{{").replace("}", "}}") def calculatePduSize(self, data: bytes) -> int: """Calculate the size of a PDU.""" diff --git a/test/framer/test_extras.py b/test/framer/test_extras.py index c037360b48..8e84a11963 100755 --- a/test/framer/test_extras.py +++ b/test/framer/test_extras.py @@ -178,11 +178,39 @@ def test_ascii_framer_skip_wrong_dev_id_then_decode(self): assert pdu.dev_id == 0xFF assert used_len == len(wrong) + len(right) - def test_tcp_framer_wrong_log(self): + @pytest.mark.parametrize( + ("is_request", "msg"), + [ + (True, b"\x00\x05\x00\x00\x00\x05\x01\x2b\x0e\x01\x00"), + ( + False, + ( + b"\x00\x05\x00\x00\x00\x22\x01\x2b\x0e\x01\x83\x00\x00\x03" + + b"\x00\x08\x50\x79\x6d\x6f\x64\x62\x75\x73\x01\x02\x50\x4d" + + b"\x02\x0a\x34\x2e\x30\x2e\x30\x64\x65\x76\x31\x37" + ), + ), + ( + False, + ( + b"\x00\x05\x00\x00\x00\x72\x01\x08\x00\x15\x00\x00\x00\x00\x00" + + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + + b"\x00\x00\x00\x00\x00\x00\x00" + ), + ), + ], + ) + def test_tcp_framer_wrong_log(self, is_request, msg): """Message causes a crash.""" pymodbus_apply_logging_config("debug") - msg = b"\x00\x05\x00\x00\x00\x05\x01\x2b\x0e\x01\x00" - used_len, pdu = self._tcp.handleFrame(msg, 1, 5) + handle = FramerSocket(DecodePDU(is_request)) + used_len, pdu = handle.handleFrame(msg, 1, 5) assert pdu is not None assert used_len == len(msg) assert pdu.transaction_id == 5 From 010455d87d93b4d43a41ba50813af41438112841 Mon Sep 17 00:00:00 2001 From: jan iversen Date: Tue, 1 Dec 2026 20:32:36 +0100 Subject: [PATCH 12/12] T3. --- pymodbus/pdu/diag_message.py | 21 ++++++++++++++++++--- test/framer/test_extras.py | 26 +------------------------- test/pdu/conftest.py | 18 ++++++++++-------- test/pdu/test_pdu.py | 2 +- 4 files changed, 30 insertions(+), 37 deletions(-) diff --git a/pymodbus/pdu/diag_message.py b/pymodbus/pdu/diag_message.py index a2442bc1a5..3e11493330 100644 --- a/pymodbus/pdu/diag_message.py +++ b/pymodbus/pdu/diag_message.py @@ -231,7 +231,10 @@ class PDUgetClearModbusPlus(PDUdiagnostic): def calculatePduSize(self, data: bytes) -> int: """Calculate the size of a PDU.""" - return 0 if (lx := len(data)) < (leff := 6 + (111 if lx > 7 else 0)) else leff + lx = len(data) + if self.is_request: + return 0 if lx < 6 else 6 + return 0 if lx < 8 else 8 + data[7] def sub_build_response(self) -> None: """Get/set info in _MCB.""" @@ -241,14 +244,26 @@ def sub_build_response(self) -> None: packet = b"" for piece in _MCB.Plus.encode(): packet += struct.pack(">H", piece) - self.message = packet def to_bytes(self): """Encode a diagnostic response.""" + code = b"\x00\x04" if self.message == CLEAR_STATISTICS else b"\x00\x03" + ctl = struct.pack(">H", self.sub_function_code) + code + if self.is_request or self.message == CLEAR_STATISTICS: + return self.preamble() + ctl return ( - self.preamble() + struct.pack(">H", self.sub_function_code) + self.message + self.preamble() + ctl + struct.pack(">H", len(self.message)) + self.message ) + def from_bytes(self, data: bytes) -> str | None: + """Decode payload.""" + (self.sub_function_code,) = struct.unpack(">H", data[2:4]) + if data[4:6] == CLEAR_STATISTICS: + self.message = CLEAR_STATISTICS + else: + self.message = data[8:] + + class _OutOfSpaceException(Exception): """Internal out of space exception.""" diff --git a/test/framer/test_extras.py b/test/framer/test_extras.py index 8e84a11963..528ca134ab 100755 --- a/test/framer/test_extras.py +++ b/test/framer/test_extras.py @@ -180,31 +180,7 @@ def test_ascii_framer_skip_wrong_dev_id_then_decode(self): @pytest.mark.parametrize( ("is_request", "msg"), - [ - (True, b"\x00\x05\x00\x00\x00\x05\x01\x2b\x0e\x01\x00"), - ( - False, - ( - b"\x00\x05\x00\x00\x00\x22\x01\x2b\x0e\x01\x83\x00\x00\x03" - + b"\x00\x08\x50\x79\x6d\x6f\x64\x62\x75\x73\x01\x02\x50\x4d" - + b"\x02\x0a\x34\x2e\x30\x2e\x30\x64\x65\x76\x31\x37" - ), - ), - ( - False, - ( - b"\x00\x05\x00\x00\x00\x72\x01\x08\x00\x15\x00\x00\x00\x00\x00" - + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - + b"\x00\x00\x00\x00\x00\x00\x00" - ), - ), - ], + [], ) def test_tcp_framer_wrong_log(self, is_request, msg): """Message causes a crash.""" diff --git a/test/pdu/conftest.py b/test/pdu/conftest.py index 542162492f..3268ed085f 100644 --- a/test/pdu/conftest.py +++ b/test/pdu/conftest.py @@ -5,6 +5,8 @@ import pymodbus.pdu.data_message as pdu_data import pymodbus.pdu.diag_message as pdu_diag import pymodbus.pdu.other_message as pdu_other +from pymodbus.constants import CLEAR_STATISTICS, GET_STATISTICS + @pytest.fixture( @@ -528,20 +530,20 @@ pdu_diag.PDUgetClearModbusPlus, "diag_getclear_modbus_response", ( - {}, - b"\x01\x08\x00\x15\x00\x00", - {}, - b"\x01\x08\x00\x15\x00\x00", + {"message": CLEAR_STATISTICS}, + b"\x01\x08\x00\x15\x00\x04", + {"message": CLEAR_STATISTICS}, + b"\x01\x08\x00\x15\x00\x04", ), ), ( # 53 pdu_diag.PDUgetClearModbusPlus, "diag_getclear_modbus_response", ( - {"message": b"\x10\x10"}, - b"\x01\x08\x00\x15\x10\x10", - {"message": b"\x10\x10"}, - b"\x01\x08\x00\x15\x10\x10", + {"message": GET_STATISTICS}, + b"\x01\x08\x00\x15\x00\x03", + {"message": bytes([0] * 108)}, + b"\x01\x08\x00\x15\x00\x03\x00\x6c" + bytes([0] * 108), ), ), ], diff --git a/test/pdu/test_pdu.py b/test/pdu/test_pdu.py index 5da810d264..b3f1e528e9 100644 --- a/test/pdu/test_pdu.py +++ b/test/pdu/test_pdu.py @@ -384,7 +384,7 @@ def test_to_bytes(self, is_request, paramPDU): pdu, _api, params, msg, params2, _msg = paramPDU else: pdu, _api, params2, _msg, params, msg = paramPDU - params_comb = params | params2 + params_comb = params2 | params x = pdu(is_request, 1, **params) assert msg == x.to_bytes() x = pdu(is_request, 1, **params_comb)