Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simple examples. #1590

Merged
merged 3 commits into from
Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 30 additions & 6 deletions doc/source/examples.rst
Original file line number Diff line number Diff line change
@@ -1,18 +1,42 @@
Examples
========

The examples can be downloaded from https://github.com/pymodbus-dev/pymodbus/tree/dev/examples
Examples are divided in 2 parts:

.. tip:: The examples needs to be run from within the examples directory, unless you modify them.
Most examples use helper.py and client_*.py or server_*.py. This is done to avoid maintaining the
same code in multiple files.
The first part are some simple examples which can be copied and run directly. These examples show the basic functionality of the library.

The second part are more advanced examples, but in order to not duplicate code, this requires you to download the examples directory and run
the examples in the directory.


Ready to run examples:
----------------------

These examples are very basic examples, showing how a client can communicate with a server.

You need to modify the code to adapt it to your situation.

Examples:
---------
Simple asynchronous client
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. literalinclude:: ../../examples/simple_async_client.py

Simple synchronous client
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. literalinclude:: ../../examples/simple_sync_client.py


Advanced examples
-----------------

These examples are considered essential usage examples, and are guaranteed to work,
because they are tested automatilly with each dev branch commit using CI.

The examples directory can be downloaded from https://github.com/pymodbus-dev/pymodbus/tree/dev/examples

.. tip:: The examples needs to be run from within the examples directory, unless you modify them.
Most examples use helper.py and client_*.py or server_*.py. This is done to avoid maintaining the
same code in multiple files.


Asynchronous client
^^^^^^^^^^^^^^^^^^^
Expand Down
4 changes: 2 additions & 2 deletions examples/client_async.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Pymodbus Aynchronous Client Example.
"""Pymodbus aynchronous client example.

An example of a single threaded synchronous client.
An example of a asynchronous client.

usage: client_async.py [-h] [--comm {tcp,udp,serial,tls}]
[--framer {ascii,binary,rtu,socket,tls}]
Expand Down
132 changes: 132 additions & 0 deletions examples/simple_async_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Pymodbus asynchronous client example.

An example of a single threaded synchronous client.

usage: simple_client_async.py

All options must be adapted in the code
The corresponding server must be started before e.g. as:
python3 server_sync.py
"""
import asyncio

from pymodbus import pymodbus_apply_logging_config

# --------------------------------------------------------------------------- #
# import the various client implementations
# --------------------------------------------------------------------------- #
from pymodbus.client import (
AsyncModbusSerialClient,
AsyncModbusTcpClient,
AsyncModbusTlsClient,
AsyncModbusUdpClient,
)
from pymodbus.exceptions import ModbusException
from pymodbus.pdu import ExceptionResponse
from pymodbus.transaction import (
# ModbusAsciiFramer,
# ModbusBinaryFramer,
ModbusRtuFramer,
ModbusSocketFramer,
ModbusTlsFramer,
)


async def run_async_client():
"""Run async client."""

# activate debugging
pymodbus_apply_logging_config("DEBUG")

# change to test other client types
select_my_client = "tcp"

print("get client")
if select_my_client == "tcp":
client = AsyncModbusTcpClient(
"127.0.0.1", # host
port=5020,
framer=ModbusSocketFramer,
# timeout=10,
# retries=3,
# retry_on_empty=False,
# close_comm_on_error=False,
# strict=True,
# source_address=("localhost", 0),
)
elif select_my_client == "udp":
client = AsyncModbusUdpClient(
"127.0.0.1", # host
port=5020,
framer=ModbusSocketFramer,
# timeout=10,
# retries=3,
# retry_on_empty=False,
# close_comm_on_error=False,
# strict=True,
# source_address=None,
)
elif select_my_client == "serial":
client = AsyncModbusSerialClient(
"/dev/tty01", # tty port
framer=ModbusRtuFramer,
# timeout=10,
# retries=3,
# retry_on_empty=False,
# close_comm_on_error=False,
# strict=True,
baudrate=9600,
# bytesize=8,
# parity="N",
# stopbits=1,
# handle_local_echo=False,
)
elif select_my_client == "tls":
client = AsyncModbusTlsClient(
"127.0.0.1", # host
port=5020,
framer=ModbusTlsFramer,
# timeout=10,
# retries=3,
# retry_on_empty=False,
# close_comm_on_error=False,
# strict=True,
# sslctx=sslctx,
certfile="my_cert.crt",
keyfile="my_cert.key",
# password="none",
server_hostname="localhost",
)
else:
print(f"Unknown client {select_my_client} selected")
return

print("connect to server")
await client.connect()
# test client is connected
assert client.connected

print("get and verify data")
try:
# See all calls in client_calls.py
rr = await client.read_coils(1, 1, slave=1)
except ModbusException as exc:
print(f"Received ModbusException({exc}) from library")
client.close()
return
if rr.isError():
print(f"Received Modbus library error({rr})")
client.close()
return
if isinstance(rr, ExceptionResponse):
print(f"Received Modbus library exception ({rr})")
# THIS IS NOT A PYTHON EXCEPTION, but a valid modbus message
client.close()

print("close connection")
client.close()


if __name__ == "__main__":
asyncio.run(run_async_client(), debug=True)
127 changes: 127 additions & 0 deletions examples/simple_sync_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""Pymodbus synchronous client example.

An example of a single threaded synchronous client.

usage: simple_client_async.py

All options must be adapted in the code
The corresponding server must be started before e.g. as:
python3 server_sync.py
"""

# --------------------------------------------------------------------------- #
# import the various client implementations
# --------------------------------------------------------------------------- #
from pymodbus import pymodbus_apply_logging_config
from pymodbus.client import (
ModbusSerialClient,
ModbusTcpClient,
ModbusTlsClient,
ModbusUdpClient,
)
from pymodbus.exceptions import ModbusException
from pymodbus.pdu import ExceptionResponse
from pymodbus.transaction import (
# ModbusAsciiFramer,
# ModbusBinaryFramer,
ModbusRtuFramer,
ModbusSocketFramer,
ModbusTlsFramer,
)


def run_sync_client():
"""Run sync client."""

# activate debugging
pymodbus_apply_logging_config("DEBUG")

# change to test other client types
select_my_client = "tcp"

print("get client")
if select_my_client == "tcp":
client = ModbusTcpClient(
"127.0.0.1", # host
port=5020,
framer=ModbusSocketFramer,
# timeout=10,
# retries=3,
# retry_on_empty=False,y
# close_comm_on_error=False,
# strict=True,
# source_address=("localhost", 0),
)
elif select_my_client == "tcp":
client = ModbusUdpClient(
"127.0.0.1", # host
port=5020,
framer=ModbusSocketFramer,
# timeout=10,
# retries=3,
# retry_on_empty=False,
# close_comm_on_error=False,
# strict=True,
# source_address=None,
)
elif select_my_client == "serial":
client = ModbusSerialClient(
"/dev/tty01", # tty port
framer=ModbusRtuFramer,
# timeout=10,
# retries=3,
# retry_on_empty=False,
# close_comm_on_error=False,.
# strict=True,
baudrate=9600,
# bytesize=8,
# parity="N",
# stopbits=1,
# handle_local_echo=False,
)
elif select_my_client == "tls":
client = ModbusTlsClient(
"127.0.0.1", # host
port=5020,
framer=ModbusTlsFramer,
# timeout=10,
# retries=3,
# retry_on_empty=False,
# close_comm_on_error=False,
# strict=True,
# sslctx=None,
certfile="my_cert.crt",
keyfile="my_cert.key",
# password=None,
server_hostname="localhost",
)
else:
print(f"Unknown client {select_my_client} selected")
return

print("connect to server")
client.connect()

print("get and verify data")
try:
rr = client.read_coils(1, 1, slave=1)
except ModbusException as exc:
print(f"Received ModbusException({exc}) from library")
client.close()
return
if rr.isError():
print(f"Received Modbus library error({rr})")
client.close()
return
if isinstance(rr, ExceptionResponse):
print(f"Received Modbus library exception ({rr})")
# THIS IS NOT A PYTHON EXCEPTION, but a valid modbus message
client.close()

print("close connection")
client.close()


if __name__ == "__main__":
run_sync_client()