Skip to content

Commit 1ee937a

Browse files
authored
remove init_<something>_client(). (#1008)
1 parent dba6531 commit 1ee937a

File tree

10 files changed

+153
-231
lines changed

10 files changed

+153
-231
lines changed

examples/client_async.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ async def setup_async_client():
4747
_logger.info("### Create client object")
4848

4949
if args.comm == "tcp":
50-
client = await AsyncModbusTCPClient(
51-
host="127.0.0.1", # define tcp address where to connect to.
50+
client = AsyncModbusTCPClient(
51+
"127.0.0.1", # define tcp address where to connect to.
5252
port=args.port, # on which port
5353
framer=ModbusSocketFramer, # how to interpret the messages
5454
timeout=1, # waiting time for request to complete
@@ -58,8 +58,8 @@ async def setup_async_client():
5858
strict=True, # use strict timing, t1.5 for Modbus RTU
5959
)
6060
elif args.comm == "udp":
61-
client = await AsyncModbusUDPClient(
62-
host="localhost", # define tcp address where to connect to.
61+
client = AsyncModbusUDPClient(
62+
"localhost", # define tcp address where to connect to.
6363
port=args.port, # on which port
6464
framer=args.framer, # how to interpret the messages
6565
timeout=1, # waiting time for request to complete
@@ -69,8 +69,8 @@ async def setup_async_client():
6969
strict=True, # use strict timing, t1.5 for Modbus RTU
7070
)
7171
elif args.comm == "serial":
72-
client = await AsyncModbusSerialClient(
73-
port=args.port, # serial port
72+
client = AsyncModbusSerialClient(
73+
args.port, # serial port
7474
framer=args.framer, # how to interpret the messages
7575
stopbits=1, # The number of stop bits to use
7676
bytesize=7, # The bytesize of the serial messages
@@ -81,7 +81,7 @@ async def setup_async_client():
8181
strict=True, # use strict timing, t1.5 for Modbus RTU
8282
)
8383
elif args.comm == "tls":
84-
client = await AsyncModbusTLSClient(
84+
client = AsyncModbusTLSClient(
8585
host="localhost", # define tcp address where to connect to.
8686
port=args.port, # on which port
8787
sslctx=None, # ssl control
@@ -93,8 +93,10 @@ async def setup_async_client():
9393
retries=3, # retries per transaction
9494
retry_on_empty=False, # Is an empty response a retry
9595
source_address=("localhost", 0), # bind socket to address
96+
server_hostname="localhost", # used for cert verification
9697
strict=True, # use strict timing, t1.5 for Modbus RTU
9798
)
99+
await client.start()
98100
return client
99101

100102

examples/client_sync.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
def setup_sync_client():
4545
"""Run client setup."""
4646
args = get_commandline()
47+
args.comm = "serial"
4748
_logger.info("### Create client object")
4849
if args.comm == "tcp":
4950
client = ModbusTcpClient(
@@ -73,7 +74,7 @@ def setup_sync_client():
7374
framer=args.framer, # how to interpret the messages
7475
stopbits=1, # The number of stop bits to use
7576
bytesize=7, # The bytesize of the serial messages
76-
parity="even", # Which kind of parity to use
77+
parity="E", # Which kind of parity to use
7778
baudrate=9600, # The baud rate to use for the serial device
7879
handle_local_echo=False, # Handle local echo of the USB-to-RS485 adaptor
7980
timeout=1, # waiting time for request to complete

examples/server_sync.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ def run_server():
183183
handler=None, # handler for each session
184184
stopbits=1, # The number of stop bits to use
185185
bytesize=7, # The bytesize of the serial messages
186-
parity="even", # Which kind of parity to use
186+
parity="E", # Which kind of parity to use
187187
baudrate=9600, # The baud rate to use for the serial device
188188
handle_local_echo=False, # Handle local echo of the USB-to-RS485 adaptor
189189
ignore_missing_slaves=True, # ignore request to a missing slave

pymodbus/client/asynchronous/async_io/__init__.py

Lines changed: 51 additions & 137 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
from pymodbus.transaction import FifoTransactionManager
1414
from pymodbus.utilities import hexlify_packets
1515
from pymodbus.transaction import (
16-
ModbusRtuFramer,
1716
ModbusSocketFramer,
1817
ModbusTlsFramer,
1918
)
@@ -232,20 +231,17 @@ class ReconnectingAsyncioModbusTcpClient:
232231
#: Maximum delay in milli seconds before reconnect is attempted.
233232
DELAY_MAX_MS = 1000 * 60 * 5
234233

235-
def __init__(self, protocol_class=None, framer=None, **kwargs):
236-
"""Initialize ReconnectingAsyncioModbusTcpClient.
237-
238-
:param protocol_class: Protocol used to talk to modbus device.
239-
"""
234+
def __init__(self, host, **kwargs):
235+
"""Initialize ReconnectingAsyncioModbusTcpClient."""
240236
# get current loop, if there are no loop a RuntimeError will be raised
241-
self.loop = asyncio.get_running_loop()
237+
self.loop = None
242238
#: Protocol used to talk to modbus device.
243-
self.protocol_class = protocol_class or ModbusClientProtocol
239+
self.protocol_class = kwargs.get("protocol_class", ModbusClientProtocol)
244240
#: Current protocol instance.
245241
self.protocol = None
246-
self.framer = framer if framer else ModbusSocketFramer
247-
self.host = None
248-
self.port = 0
242+
self.framer = kwargs.get("framer", ModbusSocketFramer)
243+
self.host = host
244+
self.port = kwargs.get("port", 502)
249245
self.connected = False
250246
#: Reconnect delay in milli seconds.
251247
self.delay_ms = self.DELAY_MIN_MS
@@ -255,20 +251,14 @@ def reset_delay(self):
255251
"""Reset wait before next reconnect to minimal period."""
256252
self.delay_ms = self.DELAY_MIN_MS
257253

258-
async def start(self, host, port=502):
259-
"""Initiate connection to start client
260-
261-
:param host:
262-
:param port:
263-
:return:
264-
"""
254+
async def start(self,):
255+
"""Initiate connection to start client."""
265256
# force reconnect if required:
266257
self.stop()
258+
self.loop = asyncio.get_running_loop()
267259

268-
txt = f"Connecting to {host}:{port}."
260+
txt = f"Connecting to {self.host}:{self.port}."
269261
_logger.debug(txt)
270-
self.host = host
271-
self.port = port
272262
return await self._connect()
273263

274264
def stop(self):
@@ -416,40 +406,30 @@ def protocol_lost_connection(self, protocol):
416406
class ReconnectingAsyncioModbusTlsClient(ReconnectingAsyncioModbusTcpClient):
417407
"""Client to connect to modbus device repeatedly over TLS."""
418408

419-
def __init__(self, protocol_class=None, framer=None, **kwargs):
420-
"""Initialize ReconnectingAsyncioModbusTcpClient
421-
422-
:param protocol_class: Protocol used to talk to modbus device.
423-
"""
409+
def __init__(self, host, **kwargs):
410+
"""Initialize ReconnectingAsyncioModbusTcpClient."""
424411
# get current loop, if there are no loop a RuntimeError will be raised
425-
self.loop = asyncio.get_running_loop()
426-
self.framer = framer if framer else ModbusTlsFramer
427-
self.server_hostname = None
428-
self.sslctx = None
429-
ReconnectingAsyncioModbusTcpClient.__init__(
430-
self, protocol_class, framer=self.framer, **kwargs
431-
)
432-
433-
async def start(self, host, port=802, sslctx=None, server_hostname=None):
434-
"""Initiate connection to start client
435-
436-
:param host:
437-
:param port:
438-
:param sslctx:
439-
:param server_hostname:
440-
:return:
441-
"""
442-
self.sslctx = sslctx
443-
if self.sslctx is None:
412+
self.loop = None
413+
self.framer = kwargs.get("framer", ModbusTlsFramer)
414+
self.server_hostname = kwargs.get("server_hostname", None)
415+
self.sslctx = kwargs.get("sslctx", None)
416+
if not self.sslctx:
444417
self.sslctx = ssl.create_default_context()
445418
# According to MODBUS/TCP Security Protocol Specification, it is
446419
# TLSv2 at least
447420
self.sslctx.options |= ssl.OP_NO_TLSv1_1
448421
self.sslctx.options |= ssl.OP_NO_TLSv1
449422
self.sslctx.options |= ssl.OP_NO_SSLv3
450423
self.sslctx.options |= ssl.OP_NO_SSLv2
451-
self.server_hostname = server_hostname
452-
return await ReconnectingAsyncioModbusTcpClient.start(self, host, port)
424+
self.port = kwargs.pop("port", 802)
425+
self.host = host
426+
ReconnectingAsyncioModbusTcpClient.__init__(self, host, port=self.port, **kwargs)
427+
428+
async def start(self):
429+
"""Initiate connection to start client."""
430+
# get current loop, if there are no loop a RuntimeError will be raised
431+
self.loop = asyncio.get_running_loop()
432+
return await ReconnectingAsyncioModbusTcpClient.start(self)
453433

454434
async def _connect(self):
455435
_logger.debug(TEXT_CONNECTING)
@@ -459,7 +439,7 @@ async def _connect(self):
459439
self.host,
460440
self.port,
461441
ssl=self.sslctx,
462-
server_hostname=self.host,
442+
server_hostname=self.server_hostname,
463443
)
464444
except Exception as exc: # pylint: disable=broad-except
465445
txt = f"Failed to connect: {exc}"
@@ -487,21 +467,17 @@ class ReconnectingAsyncioModbusUdpClient:
487467
#: Maximum delay in milli seconds before reconnect is attempted.
488468
DELAY_MAX_MS = 1000 * 60 * 5
489469

490-
def __init__(self, protocol_class=None, framer=None, **kwargs):
491-
"""Initialize ReconnectingAsyncioModbusUdpClient
492-
493-
:param protocol_class: Protocol used to talk to modbus device.
494-
"""
495-
# get current loop, if there are no loop a RuntimeError will be raised
496-
self.loop = asyncio.get_running_loop()
470+
def __init__(self, host, framer=None, **kwargs):
471+
"""Initialize ReconnectingAsyncioModbusUdpClient."""
497472
#: Protocol used to talk to modbus device.
498-
self.protocol_class = protocol_class or ModbusUdpClientProtocol
473+
self.protocol_class = kwargs.get("protocol_class", ModbusUdpClientProtocol)
474+
self.loop = None
499475
#: Current protocol instance.
500476
self.protocol = None
501-
self.framer = framer if framer else ModbusSocketFramer
477+
self.framer = framer
502478

503-
self.host = None
504-
self.port = 0
479+
self.host = host
480+
self.port = kwargs.get("port", 502)
505481

506482
self.connected = False
507483
self._proto_args = kwargs
@@ -511,25 +487,22 @@ def reset_delay(self):
511487
"""Reset wait before next reconnect to minimal period."""
512488
self.delay_ms = 100
513489

514-
async def start(self, host, port=502):
515-
"""Start reconnecting asynchronous udp client
516-
517-
:param host: Host IP to connect
518-
:param port: Host port to connect
519-
:return:
520-
"""
490+
async def start(self):
491+
"""Start reconnecting asynchronous udp client."""
521492
# force reconnect if required:
522493
self.stop()
494+
# get current loop, if there are no loop a RuntimeError will be raised
495+
self.loop = asyncio.get_running_loop()
523496

524-
txt = f"Connecting to {host}:{port}."
497+
txt = f"Connecting to {self.host}:{self.port}."
525498
_logger.debug(txt)
526499

527500
# getaddrinfo returns a list of tuples
528501
# - [(family, type, proto, canonname, sockaddr),]
529502
# We want sockaddr which is a (ip, port) tuple
530503
# udp needs ip addresses, not hostnames
531-
addrinfo = await self.loop.getaddrinfo(host, port, type=DGRAM_TYPE)
532-
self.host, self.port = addrinfo[0][-1]
504+
# addrinfo = await self.loop.getaddrinfo(self.host, self.port, type=DGRAM_TYPE)
505+
# self.host, self.port = addrinfo[0][-1]
533506
return await self._connect()
534507

535508
def stop(self):
@@ -704,16 +677,10 @@ def __init__(
704677
stopbits=1,
705678
**serial_kwargs,
706679
):
707-
"""Initialize Asyncio Modbus Serial Client
708-
709-
:param port: Port to connect
710-
:param protocol_class: Protocol used to talk to modbus device.
711-
:param framer: Framer to use
712-
"""
713-
# get current loop, if there are no loop a RuntimeError will be raised
714-
self.loop = asyncio.get_running_loop()
680+
"""Initialize Asyncio Modbus Serial Client."""
681+
self.loop = None
715682
#: Protocol used to talk to modbus device.
716-
self.protocol_class = protocol_class or ModbusRtuFramer
683+
self.protocol_class = protocol_class or ModbusClientProtocol
717684
#: Current protocol instance.
718685
self.protocol = None
719686
self.port = port
@@ -741,6 +708,12 @@ def _connected(self):
741708
"""Connect internal."""
742709
return self._connected_event.is_set()
743710

711+
async def start(self):
712+
"""Connect Async client."""
713+
# get current loop, if there are no loop a RuntimeError will be raised
714+
self.loop = asyncio.get_running_loop()
715+
await self.connect()
716+
744717
async def connect(self):
745718
"""Connect Async client."""
746719
_logger.debug(TEXT_CONNECTING)
@@ -787,62 +760,3 @@ def protocol_lost_connection(self, protocol):
787760
# asyncio.asynchronous(self._reconnect())
788761
else:
789762
_logger.error(TEST_FACTORY)
790-
791-
792-
async def init_tcp_client(proto_cls, host, port, **kwargs):
793-
"""Initialize tcp client with helper function.
794-
795-
:param proto_cls:
796-
:param host:
797-
:param port:
798-
:param kwargs:
799-
:return:
800-
"""
801-
client = ReconnectingAsyncioModbusTcpClient(
802-
protocol_class=proto_cls, **kwargs
803-
)
804-
await client.start(host, port)
805-
return client
806-
807-
808-
async def init_tls_client(
809-
proto_cls,
810-
host,
811-
port,
812-
sslctx=None,
813-
server_hostname=None,
814-
framer=None,
815-
**kwargs,
816-
):
817-
"""Initialize tcp client with Helper function.
818-
819-
:param proto_cls:
820-
:param host:
821-
:param port:
822-
:param sslctx:
823-
:param server_hostname:
824-
:param framer:
825-
:param kwargs:
826-
:return:
827-
"""
828-
client = ReconnectingAsyncioModbusTlsClient(
829-
protocol_class=proto_cls, framer=framer, **kwargs
830-
)
831-
await client.start(host, port, sslctx, server_hostname)
832-
return client
833-
834-
835-
async def init_udp_client(proto_cls, host, port, **kwargs):
836-
"""Initialize UDP client with helper function.
837-
838-
:param proto_cls:
839-
:param host:
840-
:param port:
841-
:param kwargs:
842-
:return:
843-
"""
844-
client = ReconnectingAsyncioModbusUdpClient(
845-
protocol_class=proto_cls, **kwargs
846-
)
847-
await client.start(host, port)
848-
return client

0 commit comments

Comments
 (0)