Skip to content

Commit 0216a9e

Browse files
authored
Update v2.5.3 examples. (#1430)
1 parent 5115614 commit 0216a9e

15 files changed

+438
-1057
lines changed

.pydevproject

Lines changed: 0 additions & 8 deletions
This file was deleted.

doc/source/examples.rst

Lines changed: 26 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -10,34 +10,46 @@ These examples are considered essential usage examples, and are guaranteed to wo
1010
because they are tested automatilly with each dev branch commit using CI.
1111

1212

13-
Asynchronous Client Example
13+
Asynchronous client Example
1414
^^^^^^^^^^^^^^^^^^^^^^^^^^^
1515
.. literalinclude:: ../../examples/client_async.py
1616

17-
Asynchronous Client basic calls example
17+
Asynchronous client basic calls example
1818
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1919
.. literalinclude:: ../../examples/client_calls.py
2020

21-
Modbus Payload Example
22-
^^^^^^^^^^^^^^^^^^^^^^
23-
.. literalinclude:: ../../examples/client_payload.py
21+
Asynchronous server example
22+
^^^^^^^^^^^^^^^^^^^^^^^^^^^
23+
.. literalinclude:: ../../examples/server_async.py
2424

25-
Synchronous Client Example
26-
^^^^^^^^^^^^^^^^^^^^^^^^^^
27-
.. literalinclude:: ../../examples/client_sync.py
25+
Build bcd Payload example
26+
^^^^^^^^^^^^^^^^^^^^^^^^^
27+
.. literalinclude:: ../../examples/build_bcd_payload.py
2828

29-
Forwarder Example
30-
^^^^^^^^^^^^^^^^^
29+
Message generator example
30+
^^^^^^^^^^^^^^^^^^^^^^^^^
31+
.. literalinclude:: ../../examples/message_generator.py
32+
33+
Message Parser example
34+
^^^^^^^^^^^^^^^^^^^^^^
35+
.. literalinclude:: ../../examples/message_parser.py
36+
37+
Modbus forwarder Example
38+
^^^^^^^^^^^^^^^^^^^^^^^^
3139
.. literalinclude:: ../../examples/modbus_forwarder.py
3240

33-
Asynchronous server example
34-
^^^^^^^^^^^^^^^^^^^^^^^^^^^
35-
.. literalinclude:: ../../examples/server_async.py
41+
Modbus payload client Example
42+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
43+
.. literalinclude:: ../../examples/client_payload.py
3644

37-
Modbus Payload Server example
45+
Modbus payload Server example
3846
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3947
.. literalinclude:: ../../examples/server_payload.py
4048

49+
Synchronous client Example
50+
^^^^^^^^^^^^^^^^^^^^^^^^^^
51+
.. literalinclude:: ../../examples/client_sync.py
52+
4153
Synchronous server example
4254
^^^^^^^^^^^^^^^^^^^^^^^^^^
4355
.. literalinclude:: ../../examples/server_sync.py
@@ -74,18 +86,10 @@ These examples have not been upgraded to v3.0.0 but are still relevant.
7486
Help is wanted to upgrade the examples.
7587

7688

77-
Bcd Payload example
78-
^^^^^^^^^^^^^^^^^^^
79-
.. literalinclude:: ../../examples/v2.5.3/bcd_payload.py
80-
8189
Callback Server example
8290
^^^^^^^^^^^^^^^^^^^^^^^
8391
.. literalinclude:: ../../examples/v2.5.3/callback_server.py
8492

85-
Concurrent Client example
86-
^^^^^^^^^^^^^^^^^^^^^^^^^
87-
.. literalinclude:: ../../examples/v2.5.3/concurrent_client.py
88-
8993
Custom Message example
9094
^^^^^^^^^^^^^^^^^^^^^^
9195
.. literalinclude:: ../../examples/v2.5.3/custom_message.py
@@ -98,18 +102,6 @@ Deviceinfo showcase server example
98102
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
99103
.. literalinclude:: ../../examples/v2.5.3/deviceinfo_showcase_server.py
100104

101-
Message Generator example
102-
^^^^^^^^^^^^^^^^^^^^^^^^^
103-
.. literalinclude:: ../../examples/v2.5.3/message_generator.py
104-
105-
Message Parser example
106-
^^^^^^^^^^^^^^^^^^^^^^
107-
.. literalinclude:: ../../examples/v2.5.3/message_parser.py
108-
109-
Modbus Mapper example
110-
^^^^^^^^^^^^^^^^^^^^^
111-
.. literalinclude:: ../../examples/v2.5.3/modbus_mapper.py
112-
113105
Modbus Saver example
114106
^^^^^^^^^^^^^^^^^^^^
115107
.. literalinclude:: ../../examples/v2.5.3/modbus_saver.py
Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# pylint: disable=missing-type-doc,missing-param-doc,differing-param-doc,missing-raises-doc,missing-any-param-doc
21
"""Modbus BCD Payload Builder.
32
43
This is an example of building a custom payload builder
@@ -13,10 +12,10 @@
1312
from pymodbus.utilities import pack_bitstring, unpack_bitstring
1413

1514

16-
def convert_to_bcd(decimal):
15+
def convert_to_bcd(decimal: float) -> int:
1716
"""Convert a decimal value to a bcd value
1817
19-
:param value: The decimal value to to pack into bcd
18+
:param decimal: The decimal value to to pack into bcd
2019
:returns: The number in bcd form
2120
"""
2221
place, bcd = 0, 0
@@ -28,10 +27,10 @@ def convert_to_bcd(decimal):
2827
return bcd
2928

3029

31-
def convert_from_bcd(bcd):
30+
def convert_from_bcd(bcd: int) -> int:
3231
"""Convert a bcd value to a decimal value
3332
34-
:param value: The value to unpack from bcd
33+
:param bcd: The value to unpack from bcd
3534
:returns: The number in decimal form
3635
"""
3736
place, decimal = 1, 0
@@ -43,7 +42,7 @@ def convert_from_bcd(bcd):
4342
return decimal
4443

4544

46-
def count_bcd_digits(bcd):
45+
def count_bcd_digits(bcd: int) -> int:
4746
"""Count the number of digits in a bcd value
4847
4948
:param bcd: The bcd number to count the digits of
@@ -101,22 +100,23 @@ def build(self):
101100
string = string + ("\x00" * (length % 2))
102101
return [string[i : i + 2] for i in range(0, length, 2)]
103102

104-
def add_bits(self, values):
103+
def add_bits(self, values: int) -> int:
105104
"""Add a collection of bits to be encoded
106105
107106
If these are less than a multiple of eight,
108107
they will be left padded with 0 bits to make
109108
it so.
110109
111-
:param value: The value to add to the buffer
110+
:param values: The value to add to the buffer
112111
"""
113112
value = pack_bitstring(values)
114113
self._payload.append(value)
115114

116-
def add_number(self, value, size=None):
115+
def add_number(self, value: int, size: int = None):
117116
"""Add any 8bit numeric type to the buffer
118117
119118
:param value: The value to add to the buffer
119+
:param size: Size of buffer
120120
"""
121121
encoded = []
122122
value = convert_to_bcd(value)
@@ -128,7 +128,7 @@ def add_number(self, value, size=None):
128128
size -= 1
129129
self._payload.extend(encoded)
130130

131-
def add_string(self, value):
131+
def add_string(self, value: str):
132132
"""Add a string to the buffer
133133
134134
:param value: The value to add to the buffer
@@ -155,7 +155,7 @@ def __init__(self, payload):
155155
self._pointer = 0x00
156156

157157
@staticmethod
158-
def fromRegisters(registers, endian=Endian.Little): # pylint: disable=invalid-name
158+
def fromRegisters(registers: int, endian: str = Endian.Little):
159159
"""Initialize a payload decoder
160160
161161
with the result of reading a collection of registers from a modbus device.
@@ -167,14 +167,15 @@ def fromRegisters(registers, endian=Endian.Little): # pylint: disable=invalid-n
167167
:param registers: The register results to initialize with
168168
:param endian: The endianness of the payload
169169
:returns: An initialized PayloadDecoder
170+
:raises ParameterException: parameter exception
170171
"""
171172
if isinstance(registers, list): # repack into flat binary
172173
payload = "".join(pack(">H", x) for x in registers)
173174
return BinaryPayloadDecoder(payload, endian)
174175
raise ParameterException("Invalid collection of registers supplied")
175176

176177
@staticmethod
177-
def fromCoils(coils, endian=Endian.Little): # pylint: disable=invalid-name
178+
def fromCoils(coils: int, endian: str = Endian.Little):
178179
"""Initialize a payload decoder.
179180
180181
with the result of reading a collection of coils from a modbus device.
@@ -184,6 +185,7 @@ def fromCoils(coils, endian=Endian.Little): # pylint: disable=invalid-name
184185
:param coils: The coil results to initialize with
185186
:param endian: The endianness of the payload
186187
:returns: An initialized PayloadDecoder
188+
:raises ParameterException: parameter exception
187189
"""
188190
if isinstance(coils, list):
189191
payload = pack_bitstring(coils)
@@ -206,7 +208,7 @@ def decode_bits(self):
206208
handle = self._payload[self._pointer - 1 : self._pointer]
207209
return unpack_bitstring(handle)
208210

209-
def decode_string(self, size=1):
211+
def decode_string(self, size: int = 1):
210212
"""Decode a string from the buffer
211213
212214
:param size: The size of the string to decode
@@ -215,6 +217,9 @@ def decode_string(self, size=1):
215217
return self._payload[self._pointer - size : self._pointer]
216218

217219

220+
if __name__ == "__main__":
221+
print("Test")
222+
218223
# --------------------------------------------------------------------------- #
219224
# Exported Identifiers
220225
# --------------------------------------------------------------------------- #

examples/client_test.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,13 @@ async def _handle_discrete_input(client):
5050
async def _handle_holding_registers(client):
5151
"""Read/write holding registers."""
5252
_logger.info("### write holding register and read holding registers")
53-
_check_call(await client.write_register(3, 17, slave=SLAVE))
53+
_check_call(await client.write_register(3, 21, slave=SLAVE))
5454
rr = None
55-
rr = _check_call(await client.read_holding_registers(3, 1, slave=SLAVE))
56-
assert rr.registers[0] == 17
5755
rr = _check_call(await client.read_holding_registers(4, 2, slave=SLAVE))
58-
assert rr.registers[0] == 9
59-
assert rr.registers[1] == 27177
56+
assert rr.registers[0] == 17
57+
assert rr.registers[1] == 17
58+
rr = _check_call(await client.read_holding_registers(3, 1, slave=SLAVE))
59+
assert rr.registers[0] == 21
6060

6161

6262
async def _execute_information_requests(client):
@@ -65,7 +65,7 @@ async def _execute_information_requests(client):
6565
rr = _check_call(
6666
await client.execute(req_mei.ReadDeviceInformationRequest(slave=SLAVE))
6767
)
68-
assert rr.information[0] == b"pymodbus"
68+
assert rr.information[0] == b"Pymodbus"
6969

7070

7171
async def _execute_diagnostic_requests(client):
@@ -86,11 +86,11 @@ async def _execute_diagnostic_requests(client):
8686

8787
async def run_async_calls(client):
8888
"""Demonstrate basic read/write calls."""
89-
await _handle_coils(client)
90-
await _handle_discrete_input(client)
91-
await _handle_holding_registers(client)
89+
# await _handle_coils(client)
90+
# await _handle_discrete_input(client)
91+
# await _handle_holding_registers(client)
9292
await _execute_information_requests(client)
93-
await _execute_diagnostic_requests(client)
93+
# await _execute_diagnostic_requests(client)
9494

9595

9696
if __name__ == "__main__":

examples/contrib/serial_forwarder.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,6 @@
1414
from pymodbus.server.async_io import ModbusTcpServer
1515

1616

17-
FORMAT = "%(asctime)-15s %(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s"
18-
logging.basicConfig(format=FORMAT)
1917
_logger = logging.getLogger()
2018

2119

@@ -60,10 +58,14 @@ async def stop(self):
6058

6159
def get_commandline():
6260
"""Read and validate command line arguments"""
63-
logchoices = ["critical", "error", "warning", "info", "debug"]
64-
6561
parser = argparse.ArgumentParser(description="Command line options")
66-
parser.add_argument("--log", help=",".join(logchoices), default="info", type=str)
62+
parser.add_argument(
63+
"--log",
64+
choices=["critical", "error", "warning", "info", "debug"],
65+
help="set log level, default is info",
66+
default="info",
67+
type=str,
68+
)
6769
parser.add_argument(
6870
"--port", help="RTU serial port", default="/dev/ttyUSB0", type=str
6971
)
@@ -77,9 +79,7 @@ def get_commandline():
7779
args = parser.parse_args()
7880

7981
# set defaults
80-
_logger.setLevel(
81-
args.log.upper() if args.log.lower() in logchoices else logging.INFO
82-
)
82+
_logger.setLevel(args.log.upper())
8383
if not args.slaves:
8484
args.slaves = {1, 2, 3}
8585
return args.port, args.baudrate, args.server_port, args.server_ip, args.slaves

examples/helper.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import argparse
88
import dataclasses
99
import logging
10-
from dataclasses import dataclass
1110

1211
from pymodbus import pymodbus_apply_logging_config
1312
from pymodbus.transaction import (
@@ -22,7 +21,7 @@
2221
_logger = logging.getLogger()
2322

2423

25-
@dataclass
24+
@dataclasses.dataclass
2625
class Commandline:
2726
"""Simulate commandline parameters.
2827
@@ -40,15 +39,16 @@ class Commandline:
4039
slaves = None
4140
client_port = None
4241
client = None
42+
log = "debug"
4343

4444
@classmethod
4545
def copy(cls):
46-
"""Copy Commandline"""
46+
"""Copy kl"""
4747
to_copy = cls()
4848
return dataclasses.replace(to_copy)
4949

5050

51-
def get_commandline(server=False, description=None, extras=None):
51+
def get_commandline(server=False, description=None, extras=None, cmdline=None):
5252
"""Read and validate command line arguments"""
5353
parser = argparse.ArgumentParser(description=description)
5454
parser.add_argument(
@@ -113,7 +113,7 @@ def get_commandline(server=False, description=None, extras=None):
113113
if extras:
114114
for extra in extras:
115115
parser.add_argument(extra[0], **extra[1])
116-
args = parser.parse_args()
116+
args = parser.parse_args(cmdline)
117117

118118
# set defaults
119119
comm_defaults = {
Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@
157157
modbus_diag.ReturnBusCommunicationErrorCountResponse,
158158
modbus_diag.ReturnBusExceptionErrorCountResponse,
159159
modbus_diag.ReturnSlaveMessageCountResponse,
160-
modbus_diag.ReturnSlaveNoReponseCountResponse,
160+
modbus_diag.ReturnSlaveNoResponseCountResponse,
161161
modbus_diag.ReturnSlaveNAKCountResponse,
162162
modbus_diag.ReturnSlaveBusyCountResponse,
163163
modbus_diag.ReturnSlaveBusCharacterOverrunCountResponse,
@@ -271,10 +271,8 @@ def get_options():
271271
return opt
272272

273273

274-
def main():
274+
def main(option):
275275
"""Run main runner function"""
276-
option = get_options()
277-
278276
if option.debug:
279277
try:
280278
modbus_log.setLevel(logging.DEBUG)
@@ -292,4 +290,4 @@ def main():
292290

293291

294292
if __name__ == "__main__":
295-
main()
293+
main(get_options())

0 commit comments

Comments
 (0)