Skip to content

Commit db1822d

Browse files
committed
Add connect/listen to transport with tests.
1 parent d347bc8 commit db1822d

File tree

10 files changed

+906
-187
lines changed

10 files changed

+906
-187
lines changed

pymodbus/client/base.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,16 @@ def __init__( # pylint: disable=too-many-arguments
9595
) -> None:
9696
"""Initialize a client instance."""
9797
BaseTransport.__init__(
98-
self, "comm", framer, reconnect_delay, reconnect_delay_max, timeout, timeout
98+
self,
99+
"comm",
100+
(reconnect_delay, reconnect_delay_max),
101+
timeout,
102+
framer,
103+
lambda: None,
104+
self.cb_base_connection_lost,
105+
self.cb_base_handle_data,
99106
)
107+
self.framer = framer
100108
self.params = self._params()
101109
self.params.framer = framer
102110
self.params.timeout = float(timeout)
@@ -198,24 +206,16 @@ async def async_execute(self, request=None):
198206
raise
199207
return resp
200208

201-
def data_received(self, data):
202-
"""Call when some data is received.
203-
204-
data is a non-empty bytes object containing the incoming data.
205-
"""
206-
Log.debug("recv: {}", data, ":hex")
207-
self.framer.processIncomingPacket(data, self._handle_response, slave=0)
208-
209-
def cb_handle_data(self, _data: bytes) -> int:
209+
def cb_base_handle_data(self, data: bytes) -> int:
210210
"""Handle received data
211211
212212
returns number of bytes consumed
213213
"""
214+
Log.debug("recv: {}", data, ":hex")
215+
self.framer.processIncomingPacket(data, self._handle_response, slave=0)
216+
return len(data)
214217

215-
def cb_connection_made(self) -> None:
216-
"""Handle new connection"""
217-
218-
def cb_connection_lost(self, _reason: Exception) -> None:
218+
def cb_base_connection_lost(self, _reason: Exception) -> None:
219219
"""Handle lost connection"""
220220
for tid in list(self.transaction):
221221
self.raise_future(

pymodbus/client/serial.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
from typing import Any, Type
77

88
from pymodbus.client.base import ModbusBaseClient
9-
from pymodbus.client.serial_asyncio import create_serial_connection
109
from pymodbus.constants import Defaults
1110
from pymodbus.exceptions import ConnectionException
1211
from pymodbus.framer import ModbusFramer
1312
from pymodbus.framer.rtu_framer import ModbusRtuFramer
1413
from pymodbus.logging import Log
14+
from pymodbus.transport.serial_asyncio import create_serial_connection
1515
from pymodbus.utilities import ModbusTransactionState
1616

1717

@@ -173,13 +173,12 @@ def __init__(
173173
else 0.05
174174
)
175175

176-
if isinstance(self.framer, ModbusRtuFramer):
177-
if self.params.baudrate > 19200:
178-
self.silent_interval = 1.75 / 1000 # ms
179-
else:
180-
self.inter_char_timeout = 1.5 * self._t0
181-
self.silent_interval = 3.5 * self._t0
182-
self.silent_interval = round(self.silent_interval, 6)
176+
if self.params.baudrate > 19200:
177+
self.silent_interval = 1.75 / 1000 # ms
178+
else:
179+
self.inter_char_timeout = 1.5 * self._t0
180+
self.silent_interval = 3.5 * self._t0
181+
self.silent_interval = round(self.silent_interval, 6)
183182

184183
@property
185184
def connected(self):

pymodbus/server/async_io.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
from contextlib import suppress
88
from typing import Union
99

10-
from pymodbus.client.serial_asyncio import create_serial_connection
1110
from pymodbus.constants import Defaults
1211
from pymodbus.datastore import ModbusServerContext
1312
from pymodbus.device import ModbusControlBlock, ModbusDeviceIdentification
@@ -21,6 +20,7 @@
2120
ModbusSocketFramer,
2221
ModbusTlsFramer,
2322
)
23+
from pymodbus.transport.serial_asyncio import create_serial_connection
2424

2525

2626
with suppress(ImportError):
File renamed without changes.

pymodbus/client/serial_asyncio/__init__.py renamed to pymodbus/transport/serial_asyncio/__init__.py

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python3
2-
# -*- coding: utf-8 -*-
32
#
43
# Implementation of asyncio support.
54
#
@@ -16,12 +15,13 @@
1615
implementation. It should be possible to get that working though.
1716
"""
1817
import asyncio
18+
import contextlib
1919
import os
2020

21-
try:
21+
22+
with contextlib.suppress(ImportError):
2223
import serial
23-
except ImportError:
24-
pass
24+
2525

2626
try:
2727
import termios
@@ -41,7 +41,7 @@ class SerialTransport(asyncio.Transport):
4141
indeed a serial port.
4242
4343
44-
You generally wont instantiate a transport yourself; instead, you
44+
You generally won`t instantiate a transport yourself; instead, you
4545
will call `create_serial_connection` which will create the
4646
transport and try to initiate the underlying communication channel,
4747
calling you back when it succeeds.
@@ -129,7 +129,8 @@ def write(self, data):
129129
130130
This method does not block; it buffers the data and arranges
131131
for it to be sent out asynchronously. Writes made after the
132-
transport has been closed will be ignored."""
132+
transport has been closed will be ignored.
133+
"""
133134
if self._closing:
134135
return
135136

@@ -151,7 +152,7 @@ def can_write_eof(self):
151152
def pause_reading(self):
152153
"""Pause the receiving end of the transport.
153154
154-
No data will be passed to the protocols data_received() method
155+
No data will be passed to the protocol`s data_received() method
155156
until resume_reading() is called.
156157
"""
157158
self._remove_reader()
@@ -167,7 +168,7 @@ def resume_reading(self):
167168
def set_write_buffer_limits(self, high=None, low=None):
168169
"""Set the high- and low-water limits for write flow control.
169170
170-
These two values control when the protocols
171+
These two values control when the protocol`s
171172
pause_writing()and resume_writing() methods are called. If
172173
specified, the low-water limit must be less than or equal to
173174
the high-water limit. Neither high nor low can be negative.
@@ -197,7 +198,7 @@ def abort(self):
197198
self._abort(None)
198199

199200
def flush(self):
200-
"""clears output buffer and stops any more data being written"""
201+
"""Clears output buffer and stops any more data being written"""
201202
self._remove_writer()
202203
self._write_buffer.clear()
203204
self._maybe_resume_protocol()
@@ -361,7 +362,7 @@ def _set_write_buffer_limits(self, high=None, low=None):
361362
if low is None:
362363
low = high // 4
363364
if not high >= low >= 0:
364-
raise ValueError("high (%r) must be >= low (%r) must be >= 0" % (high, low))
365+
raise ValueError(f"high ({high!r}) must be >= low ({low!r}) must be >= 0")
365366
self._high_water = high
366367
self._low_water = low
367368

@@ -423,19 +424,15 @@ def _call_connection_lost(self, exc):
423424
assert not self._has_writer
424425
assert not self._has_reader
425426
if self._serial:
426-
try:
427+
with contextlib.suppress(Exception):
427428
self._serial.flush()
428-
except serial.SerialException if os.name == "nt" else termios.error:
429-
# ignore serial errors which may happen if the serial device was
430-
# hot-unplugged.
431-
pass
429+
432430
self._serial.close()
433431
self._serial = None
434432
if self._protocol:
435-
try:
433+
with contextlib.suppress(Exception):
436434
self._protocol.connection_lost(exc)
437-
except:
438-
pass
435+
439436
self._write_buffer.clear()
440437
self._write_buffer.clear()
441438
self._loop = None

0 commit comments

Comments
 (0)