Skip to content

Commit 16c6eca

Browse files
authored
Correct test_examples (and base code). (#1035)
1 parent 66aeeba commit 16c6eca

File tree

7 files changed

+131
-90
lines changed

7 files changed

+131
-90
lines changed

examples/client_sync.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def setup_client(args):
6666
elif args.comm == "udp":
6767
client = ModbusUdpClient(
6868
"localhost",
69-
# port=502,
69+
port=args.port,
7070
# Common optional paramers:
7171
# modbus_decoder=ClientDecoder,
7272
framer=args.framer,
@@ -122,9 +122,12 @@ def run_client(modbus_calls=None, args=None):
122122
"""Run sync client."""
123123
_logger.info("### Client ready")
124124
client = setup_client(args)
125-
client.connect()
126-
if modbus_calls:
127-
modbus_calls(client)
125+
try:
126+
client.connect()
127+
if modbus_calls:
128+
modbus_calls(client)
129+
except: # pylint: disable=bare-except # noqa: E722
130+
_logger.error("Got exception in client.")
128131
client.close()
129132
_logger.info("### End of Program")
130133

examples/server_async.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ def setup_server(args):
6161
"""Run server setup."""
6262
if not args:
6363
args = get_commandline()
64+
defer_start = False # No function.
65+
else:
66+
defer_start = True # Needed when running tests, otherwise no function.
6467

6568
# The datastores only respond to the addresses that are initialized
6669
# If you initialize a DataBlock to addresses of 0x00 to 0xFF, a request to
@@ -136,16 +139,16 @@ def setup_server(args):
136139
)
137140
if args.comm != "serial":
138141
args.port = int(args.port)
139-
return args.comm, args.port, store, identity, args.framer
142+
return args.comm, args.port, store, identity, args.framer, defer_start
140143

141144

142145
async def run_server(args=None):
143146
"""Run server."""
144-
server, port, store, identity, framer = setup_server(args)
147+
server_id, port, store, identity, framer, defer_start = setup_server(args)
145148

146149
_logger.info("### start server")
147-
if server == "tcp":
148-
server_obj = await StartTcpServer(
150+
if server_id == "tcp":
151+
server = StartTcpServer(
149152
context=store, # Data storage
150153
identity=identity, # server identify
151154
# TBD host=
@@ -159,9 +162,10 @@ async def run_server(args=None):
159162
broadcast_enable=False, # treat unit_id 0 as broadcast address,
160163
# TBD timeout=1, # waiting time for request to complete
161164
# TBD strict=True, # use strict timing, t1.5 for Modbus RTU
165+
defer_start=defer_start # Only define server do not activate
162166
)
163-
elif server == "udp":
164-
server_obj = await StartUdpServer(
167+
elif server_id == "udp":
168+
server = StartUdpServer(
165169
context=store, # Data storage
166170
identity=identity, # server identify
167171
address=("", port), # listen address
@@ -173,11 +177,12 @@ async def run_server(args=None):
173177
broadcast_enable=False, # treat unit_id 0 as broadcast address,
174178
# TBD timeout=1, # waiting time for request to complete
175179
# TBD strict=True, # use strict timing, t1.5 for Modbus RTU
180+
defer_start=defer_start # Only define server do not activate
176181
)
177-
elif server == "serial":
182+
elif server_id == "serial":
178183
# socat -d -d PTY,link=/tmp/ptyp0,raw,echo=0,ispeed=9600 PTY,
179184
# link=/tmp/ttyp0,raw,echo=0,ospeed=9600
180-
server_obj = await StartSerialServer(
185+
server = StartSerialServer(
181186
context=store, # Data storage
182187
identity=identity, # server identify
183188
timeout=0.005, # waiting time for request to complete
@@ -193,9 +198,10 @@ async def run_server(args=None):
193198
ignore_missing_slaves=True, # ignore request to a missing slave
194199
broadcast_enable=False, # treat unit_id 0 as broadcast address,
195200
strict=True, # use strict timing, t1.5 for Modbus RTU
201+
defer_start=defer_start # Only define server do not activate
196202
)
197-
elif server == "tls":
198-
server_obj = await StartTlsServer(
203+
elif server_id == "tls":
204+
server = StartTlsServer(
199205
context=store, # Data storage
200206
host="localhost", # define tcp address where to connect to.
201207
port=port, # on which port
@@ -214,10 +220,9 @@ async def run_server(args=None):
214220
broadcast_enable=False, # treat unit_id 0 as broadcast address,
215221
# TBD timeout=1, # waiting time for request to complete
216222
# TBD strict=True, # use strict timing, t1.5 for Modbus RTU
223+
defer_start=defer_start # Only define server do not activate
217224
)
218-
asyncio.get_event_loop().call_later(20, lambda: server.serve_forever)
219-
await server_obj.serve_forever()
220-
225+
return server
221226

222227
# --------------------------------------------------------------------------- #
223228
# Extra code, to allow commandline parameters instead of changing the code

examples/server_sync.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ def setup_server(args):
6060
"""Run server setup."""
6161
if not args:
6262
args = get_commandline()
63+
defer_start = False # No function.
64+
else:
65+
defer_start = True # Needed when running tests, otherwise no function.
6366

6467
# The datastores only respond to the addresses that are initialized
6568
# If you initialize a DataBlock to addresses of 0x00 to 0xFF, a request to
@@ -135,14 +138,14 @@ def setup_server(args):
135138
)
136139
if args.comm != "serial":
137140
args.port = int(args.port)
138-
return args.comm, args.port, store, identity, args.framer, args.prepare
141+
return args.comm, args.port, store, identity, args.framer, defer_start
139142

140143

141144
def run_server(args=None):
142145
"""Run server."""
143-
server_id, port, store, identity, framer, prepare = setup_server(args)
144-
145-
_logger.info("### start server")
146+
server_id, port, store, identity, framer, defer_start = setup_server(args)
147+
txt = f"### start server, listening on {port} - {server_id}"
148+
_logger.info(txt)
146149
if server_id == "tcp":
147150
server = StartTcpServer(
148151
context=store, # Data storage
@@ -158,21 +161,24 @@ def run_server(args=None):
158161
# broadcast_enable=False, # treat unit_id 0 as broadcast address,
159162
# TBD timeout=1, # waiting time for request to complete
160163
# TBD strict=True, # use strict timing, t1.5 for Modbus RTU
161-
prepare=prepare # Only prepare server do not activate, INTERNAL.
164+
defer_start=defer_start # Only define server do not activate
162165
)
163166
elif server_id == "udp":
164167
server = StartUdpServer(
165168
context=store, # Data storage
166169
identity=identity, # server identify
170+
# TBD host=
171+
# TBD port=
167172
address=("", port), # listen address
168-
custom_functions=[], # allow custom handling
173+
# custom_functions=[], # allow custom handling
169174
framer=framer, # The framer strategy to use
170-
handler=None, # handler for each session
175+
# TBD handler=None, # handler for each session
171176
# TBD allow_reuse_address=True, # allow the reuse of an address
172-
ignore_missing_slaves=True, # ignore request to a missing slave
173-
broadcast_enable=False, # treat unit_id 0 as broadcast address,
177+
# ignore_missing_slaves=True, # ignore request to a missing slave
178+
# broadcast_enable=False, # treat unit_id 0 as broadcast address,
174179
# TBD timeout=1, # waiting time for request to complete
175180
# TBD strict=True, # use strict timing, t1.5 for Modbus RTU
181+
defer_start=defer_start # Only define server do not activate
176182
)
177183
elif server_id == "serial":
178184
# socat -d -d PTY,link=/tmp/ptyp0,raw,echo=0,ispeed=9600 PTY,
@@ -193,6 +199,7 @@ def run_server(args=None):
193199
ignore_missing_slaves=True, # ignore request to a missing slave
194200
broadcast_enable=False, # treat unit_id 0 as broadcast address,
195201
strict=True, # use strict timing, t1.5 for Modbus RTU
202+
defer_start=defer_start # Only define server do not activate
196203
)
197204
elif server_id == "tls":
198205
server = StartTlsServer(
@@ -214,6 +221,7 @@ def run_server(args=None):
214221
broadcast_enable=False, # treat unit_id 0 as broadcast address,
215222
# TBD timeout=1, # waiting time for request to complete
216223
# TBD strict=True, # use strict timing, t1.5 for Modbus RTU
224+
defer_start=defer_start # Only define server do not activate
217225
)
218226
return server
219227

pymodbus/server/async_io.py

Lines changed: 26 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,7 @@ def connection_lost(self, call_exc):
125125
_logger.debug(txt)
126126

127127
self.running = False
128-
129-
except Exception as exc: # pragma: no cover pylint: disable=broad-except
128+
except Exception as exc: # pylint: disable=broad-except
130129
txt = (
131130
f"Datastore unable to fulfill request: {exc}; {traceback.format_exc()}"
132131
)
@@ -858,9 +857,9 @@ async def StartTcpServer( # pylint: disable=invalid-name,dangerous-default-valu
858857
:param address: An optional (interface, port) to bind to.
859858
:param custom_functions: An optional list of custom function classes
860859
supported by server instance.
861-
:param defer_start: if set, a coroutine which can be started and stopped
862-
will be returned. Otherwise, the server will be immediately spun
863-
up without the ability to shut it off from within the asyncio loop
860+
:param defer_start: if set, the server object will be returned ready to start.
861+
Otherwise, the server will be immediately spun
862+
up without the ability to shut it off
864863
:param kwargs: The rest
865864
:return: an initialized but inactive server object coroutine
866865
"""
@@ -870,10 +869,9 @@ async def StartTcpServer( # pylint: disable=invalid-name,dangerous-default-valu
870869
for func in custom_functions:
871870
server.decoder.register(func) # pragma: no cover
872871

873-
if not defer_start:
874-
await server.serve_forever()
875-
876-
return server
872+
if defer_start:
873+
return server
874+
await server.serve_forever()
877875

878876

879877
async def StartTlsServer( # pylint: disable=invalid-name,dangerous-default-value,too-many-arguments
@@ -906,9 +904,9 @@ async def StartTlsServer( # pylint: disable=invalid-name,dangerous-default-valu
906904
:param allow_reuse_port: Whether the server will allow the reuse of a port.
907905
:param custom_functions: An optional list of custom function classes
908906
supported by server instance.
909-
:param defer_start: if set, a coroutine which can be started and stopped
910-
will be returned. Otherwise, the server will be immediately spun
911-
up without the ability to shut it off from within the asyncio loop
907+
:param defer_start: if set, the server object will be returned ready to start.
908+
Otherwise, the server will be immediately spun
909+
up without the ability to shut it off
912910
:param kwargs: The rest
913911
:return: an initialized but inactive server object coroutine
914912
"""
@@ -931,10 +929,9 @@ async def StartTlsServer( # pylint: disable=invalid-name,dangerous-default-valu
931929
for func in custom_functions:
932930
server.decoder.register(func) # pragma: no cover
933931

934-
if not defer_start:
935-
await server.serve_forever()
936-
937-
return server
932+
if defer_start:
933+
return server
934+
await server.serve_forever()
938935

939936

940937
async def StartUdpServer( # pylint: disable=invalid-name,dangerous-default-value
@@ -952,7 +949,9 @@ async def StartUdpServer( # pylint: disable=invalid-name,dangerous-default-valu
952949
:param address: An optional (interface, port) to bind to.
953950
:param custom_functions: An optional list of custom function classes
954951
supported by server instance.
955-
:param defer_start: start with delay
952+
:param defer_start: if set, the server object will be returned ready to start.
953+
Otherwise, the server will be immediately spun
954+
up without the ability to shut it off
956955
:param kwargs:
957956
"""
958957
framer = kwargs.pop("framer", ModbusSocketFramer)
@@ -961,16 +960,16 @@ async def StartUdpServer( # pylint: disable=invalid-name,dangerous-default-valu
961960
for func in custom_functions:
962961
server.decoder.register(func) # pragma: no cover
963962

964-
if not defer_start:
965-
await server.serve_forever() # pragma: no cover
966-
967-
return server
963+
if defer_start:
964+
return server
965+
await server.serve_forever()
968966

969967

970968
async def StartSerialServer( # pylint: disable=invalid-name,dangerous-default-value
971969
context=None,
972970
identity=None,
973971
custom_functions=[],
972+
defer_start=False,
974973
**kwargs,
975974
): # pragma: no cover
976975
"""Start and run a serial modbus server.
@@ -979,25 +978,22 @@ async def StartSerialServer( # pylint: disable=invalid-name,dangerous-default-v
979978
:param identity: An optional identify structure
980979
:param custom_functions: An optional list of custom function classes
981980
supported by server instance.
981+
:param defer_start: if set, the server object will be returned ready to start.
982+
Otherwise, the server will be immediately spun
983+
up without the ability to shut it off
982984
:param kwargs: The rest
983985
"""
984986
framer = kwargs.pop("framer", ModbusAsciiFramer)
985987
server = ModbusSerialServer(context, framer, identity=identity, **kwargs)
986988
for func in custom_functions:
987989
server.decoder.register(func)
990+
991+
if defer_start:
992+
return server
988993
await server.start()
989994
await server.serve_forever()
990995

991996

992-
def StopServer(): # pylint: disable=invalid-name
993-
"""Stop Async Server."""
994-
warnings.warn(
995-
"deprecated API for asyncio. Call server_close() on "
996-
"server object returned by StartXxxServer",
997-
DeprecationWarning,
998-
)
999-
1000-
1001997
# --------------------------------------------------------------------------- #
1002998
# Exported symbols
1003999
# --------------------------------------------------------------------------- #

0 commit comments

Comments
 (0)