Skip to content

Commit

Permalink
Remove self.params from async client (#1640)
Browse files Browse the repository at this point in the history
  • Loading branch information
janiversen authored Jul 5, 2023
1 parent 270cdb5 commit 04117df
Show file tree
Hide file tree
Showing 16 changed files with 359 additions and 348 deletions.
51 changes: 25 additions & 26 deletions pymodbus/client/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,22 +52,13 @@ class ModbusBaseClient(ModbusClientMixin, ModbusProtocol):
class _params:
"""Parameter class."""

host: str = None
port: str | int = None
timeout: float = None
retries: int = None
retry_on_empty: bool = None
close_comm_on_error: bool = None
strict: bool = None
broadcast_enable: bool = None
reconnect_delay: int = None

baudrate: int = None
bytesize: int = None
parity: str = None
stopbits: int = None
handle_local_echo: bool = None

source_address: tuple[str, int] = None

server_hostname: str = None
Expand All @@ -89,28 +80,32 @@ def __init__( # pylint: disable=too-many-arguments
"""Initialize a client instance."""
ModbusClientMixin.__init__(self)
self.use_sync = kwargs.get("use_sync", False)
setup_params = CommParams(
comm_type=kwargs.get("CommType"),
comm_name="comm",
source_address=kwargs.get("source_address", ("127.0.0.1", 0)),
reconnect_delay=reconnect_delay,
reconnect_delay_max=reconnect_delay_max,
timeout_connect=timeout,
host=kwargs.get("host", None),
port=kwargs.get("port", None),
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 not self.use_sync:
ModbusProtocol.__init__(
self,
CommParams(
comm_type=kwargs.get("CommType"),
comm_name="comm",
reconnect_delay=reconnect_delay,
reconnect_delay_max=reconnect_delay_max,
timeout_connect=timeout,
host=kwargs.get("host", None),
port=kwargs.get("port", None),
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),
),
setup_params,
False,
)
else:
self.comm_params = setup_params
self.framer = framer
self.params = self._params()
self.params.timeout = float(timeout)
self.params.retries = int(retries)
self.params.retry_on_empty = bool(retry_on_empty)
self.params.close_comm_on_error = bool(close_comm_on_error)
Expand Down Expand Up @@ -199,7 +194,9 @@ async def async_execute(self, request=None):
resp = b"Broadcast write sent - no response expected"
else:
try:
resp = await asyncio.wait_for(req, timeout=self.params.timeout)
resp = await asyncio.wait_for(
req, timeout=self.comm_params.timeout_connect
)
except asyncio.exceptions.TimeoutError:
self.close(reconnect=True)
raise
Expand Down Expand Up @@ -315,4 +312,6 @@ def __str__(self):
:returns: The string representation
"""
return f"{self.__class__.__name__} {self.params.host}:{self.params.port}"
return (
f"{self.__class__.__name__} {self.comm_params.host}:{self.comm_params.port}"
)
53 changes: 26 additions & 27 deletions pymodbus/client/serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ def __init__(
bytesize: int = 8,
parity: str = "N",
stopbits: int = 1,
handle_local_echo: bool = False,
**kwargs: Any,
) -> None:
"""Initialize Asyncio Modbus Serial Client."""
Expand All @@ -68,12 +67,6 @@ def __init__(
stopbits=stopbits,
**kwargs,
)
self.params.port = port
self.params.baudrate = baudrate
self.params.bytesize = bytesize
self.params.parity = parity
self.params.stopbits = stopbits
self.params.handle_local_echo = handle_local_echo

@property
def connected(self):
Expand Down Expand Up @@ -132,24 +125,27 @@ def __init__(
bytesize: int = 8,
parity: str = "N",
stopbits: int = 1,
handle_local_echo: bool = False,
**kwargs: Any,
) -> None:
"""Initialize Modbus Serial Client."""
self.transport = None
kwargs["use_sync"] = True
super().__init__(framer=framer, **kwargs)
self.params.port = port
self.params.baudrate = baudrate
self.params.bytesize = bytesize
self.params.parity = parity
self.params.stopbits = stopbits
self.params.handle_local_echo = handle_local_echo
ModbusBaseClient.__init__(
self,
framer=framer,
CommType=CommType.SERIAL,
host=port,
baudrate=baudrate,
bytesize=bytesize,
parity=parity,
stopbits=stopbits,
**kwargs,
)
self.socket = None

self.last_frame_end = None

self._t0 = float(1 + 8 + 2) / self.params.baudrate
self._t0 = float(1 + 8 + 2) / self.comm_params.baudrate

"""
The minimum delay is 0.01s and the maximum can be set to 0.05s.
Expand All @@ -161,7 +157,7 @@ def __init__(
else 0.05
)

if self.params.baudrate > 19200:
if self.comm_params.baudrate > 19200:
self.silent_interval = 1.75 / 1000 # ms
else:
self.inter_char_timeout = 1.5 * self._t0
Expand All @@ -179,12 +175,12 @@ def connect(self): # pylint: disable=invalid-overridden-method
return True
try:
self.socket = serial.serial_for_url(
self.params.port,
timeout=self.params.timeout,
bytesize=self.params.bytesize,
stopbits=self.params.stopbits,
baudrate=self.params.baudrate,
parity=self.params.parity,
self.comm_params.host,
timeout=self.comm_params.timeout_connect,
bytesize=self.comm_params.bytesize,
stopbits=self.comm_params.stopbits,
baudrate=self.comm_params.baudrate,
parity=self.comm_params.parity,
)
if isinstance(self.framer, ModbusRtuFramer):
if self.params.strict:
Expand Down Expand Up @@ -244,10 +240,13 @@ def _wait_for_data(self):
"""Wait for data."""
size = 0
more_data = False
if self.params.timeout is not None and self.params.timeout:
if (
self.comm_params.timeout_connect is not None
and self.comm_params.timeout_connect
):
condition = partial(
lambda start, timeout: (time.time() - start) <= timeout,
timeout=self.params.timeout,
timeout=self.comm_params.timeout_connect,
)
else:
condition = partial(lambda dummy1, dummy2: True, dummy2=None)
Expand Down Expand Up @@ -286,11 +285,11 @@ def is_socket_open(self):

def __str__(self):
"""Build a string representation of the connection."""
return f"ModbusSerialClient({self.framer} baud[{self.params.baudrate}])"
return f"ModbusSerialClient({self.framer} baud[{self.comm_params.baudrate}])"

def __repr__(self):
"""Return string representation."""
return (
f"<{self.__class__.__name__} at {hex(id(self))} socket={self.socket}, "
f"framer={self.framer}, timeout={self.params.timeout}>"
f"framer={self.framer}, timeout={self.comm_params.timeout_connect}>"
)
22 changes: 10 additions & 12 deletions pymodbus/client/tcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,6 @@ def __init__(
port=port,
**kwargs,
)
self.params.host = host
self.params.port = port
self.params.source_address = source_address

async def connect(self) -> bool:
Expand Down Expand Up @@ -111,11 +109,11 @@ def __init__(
**kwargs: Any,
) -> None:
"""Initialize Modbus TCP Client."""
if "CommType" not in kwargs:
kwargs["CommType"] = CommType.TCP
kwargs["use_sync"] = True
self.transport = None
super().__init__(framer=framer, host=host, port=port, **kwargs)
self.params.host = host
self.params.port = port
self.params.source_address = source_address
self.socket = None

Expand All @@ -130,8 +128,8 @@ def connect(self): # pylint: disable=invalid-overridden-method
return True
try:
self.socket = socket.create_connection(
(self.params.host, self.params.port),
timeout=self.params.timeout,
(self.comm_params.host, self.comm_params.port),
timeout=self.comm_params.timeout_connect,
source_address=self.params.source_address,
)
Log.debug(
Expand All @@ -141,8 +139,8 @@ def connect(self): # pylint: disable=invalid-overridden-method
except OSError as msg:
Log.error(
"Connection to ({}, {}) failed: {}",
self.params.host,
self.params.port,
self.comm_params.host,
self.comm_params.port,
msg,
)
self.close()
Expand All @@ -157,7 +155,7 @@ def close(self): # pylint: disable=arguments-differ
def _check_read_buffer(self):
"""Check read buffer."""
time_ = time.time()
end = time_ + self.params.timeout
end = time_ + self.comm_params.timeout_connect
data = None
ready = select.select([self.socket], [], [], end - time_)
if ready[0]:
Expand Down Expand Up @@ -193,7 +191,7 @@ def recv(self, size):
# less than the expected size.
self.socket.setblocking(0)

timeout = self.params.timeout
timeout = self.comm_params.timeout_connect

# If size isn't specified read up to 4096 bytes at a time.
if size is None:
Expand Down Expand Up @@ -270,11 +268,11 @@ def __str__(self):
:returns: The string representation
"""
return f"ModbusTcpClient({self.params.host}:{self.params.port})"
return f"ModbusTcpClient({self.comm_params.host}:{self.comm_params.port})"

def __repr__(self):
"""Return string representation."""
return (
f"<{self.__class__.__name__} at {hex(id(self))} socket={self.socket}, "
f"ipaddr={self.params.host}, port={self.params.port}, timeout={self.params.timeout}>"
f"ipaddr={self.comm_params.host}, port={self.comm_params.port}, timeout={self.comm_params.timeout_connect}>"
)
20 changes: 11 additions & 9 deletions pymodbus/client/tls.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,9 @@ def __init__(
):
"""Initialize Modbus TLS Client."""
self.transport = None
super().__init__(host, port=port, framer=framer, **kwargs)
super().__init__(
host, CommType=CommType.TLS, port=port, framer=framer, **kwargs
)
self.sslctx = CommParams.generate_ssl(
False, certfile, keyfile, password, sslctx=sslctx
)
Expand All @@ -147,28 +149,28 @@ def connect(self):
if self.params.source_address:
sock.bind(self.params.source_address)
self.socket = self.sslctx.wrap_socket(
sock, server_side=False, server_hostname=self.params.host
sock, server_side=False, server_hostname=self.comm_params.host
)
self.socket.settimeout(self.params.timeout)
self.socket.connect((self.params.host, self.params.port))
self.socket.settimeout(self.comm_params.timeout_connect)
self.socket.connect((self.comm_params.host, self.comm_params.port))
except OSError as msg:
Log.error(
"Connection to ({}, {}) failed: {}",
self.params.host,
self.params.port,
self.comm_params.host,
self.comm_params.port,
msg,
)
self.close()
return self.socket is not None

def __str__(self):
"""Build a string representation of the connection."""
return f"ModbusTlsClient({self.params.host}:{self.params.port})"
return f"ModbusTlsClient({self.comm_params.host}:{self.comm_params.port})"

def __repr__(self):
"""Return string representation."""
return (
f"<{self.__class__.__name__} at {hex(id(self))} socket={self.socket}, "
f"ipaddr={self.params.host}, port={self.params.port}, sslctx={self.sslctx}, "
f"timeout={self.params.timeout}>"
f"ipaddr={self.comm_params.host}, port={self.comm_params.port}, sslctx={self.sslctx}, "
f"timeout={self.comm_params.timeout_connect}>"
)
19 changes: 10 additions & 9 deletions pymodbus/client/udp.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ def __init__(
ModbusBaseClient.__init__(
self, framer=framer, CommType=CommType.UDP, host=host, port=port, **kwargs
)
self.params.port = port
self.params.source_address = source_address

@property
Expand Down Expand Up @@ -117,9 +116,9 @@ def __init__(
"""Initialize Modbus UDP Client."""
kwargs["use_sync"] = True
self.transport = None
super().__init__(framer=framer, **kwargs)
self.params.host = host
self.params.port = port
super().__init__(
framer=framer, port=port, host=host, CommType=CommType.UDP, **kwargs
)
self.params.source_address = source_address

self.socket = None
Expand All @@ -137,9 +136,9 @@ def connect(self): # pylint: disable=invalid-overridden-method
if self.socket:
return True
try:
family = ModbusUdpClient._get_address_family(self.params.host)
family = ModbusUdpClient._get_address_family(self.comm_params.host)
self.socket = socket.socket(family, socket.SOCK_DGRAM)
self.socket.settimeout(self.params.timeout)
self.socket.settimeout(self.comm_params.timeout_connect)
except OSError as exc:
Log.error("Unable to create udp socket {}", exc)
self.close()
Expand All @@ -161,7 +160,9 @@ def send(self, request):
if not self.socket:
raise ConnectionException(str(self))
if request:
return self.socket.sendto(request, (self.params.host, self.params.port))
return self.socket.sendto(
request, (self.comm_params.host, self.comm_params.port)
)
return 0

def recv(self, size):
Expand All @@ -183,11 +184,11 @@ def is_socket_open(self):

def __str__(self):
"""Build a string representation of the connection."""
return f"ModbusUdpClient({self.params.host}:{self.params.port})"
return f"ModbusUdpClient({self.comm_params.host}:{self.comm_params.port})"

def __repr__(self):
"""Return string representation."""
return (
f"<{self.__class__.__name__} at {hex(id(self))} socket={self.socket}, "
f"ipaddr={self.params.host}, port={self.params.port}, timeout={self.params.timeout}>"
f"ipaddr={self.comm_params.host}, port={self.comm_params.port}, timeout={self.comm_params.timeout_connect}>"
)
Loading

0 comments on commit 04117df

Please sign in to comment.