Skip to content

Commit

Permalink
remove kwargs client.
Browse files Browse the repository at this point in the history
  • Loading branch information
janiversen committed Jul 21, 2024
1 parent fbaf05d commit 5b3d564
Show file tree
Hide file tree
Showing 8 changed files with 74 additions and 59 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ prof/
/pymodbus.egg-info/
venv
downloaded_files/
pymodbus.log
69 changes: 35 additions & 34 deletions pymodbus/client/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ class ModbusBaseClient(ModbusClientMixin[Awaitable[ModbusResponse]]):
:param reconnect_delay_max: Maximum delay in seconds.milliseconds before reconnecting.
:param on_connect_callback: Will be called when connected/disconnected (bool parameter)
:param no_resend_on_retry: Do not resend request when retrying due to missing response.
:param comm_type: Type of communication (set by interface class)
:param kwargs: Experimental parameters.
.. tip::
Expand All @@ -60,30 +59,30 @@ def __init__( # pylint: disable=too-many-arguments
reconnect_delay_max: float = 300,
on_connect_callback: Callable[[bool], None] | None = None,
no_resend_on_retry: bool = False,
comm_type: CommType | None = None,
source_address: tuple[str, int] | None = None,

comm_params: CommParams | None = None,
**kwargs: Any,
) -> None:
"""Initialize a client instance."""
ModbusClientMixin.__init__(self) # type: ignore[arg-type]
if comm_params:
self.comm_params = comm_params
self.comm_params.comm_name="comm"
self.comm_params.source_address=source_address
self.comm_params.reconnect_delay=reconnect_delay
self.comm_params.reconnect_delay_max=reconnect_delay_max
self.comm_params.timeout_connect=timeout
self.comm_params.host=kwargs.get("host", None)
self.comm_params.port=kwargs.get("port", 0)
self.comm_params.baudrate=kwargs.get("baudrate", None)
self.comm_params.bytesize=kwargs.get("bytesize", None)
self.comm_params.parity=kwargs.get("parity", None)
self.comm_params.stopbits=kwargs.get("stopbits", None)
self.comm_params.handle_local_echo=kwargs.get("handle_local_echo", False)
self.ctx = ModbusClientProtocol(
framer,
CommParams(
comm_type=comm_type,
comm_name="comm",
source_address=source_address,
reconnect_delay=reconnect_delay,
reconnect_delay_max=reconnect_delay_max,
timeout_connect=timeout,
host=kwargs.get("host", None),
port=kwargs.get("port", 0),
sslctx=kwargs.get("sslctx", None),
baudrate=kwargs.get("baudrate", None),
bytesize=kwargs.get("bytesize", None),
parity=kwargs.get("parity", None),
stopbits=kwargs.get("stopbits", None),
handle_local_echo=kwargs.get("handle_local_echo", False),
),
self.comm_params,
on_connect_callback,
)
self.no_resend_on_retry = no_resend_on_retry
Expand Down Expand Up @@ -276,26 +275,28 @@ def __init__( # pylint: disable=too-many-arguments
no_resend_on_retry: bool = False,
comm_type: CommType | None = None,
source_address: tuple[str, int] | None = None,
comm_params: CommParams | None = None,
**kwargs: Any,
) -> None:
"""Initialize a client instance."""
ModbusClientMixin.__init__(self) # type: ignore[arg-type]
self.comm_params = CommParams(
comm_type=comm_type,
comm_name="comm",
source_address=source_address,
reconnect_delay=reconnect_delay,
reconnect_delay_max=reconnect_delay_max,
timeout_connect=timeout,
host=kwargs.get("host", None),
port=kwargs.get("port", 0),
sslctx=kwargs.get("sslctx", None),
baudrate=kwargs.get("baudrate", None),
bytesize=kwargs.get("bytesize", None),
parity=kwargs.get("parity", None),
stopbits=kwargs.get("stopbits", None),
handle_local_echo=kwargs.get("handle_local_echo", False),
)
if comm_params:
self.comm_params = comm_params
if comm_type:
self.comm_params.comm_type=comm_type
self.comm_params.comm_name="comm"
self.comm_params.source_address=source_address
self.comm_params.reconnect_delay=reconnect_delay
self.comm_params.reconnect_delay_max=reconnect_delay_max
self.comm_params.timeout_connect=timeout
self.comm_params.host=kwargs.get("host", None)
self.comm_params.port=kwargs.get("port", 0)
self.comm_params.sslctx=kwargs.get("sslctx", None)
self.comm_params.baudrate=kwargs.get("baudrate", None)
self.comm_params.bytesize=kwargs.get("bytesize", None)
self.comm_params.parity=kwargs.get("parity", None)
self.comm_params.stopbits=kwargs.get("stopbits", None)
self.comm_params.handle_local_echo=kwargs.get("handle_local_echo", False)
self.params = self._params()
self.params.retries = int(retries)
self.params.retry_on_empty = bool(retry_on_empty)
Expand Down
8 changes: 3 additions & 5 deletions pymodbus/client/serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from pymodbus.exceptions import ConnectionException
from pymodbus.framer import FramerType
from pymodbus.logging import Log
from pymodbus.transport import CommType
from pymodbus.transport import CommParams, CommType
from pymodbus.utilities import ModbusTransactionState


Expand Down Expand Up @@ -81,10 +81,10 @@ def __init__(
"Serial client requires pyserial "
'Please install with "pip install pyserial" and try again.'
)
self.comm_params = CommParams(comm_type=CommType.SERIAL)
ModbusBaseClient.__init__(
self,
framer,
comm_type=CommType.SERIAL,
host=port,
baudrate=baudrate,
bytesize=bytesize,
Expand Down Expand Up @@ -159,9 +159,9 @@ def __init__(
**kwargs: Any,
) -> None:
"""Initialize Modbus Serial Client."""
self.comm_params = CommParams(comm_type=CommType.SERIAL)
super().__init__(
framer,
comm_type=CommType.SERIAL,
host=port,
baudrate=baudrate,
bytesize=bytesize,
Expand All @@ -171,9 +171,7 @@ def __init__(
)
self.socket: serial.Serial | None = None
self.strict = bool(strict)

self.last_frame_end = None

self._t0 = float(1 + bytesize + stopbits) / baudrate

# Check every 4 bytes / 2 registers if the reading is ready
Expand Down
10 changes: 5 additions & 5 deletions pymodbus/client/tcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from pymodbus.exceptions import ConnectionException
from pymodbus.framer import FramerType
from pymodbus.logging import Log
from pymodbus.transport import CommType
from pymodbus.transport import CommParams, CommType


class AsyncModbusTcpClient(ModbusBaseClient):
Expand Down Expand Up @@ -63,8 +63,8 @@ def __init__(
**kwargs: Any,
) -> None:
"""Initialize Asyncio Modbus TCP Client."""
if "comm_type" not in kwargs:
kwargs["comm_type"] = CommType.TCP
if not hasattr(self,"comm_params"):
self.comm_params = CommParams(comm_type=CommType.TCP)
if source_address:
kwargs["source_address"] = source_address
ModbusBaseClient.__init__(
Expand Down Expand Up @@ -132,8 +132,8 @@ def __init__(
**kwargs: Any,
) -> None:
"""Initialize Modbus TCP Client."""
if "comm_type" not in kwargs:
kwargs["comm_type"] = CommType.TCP
if not hasattr(self,"comm_params"):
self.comm_params = CommParams(comm_type=CommType.TCP)
super().__init__(
framer,
host=host,
Expand Down
8 changes: 6 additions & 2 deletions pymodbus/client/tls.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@ def __init__(
**kwargs: Any,
):
"""Initialize Asyncio Modbus TLS Client."""
self.comm_params = CommParams(comm_type=CommType.TLS)
AsyncModbusTcpClient.__init__(
self,
host,
port=port,
framer=framer,
comm_type=CommType.TLS,
sslctx=sslctx,
**kwargs,
)
Expand Down Expand Up @@ -149,8 +149,12 @@ def __init__(
**kwargs: Any,
):
"""Initialize Modbus TLS Client."""
self.comm_params = CommParams(
comm_type=CommType.TLS,
sslctx=sslctx,
)
super().__init__(
host, comm_type=CommType.TLS, port=port, framer=framer, **kwargs
host, port=port, framer=framer, **kwargs
)
self.sslctx = sslctx
self.server_hostname = server_hostname
Expand Down
6 changes: 3 additions & 3 deletions pymodbus/client/udp.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from pymodbus.exceptions import ConnectionException
from pymodbus.framer import FramerType
from pymodbus.logging import Log
from pymodbus.transport import CommType
from pymodbus.transport import CommParams, CommType


DGRAM_TYPE = socket.SOCK_DGRAM
Expand Down Expand Up @@ -62,10 +62,10 @@ def __init__(
**kwargs: Any,
) -> None:
"""Initialize Asyncio Modbus UDP Client."""
self.comm_params = CommParams(comm_type=CommType.UDP)
ModbusBaseClient.__init__(
self,
framer,
comm_type=CommType.UDP,
host=host,
port=port,
**kwargs,
Expand Down Expand Up @@ -130,11 +130,11 @@ def __init__(
**kwargs: Any,
) -> None:
"""Initialize Modbus UDP Client."""
self.comm_params = CommParams(comm_type=CommType.UDP)
super().__init__(
framer,
port=port,
host=host,
comm_type=CommType.UDP,
**kwargs,
)
self.params.source_address = source_address
Expand Down
3 changes: 2 additions & 1 deletion test/framers/test_old_framers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
ModbusTlsFramer,
)
from pymodbus.pdu.bit_read_message import ReadCoilsRequest
from pymodbus.transport import CommType
from pymodbus.transport import CommParams, CommType
from pymodbus.utilities import ModbusTransactionState


Expand Down Expand Up @@ -330,6 +330,7 @@ async def test_send_packet(self, rtu_framer):
host="localhost",
port=BASE_PORT + 1,
CommType=CommType.TCP,
comm_params=CommParams(),
)
client.state = ModbusTransactionState.TRANSACTION_COMPLETE
client.silent_interval = 1
Expand Down
28 changes: 19 additions & 9 deletions test/sub_client/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from pymodbus.datastore.store import ModbusSequentialDataBlock
from pymodbus.exceptions import ConnectionException, ModbusException, ModbusIOException
from pymodbus.pdu import ModbusRequest
from pymodbus.transport import CommType
from pymodbus.transport import CommParams, CommType


BASE_PORT = 6500
Expand Down Expand Up @@ -281,6 +281,7 @@ async def test_client_modbusbaseclient():
host="localhost",
port=BASE_PORT + 1,
CommType=CommType.TCP,
comm_params=CommParams(),
)
client.register(pdu_bit_read.ReadCoilsResponse)
assert str(client)
Expand Down Expand Up @@ -316,6 +317,7 @@ async def test_client_base_async():
host="localhost",
port=BASE_PORT + 2,
CommType=CommType.TCP,
comm_params=CommParams(),
) as client:
str(client)
p_connect.return_value = asyncio.Future()
Expand All @@ -327,7 +329,8 @@ async def test_client_base_async():
@pytest.mark.skip()
async def test_client_protocol_receiver():
"""Test the client protocol data received."""
base = ModbusBaseClient(FramerType.SOCKET)
base = ModbusBaseClient(FramerType.SOCKET, comm_params=CommParams(),
)
transport = mock.MagicMock()
base.ctx.connection_made(transport)
assert base.transport == transport
Expand All @@ -349,7 +352,8 @@ async def test_client_protocol_receiver():
@pytest.mark.skip()
async def test_client_protocol_response():
"""Test the udp client protocol builds responses."""
base = ModbusBaseClient(FramerType.SOCKET)
base = ModbusBaseClient(FramerType.SOCKET, comm_params=CommParams(),
)
response = base.build_response(0x00) # pylint: disable=protected-access
excp = response.exception()
assert isinstance(excp, ConnectionException)
Expand All @@ -363,7 +367,8 @@ async def test_client_protocol_response():
async def test_client_protocol_handler():
"""Test the client protocol handles responses."""
base = ModbusBaseClient(
FramerType.ASCII, host="localhost", port=+3, CommType=CommType.TCP
FramerType.ASCII, host="localhost", port=+3, CommType=CommType.TCP, comm_params=CommParams(),

)
transport = mock.MagicMock()
base.ctx.connection_made(transport=transport)
Expand Down Expand Up @@ -411,7 +416,8 @@ def close(self):

async def test_client_protocol_execute():
"""Test the client protocol execute method."""
base = ModbusBaseClient(FramerType.SOCKET, host="127.0.0.1")
base = ModbusBaseClient(FramerType.SOCKET, host="127.0.0.1", comm_params=CommParams(),
)
request = pdu_bit_read.ReadCoilsRequest(1, 1)
transport = MockTransport(base, request)
base.ctx.connection_made(transport=transport)
Expand All @@ -422,7 +428,8 @@ async def test_client_protocol_execute():

async def test_client_execute_broadcast():
"""Test the client protocol execute method."""
base = ModbusBaseClient(FramerType.SOCKET, host="127.0.0.1")
base = ModbusBaseClient(FramerType.SOCKET, host="127.0.0.1", comm_params=CommParams(),
)
base.broadcast_enable = True
request = pdu_bit_read.ReadCoilsRequest(1, 1)
transport = MockTransport(base, request)
Expand All @@ -432,7 +439,8 @@ async def test_client_execute_broadcast():

async def test_client_protocol_retry():
"""Test the client protocol execute method with retries."""
base = ModbusBaseClient(FramerType.SOCKET, host="127.0.0.1", timeout=0.1)
base = ModbusBaseClient(FramerType.SOCKET, host="127.0.0.1", timeout=0.1, comm_params=CommParams(),
)
request = pdu_bit_read.ReadCoilsRequest(1, 1)
transport = MockTransport(base, request, retries=2)
base.ctx.connection_made(transport=transport)
Expand All @@ -445,7 +453,8 @@ async def test_client_protocol_retry():

async def test_client_protocol_timeout():
"""Test the client protocol execute method with timeout."""
base = ModbusBaseClient(FramerType.SOCKET, host="127.0.0.1", timeout=0.1, retries=2)
base = ModbusBaseClient(FramerType.SOCKET, host="127.0.0.1", timeout=0.1, retries=2, comm_params=CommParams(),
)
# Avoid creating do_reconnect() task
base.ctx.connection_lost = mock.MagicMock()
request = pdu_bit_read.ReadCoilsRequest(1, 1)
Expand Down Expand Up @@ -645,7 +654,8 @@ def test_client_mixin_convert_fail():

async def test_client_build_response():
"""Test fail of build_response."""
client = ModbusBaseClient(FramerType.RTU)
client = ModbusBaseClient(FramerType.RTU, comm_params=CommParams(),
)
with pytest.raises(ConnectionException):
await client.build_response(ModbusRequest(0, 0, 0, False))

Expand Down

0 comments on commit 5b3d564

Please sign in to comment.