Skip to content

Commit b187401

Browse files
committed
ASCII framer using message decode() (#2128)
1 parent a824775 commit b187401

File tree

11 files changed

+19
-34
lines changed

11 files changed

+19
-34
lines changed

pymodbus/framer/ascii_framer.py

Lines changed: 13 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Ascii_framer."""
22
# pylint: disable=missing-type-doc
3-
from binascii import a2b_hex
43

54
from pymodbus.exceptions import ModbusIOException
65
from pymodbus.framer.base import BYTE_ORDER, FRAME_HEADER, ModbusFramer
@@ -52,44 +51,24 @@ def decode_data(self, data):
5251

5352
def frameProcessIncomingPacket(self, single, callback, slave, _tid=None, **kwargs):
5453
"""Process new packet pattern."""
55-
def check_frame(self):
56-
"""Check and decode the next frame."""
57-
start = self._buffer.find(self._start)
58-
if start == -1:
59-
return False
60-
if start > 0: # go ahead and skip old bad data
61-
self._buffer = self._buffer[start:]
62-
start = 0
63-
64-
if (end := self._buffer.find(self._end)) != -1:
65-
self._header["len"] = end
66-
self._header["uid"] = int(self._buffer[1:3], 16)
67-
self._header["lrc"] = int(self._buffer[end - 2 : end], 16)
68-
data = a2b_hex(self._buffer[start + 1 : end - 2])
69-
return MessageAscii.check_LRC(data, self._header["lrc"])
70-
return False
71-
72-
while len(self._buffer) > 1:
73-
if not check_frame(self):
74-
break
54+
while len(self._buffer):
55+
used_len, _tid, dev_id, data = self.message_handler.decode(self._buffer)
56+
if not data:
57+
if not used_len:
58+
return
59+
self._buffer = self._buffer[used_len :]
60+
continue
61+
self._header["uid"] = dev_id
7562
if not self._validate_slave_id(slave, single):
76-
header_txt = self._header["uid"]
77-
Log.error("Not a valid slave id - {}, ignoring!!", header_txt)
63+
Log.error("Not a valid slave id - {}, ignoring!!", dev_id)
7864
self.resetFrame()
79-
continue
65+
return
8066

81-
start = self._hsize + 1
82-
end = self._header["len"] - 2
83-
buffer = self._buffer[start:end]
84-
if end > 0:
85-
frame = a2b_hex(buffer)
86-
else:
87-
frame = b""
88-
if (result := self.decoder.decode(frame)) is None:
67+
if (result := self.decoder.decode(data)) is None:
8968
raise ModbusIOException("Unable to decode response")
9069
self.populateResult(result)
91-
self._buffer = self._buffer[self._header["len"] + 2 :]
92-
self._header = {"lrc": "0000", "len": 0, "uid": 0x00}
70+
self._buffer = self._buffer[used_len :]
71+
self._header = {"uid": 0x00}
9372
callback(result) # defer this
9473

9574
def buildPacket(self, message):
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)