1313from pymodbus .transaction import FifoTransactionManager
1414from pymodbus .utilities import hexlify_packets
1515from 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):
416406class 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