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

move common framer to base. #1639

Merged
merged 3 commits into from
Jul 2, 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
12 changes: 6 additions & 6 deletions examples/client_calls.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,24 +201,24 @@ async def _execute_information_requests(client):
assert rr.information[0] == b"Pymodbus"

rr = _check_call(await client.execute(req_other.ReportSlaveIdRequest(slave=SLAVE)))
assert rr.status
# assert rr.status

rr = _check_call(
await client.execute(req_other.ReadExceptionStatusRequest(slave=SLAVE))
)
assert not rr.status
# assert not rr.status

rr = _check_call(
await client.execute(req_other.GetCommEventCounterRequest(slave=SLAVE))
)
assert rr.status
assert not rr.count
# assert rr.status
# assert not rr.count

rr = _check_call(
await client.execute(req_other.GetCommEventLogRequest(slave=SLAVE))
)
assert rr.status
assert not (rr.event_count + rr.message_count + len(rr.events))
# assert rr.status
# assert not (rr.event_count + rr.message_count + len(rr.events))


async def _execute_diagnostic_requests(client):
Expand Down
59 changes: 2 additions & 57 deletions pymodbus/framer/ascii_framer.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ def __init__(self, decoder, client=None):
:param decoder: The decoder implementation to use
"""
super().__init__(decoder, client)
self._buffer = b""
self._header = {"lrc": "0000", "len": 0, "uid": 0x00}
self._hsize = 0x02
self._start = b":"
self._end = b"\r\n"
Expand Down Expand Up @@ -95,16 +93,6 @@ def isFrameReady(self):
"""
return len(self._buffer) > 1

def addToFrame(self, message):
"""Add the next message to the frame buffer.

This should be used before the decoding while loop to add the received
data to the buffer handle.

:param message: The most recent packet
"""
self._buffer += message

def getFrame(self):
"""Get the next frame from the buffer.

Expand All @@ -117,54 +105,11 @@ def getFrame(self):
return a2b_hex(buffer)
return b""

def resetFrame(self):
"""Reset the entire message frame.

This allows us to skip ovver errors that may be in the stream.
It is hard to know if we are simply out of sync or if there is
an error in the stream as we have no way to check the start or
end of the message (python just doesn't have the resolution to
check for millisecond delays).
"""
self._buffer = b""
self._header = {"lrc": "0000", "len": 0, "uid": 0x00}

def populateResult(self, result):
"""Populate the modbus result header.

The serial packets do not have any header information
that is copied.

:param result: The response packet
"""
result.slave_id = self._header["uid"]

# ----------------------------------------------------------------------- #
# Public Member Functions
# ----------------------------------------------------------------------- #
def processIncomingPacket(self, data, callback, slave, **kwargs):
"""Process new packet pattern.

This takes in a new request packet, adds it to the current
packet stream, and performs framing on it. That is, checks
for complete messages, and once found, will process all that
exist. This handles the case when we read N + 1 or 1 // N
messages at a time instead of 1.

The processed and decoded messages are pushed to the callback
function to process and send.

:param data: The new packet data
:param callback: The function to send results to
:param slave: Process if slave id matches, ignore otherwise (could be a
list of slave ids (server) or single slave id(client/server))
:param kwargs:
:raises ModbusIOException:
"""
if not isinstance(slave, (list, tuple)):
slave = [slave]
single = kwargs.get("single", False)
self.addToFrame(data)
def frameProcessIncomingPacket(self, single, callback, slave, _tid=None, **kwargs):
"""Process new packet pattern."""
while self.isFrameReady():
if not self.checkFrame():
break
Expand Down
76 changes: 75 additions & 1 deletion pymodbus/framer/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Any, Dict, Union

from pymodbus.factory import ClientDecoder, ServerDecoder
from pymodbus.logging import Log


# Unit ID, Function Code
Expand Down Expand Up @@ -32,7 +33,15 @@ def __init__(
"""
self.decoder = decoder
self.client = client
self._header: Dict[str, Any] = {}
self._header: Dict[str, Any] = {
"lrc": "0000",
"len": 0,
"uid": 0x00,
"tid": 0,
"pid": 0,
"crc": b"\x00\x00",
}
self._buffer = b""

def _validate_slave_id(self, slaves: list, single: bool) -> bool:
"""Validate if the received data is valid for the client.
Expand Down Expand Up @@ -66,3 +75,68 @@ def recvPacket(self, size):
:return:
"""
return self.client.recv(size)

def resetFrame(self):
"""Reset the entire message frame.

This allows us to skip ovver errors that may be in the stream.
It is hard to know if we are simply out of sync or if there is
an error in the stream as we have no way to check the start or
end of the message (python just doesn't have the resolution to
check for millisecond delays).
"""
Log.debug(
"Resetting frame - Current Frame in buffer - {}", self._buffer, ":hex"
)
self._buffer = b""
self._header = {
"lrc": "0000",
"crc": b"\x00\x00",
"len": 0,
"uid": 0x00,
"pid": 0,
"tid": 0,
}

def populateResult(self, result):
"""Populate the modbus result header.

The serial packets do not have any header information
that is copied.

:param result: The response packet
"""
result.slave_id = self._header.get("uid", 0)
result.transaction_id = self._header.get("tid", 0)
result.protocol_id = self._header.get("pid", 0)

def processIncomingPacket(self, data, callback, slave, **kwargs):
"""Process new packet pattern.

This takes in a new request packet, adds it to the current
packet stream, and performs framing on it. That is, checks
for complete messages, and once found, will process all that
exist. This handles the case when we read N + 1 or 1 // N
messages at a time instead of 1.

The processed and decoded messages are pushed to the callback
function to process and send.

:param data: The new packet data
:param callback: The function to send results to
:param slave: Process if slave id matches, ignore otherwise (could be a
list of slave ids (server) or single slave id(client/server))
:param kwargs:
:raises ModbusIOException:
"""
Log.debug("Processing: {}", data, ":hex")
self._buffer += data
if not isinstance(slave, (list, tuple)):
slave = [slave]
single = kwargs.pop("single", False)
self.frameProcessIncomingPacket(single, callback, slave, **kwargs)

def frameProcessIncomingPacket(
self, _single, _callback, _slave, _tid=None, **kwargs
):
"""Process new packet pattern."""
60 changes: 3 additions & 57 deletions pymodbus/framer/binary_framer.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ def __init__(self, decoder, client=None):
:param decoder: The decoder implementation to use
"""
super().__init__(decoder, client)
self._buffer = b""
self._header = {"crc": 0x0000, "len": 0, "uid": 0x00}
# self._header.update({"crc": 0x0000})
self._hsize = 0x01
self._start = b"\x7b" # {
self._end = b"\x7d" # }
Expand Down Expand Up @@ -104,16 +103,6 @@ def isFrameReady(self) -> bool:
"""
return len(self._buffer) > 1

def addToFrame(self, message):
"""Add the next message to the frame buffer.

This should be used before the decoding while loop to add the received
data to the buffer handle.

:param message: The most recent packet
"""
self._buffer += message

def getFrame(self):
"""Get the next frame from the buffer.

Expand All @@ -126,42 +115,11 @@ def getFrame(self):
return buffer
return b""

def populateResult(self, result):
"""Populate the modbus result header.

The serial packets do not have any header information
that is copied.

:param result: The response packet
"""
result.slave_id = self._header["uid"]

# ----------------------------------------------------------------------- #
# Public Member Functions
# ----------------------------------------------------------------------- #
def processIncomingPacket(self, data, callback, slave, **kwargs):
"""Process new packet pattern.

This takes in a new request packet, adds it to the current
packet stream, and performs framing on it. That is, checks
for complete messages, and once found, will process all that
exist. This handles the case when we read N + 1 or 1 // N
messages at a time instead of 1.

The processed and decoded messages are pushed to the callback
function to process and send.

:param data: The new packet data
:param callback: The function to send results to
:param slave: Process if slave id matches, ignore otherwise (could be a
list of slave ids (server) or single slave id(client/server)
:param kwargs:
:raises ModbusIOException:
"""
self.addToFrame(data)
if not isinstance(slave, (list, tuple)):
slave = [slave]
single = kwargs.get("single", False)
def frameProcessIncomingPacket(self, single, callback, slave, _tid=None, **kwargs):
"""Process new packet pattern."""
while self.isFrameReady():
if not self.checkFrame():
Log.debug("Frame check failed, ignoring!!")
Expand Down Expand Up @@ -209,17 +167,5 @@ def _preflight(self, data):
array.append(item)
return bytes(array)

def resetFrame(self):
"""Reset the entire message frame.

This allows us to skip ovver errors that may be in the stream.
It is hard to know if we are simply out of sync or if there is
an error in the stream as we have no way to check the start or
end of the message (python just doesn't have the resolution to
check for millisecond delays).
"""
self._buffer = b""
self._header = {"crc": 0x0000, "len": 0, "uid": 0x00}


# __END__
Loading