You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by hu...@apache.org on 2024/05/10 14:21:07 UTC
(plc4x) 01/01: fix(plc4py): start to make the umas and modbus drivers act similialy.
This is an automated email from the ASF dual-hosted git repository.
hutcheb pushed a commit to branch fix/plc4py/lukas_branch
in repository https://gitbox.apache.org/repos/asf/plc4x.git
commit 26b333adfdc8a39a2d1028c80a4435f2703a7f7f
Author: Ben Hutcheson <be...@gmail.com>
AuthorDate: Fri May 10 16:20:55 2024 +0200
fix(plc4py): start to make the umas and modbus drivers act similialy.
---
plc4py/plc4py/drivers/modbus/ModbusConnection.py | 42 +++++++++++-----------
plc4py/plc4py/drivers/modbus/ModbusDevice.py | 1 +
plc4py/plc4py/drivers/modbus/ModbusProtocol.py | 10 ++++--
.../protocols/modbus/readwrite/ModbusTcpADU.py | 8 +----
.../drivers/modbus/test_modbus_connection.py | 18 +++++-----
.../plc4py/drivers/umas/test_umas_connection.py | 2 +-
6 files changed, 40 insertions(+), 41 deletions(-)
diff --git a/plc4py/plc4py/drivers/modbus/ModbusConnection.py b/plc4py/plc4py/drivers/modbus/ModbusConnection.py
index 9c929d7e07..d483afdcfc 100644
--- a/plc4py/plc4py/drivers/modbus/ModbusConnection.py
+++ b/plc4py/plc4py/drivers/modbus/ModbusConnection.py
@@ -60,6 +60,7 @@ class ModbusConnection(PlcConnection, PlcReader, PlcWriter, PlcConnectionMetaDat
:param config: Modbus configuration object
:param transport: Plc4xBaseTransport object used for the TCP connection
"""
+
def __init__(self, config: ModbusConfiguration, transport: Plc4xBaseTransport):
"""
Initializes a ModbusConnection object
@@ -150,7 +151,7 @@ class ModbusConnection(PlcConnection, PlcReader, PlcWriter, PlcConnectionMetaDat
"""
return DefaultReadRequestBuilder(ModbusTagBuilder)
- async def execute(self, request: PlcRequest) -> PlcResponse:
+ def execute(self, request: PlcRequest) -> Awaitable[PlcResponse]:
"""
Executes a PlcRequest as long as it's already connected
:param request: Plc Request to execute
@@ -160,9 +161,10 @@ class ModbusConnection(PlcConnection, PlcReader, PlcWriter, PlcConnectionMetaDat
return self._default_failed_request(PlcResponseCode.NOT_CONNECTED)
if isinstance(request, PlcReadRequest):
- return await self._read(request)
+ return self._read(request)
+
elif isinstance(request, PlcWriteRequest):
- return await self._write(request)
+ return self._write(request)
return self._default_failed_request(PlcResponseCode.NOT_CONNECTED)
@@ -181,7 +183,7 @@ class ModbusConnection(PlcConnection, PlcReader, PlcWriter, PlcConnectionMetaDat
"""
return self._device is None
- async def _read(self, request: PlcReadRequest) -> PlcReadResponse:
+ def _read(self, request: PlcReadRequest) -> Awaitable[PlcReadResponse]:
"""
Executes a PlcReadRequest
@@ -195,24 +197,23 @@ class ModbusConnection(PlcConnection, PlcReader, PlcWriter, PlcConnectionMetaDat
:param request: PlcReadRequest to execute
:return: PlcReadResponse
"""
- if self._check_connection():
- # If no device is set, log an error and return a response with the NOT_CONNECTED code
- logging.error("No device is set in the modbus connection!")
+ if self._device is None:
+ logging.error("No device is set in the Umas connection!")
return self._default_failed_request(PlcResponseCode.NOT_CONNECTED)
- try:
- # Send the read request to the device and wait for a response
- logging.debug("Sending read request to Modbus Device")
- response = await asyncio.wait_for(
- self._device.read(request, self._transport), 5
- )
- # Return the response
- return response
- except Exception:
- # If an error occurs during the execution of the read request, return a response with
- # the INTERNAL_ERROR code
- # TODO:- This exception is very general and probably should be replaced
- return PlcReadResponse(PlcResponseCode.INTERNAL_ERROR, {})
+ # TODO: Insert Optimizer base on data from a browse request
+ async def _request(req, device) -> PlcReadResponse:
+ try:
+ response = await asyncio.wait_for(device.read(req, self._transport), 10)
+ return response
+ except Exception:
+ # TODO:- This exception is very general and probably should be replaced
+
+ return PlcReadResponse(PlcResponseCode.INTERNAL_ERROR, {})
+
+ logging.debug("Sending read request to UmasDevice")
+ future = asyncio.ensure_future(_request(request, self._device))
+ return future
async def _write(self, request: PlcWriteRequest) -> PlcWriteResponse:
"""
@@ -295,6 +296,7 @@ class ModbusDriver(PlcDriver):
:param authentication: Optional PlcAuthentication instance used to authenticate the connection.
:return: An instance of PlcConnection that is connected to the PLC
"""
+
async def get_connection(
self, url: str, authentication: PlcAuthentication = PlcAuthentication()
) -> PlcConnection:
diff --git a/plc4py/plc4py/drivers/modbus/ModbusDevice.py b/plc4py/plc4py/drivers/modbus/ModbusDevice.py
index 977b9287e1..dedda15406 100644
--- a/plc4py/plc4py/drivers/modbus/ModbusDevice.py
+++ b/plc4py/plc4py/drivers/modbus/ModbusDevice.py
@@ -143,6 +143,7 @@ class ModbusDevice:
read_buffer,
request.tags[request.tag_names[0]].data_type,
request.tags[request.tag_names[0]].quantity,
+ True,
)
response_item = ResponseItem(PlcResponseCode.OK, returned_value)
diff --git a/plc4py/plc4py/drivers/modbus/ModbusProtocol.py b/plc4py/plc4py/drivers/modbus/ModbusProtocol.py
index 4c51d2b054..f3ae557611 100644
--- a/plc4py/plc4py/drivers/modbus/ModbusProtocol.py
+++ b/plc4py/plc4py/drivers/modbus/ModbusProtocol.py
@@ -44,12 +44,16 @@ class ModbusProtocol(Plc4xBaseProtocol):
bool: True if the estimated packet length plus the current position is less than the length of the buffer, False otherwise.
"""
current_position = read_buffer.position
- logging.debug(f"Current position in packet_length_estimator: {current_position}")
+ logging.debug(
+ f"Current position in packet_length_estimator: {current_position}"
+ )
read_buffer.position = 8 * 4
packet_length: int = read_buffer.read_unsigned_short()
logging.debug(f"Packet length in packet_length_estimator: {packet_length}")
read_buffer.position = current_position
- logging.debug(f"Buffer length in packet_length_estimator: {len(read_buffer.bb)}")
+ logging.debug(
+ f"Buffer length in packet_length_estimator: {len(read_buffer.bb)}"
+ )
return packet_length + current_position < len(read_buffer.bb)
def data_received(self, data):
@@ -79,7 +83,7 @@ class ModbusProtocol(Plc4xBaseProtocol):
adu: ModbusTcpADU = ModbusTcpADU.static_parse_builder(
read_buffer, DriverType.MODBUS_TCP, True
).build(True)
- #logging.debug(f"Received ADU: {adu}")
+ # logging.debug(f"Received ADU: {adu}")
# If the ADU transaction identifier is in the messages dictionary,
# set the PDU (data) as a result of the associated Future object.
if adu.transaction_identifier in self.messages:
diff --git a/plc4py/plc4py/protocols/modbus/readwrite/ModbusTcpADU.py b/plc4py/plc4py/protocols/modbus/readwrite/ModbusTcpADU.py
index bd61d7b75f..f0edc3a8ee 100644
--- a/plc4py/plc4py/protocols/modbus/readwrite/ModbusTcpADU.py
+++ b/plc4py/plc4py/protocols/modbus/readwrite/ModbusTcpADU.py
@@ -101,7 +101,6 @@ class ModbusTcpADU(ModbusADU):
read_buffer: ReadBuffer, driver_type: DriverType, response: bool
):
read_buffer.push_context("ModbusTcpADU")
- print(f"Entering ModbusTcpADU static_parse_builder()")
transaction_identifier: int = read_buffer.read_unsigned_short(
logical_name="transaction_identifier",
@@ -110,7 +109,6 @@ class ModbusTcpADU(ModbusADU):
driver_type=driver_type,
response=response,
)
- print(f"transaction_identifier: 0x{transaction_identifier:04x}")
PROTOCOL_IDENTIFIER: int = read_buffer.read_unsigned_short(
logical_name="protocol_identifier",
@@ -118,7 +116,6 @@ class ModbusTcpADU(ModbusADU):
driver_type=driver_type,
response=response,
)
- print(f"PROTOCOL_IDENTIFIER: 0x{PROTOCOL_IDENTIFIER:04x}")
length: int = read_buffer.read_unsigned_short(
logical_name="length",
@@ -126,7 +123,6 @@ class ModbusTcpADU(ModbusADU):
driver_type=driver_type,
response=response,
)
- print(f"length: {length}")
unit_identifier: int = read_buffer.read_unsigned_byte(
logical_name="unit_identifier",
@@ -135,7 +131,6 @@ class ModbusTcpADU(ModbusADU):
driver_type=driver_type,
response=response,
)
- print(f"unit_identifier: 0x{unit_identifier:02x}")
pdu: ModbusPDU = read_buffer.read_complex(
read_function=ModbusPDU.static_parse,
@@ -144,9 +139,8 @@ class ModbusTcpADU(ModbusADU):
driver_type=driver_type,
response=response,
)
-
+
read_buffer.pop_context("ModbusTcpADU")
- print(f"Exiting ModbusTcpADU static_parse_builder()")
# Create the instance
return ModbusTcpADUBuilder(transaction_identifier, unit_identifier, pdu)
diff --git a/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_connection.py b/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_connection.py
index 8a4111a03c..da50875489 100644
--- a/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_connection.py
+++ b/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_connection.py
@@ -36,21 +36,19 @@ async def manual_test_plc_driver_modbus_connect():
@pytest.mark.asyncio
-async def manual_test_plc_driver_modbus_read():
+async def test_plc_driver_modbus_read():
+ log = logging.getLogger(__name__)
- connection_string = "modbus://127.0.0.1:5020"
driver_manager = PlcDriverManager()
- response = None
-
- async def communicate_with_plc():
- async with driver_manager.connection(connection_string) as connection:
- with connection.read_request_builder() as builder:
- builder.add_item("Random Tag", "4x00001[10]")
- request = builder.build()
+ async with driver_manager.connection("modbus://192.168.1.177:502") as connection:
+ with connection.read_request_builder() as builder:
+ builder.add_item("Random Tag", "4x00001[10]")
+ request = builder.build()
future = connection.execute(request)
await future
response = future.result()
+ value = response.tags["Random Tag"].value
+ log.error(f"Read tag 4x00001[10] - {value}")
- communicate_with_plc()
pass
diff --git a/plc4py/tests/unit/plc4py/drivers/umas/test_umas_connection.py b/plc4py/tests/unit/plc4py/drivers/umas/test_umas_connection.py
index b99c28d88e..e3da81be0a 100644
--- a/plc4py/tests/unit/plc4py/drivers/umas/test_umas_connection.py
+++ b/plc4py/tests/unit/plc4py/drivers/umas/test_umas_connection.py
@@ -34,7 +34,7 @@ async def manual_test_plc_driver_umas_connect():
@pytest.mark.asyncio
-async def manual_test_plc_driver_umas_read():
+async def test_plc_driver_umas_read():
log = logging.getLogger(__name__)
driver_manager = PlcDriverManager()