-
Notifications
You must be signed in to change notification settings - Fork 951
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a487a8c
commit a1f0cad
Showing
7 changed files
with
485 additions
and
41 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
import logging | ||
|
||
from pymodbus.framer.rtu_framer import ModbusRtuFramer | ||
from pymodbus.utilities import checkCRC | ||
import struct | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
|
||
class PatchedModbusRtuFramer(ModbusRtuFramer): | ||
def isFrameIntendedForUs(self, units: list[int]): | ||
try: | ||
unit = self._buffer[0] | ||
return unit in units | ||
except IndexError as e: | ||
return True | ||
|
||
def advanceToNextOccurrenceOfUnit(self, units: list[int]): | ||
j = None | ||
for i, b in enumerate(self._buffer): | ||
if b in units and i > 0: | ||
j = i | ||
break | ||
|
||
if j: | ||
self._buffer = self._buffer[j:] | ||
else: | ||
self._buffer = b"" | ||
|
||
self._header = {"uid": 0x00, "len": 0, "crc": b"\x00\x00"} | ||
return len(self._buffer) | ||
|
||
def checkFrame(self): | ||
try: | ||
self.populateHeader() | ||
frame_size = self._header["len"] | ||
|
||
if len(self._buffer) > frame_size: | ||
# This means there are bytes *after* a valid frame intended to us. | ||
# If there are bytes after that means we've probably de-sychronized | ||
# and the master has considered us as having timed out and moved on. | ||
# That or there is somehow a random sequence of bytes which looks like | ||
# a real command to us and magically a crc. | ||
# In either case, we must not respond. | ||
return False | ||
|
||
data = self._buffer[: frame_size - 2] | ||
crc = self._header["crc"] | ||
crc_val = (int(crc[0]) << 8) + int(crc[1]) | ||
return checkCRC(data, crc_val) | ||
except (IndexError, KeyError, struct.error): | ||
return False | ||
|
||
def processIncomingPacket(self, data, callback, unit, **kwargs): | ||
if not isinstance(unit, (list, tuple)): | ||
unit = [unit] | ||
self.addToFrame(data) | ||
single = kwargs.get("single", False) | ||
while True: | ||
if not self.isFrameIntendedForUs(unit): | ||
if self.advanceToNextOccurrenceOfUnit(unit) == 0: | ||
log.info(f"❌ Frame - [{data}] not intended for us, ignoring!!") | ||
break | ||
elif self.isFrameReady(): | ||
if self.checkFrame(): | ||
if self._validate_unit_id(unit, single): | ||
self._process(callback) | ||
log.info(f"✅ Frame - [{data}] responded to!!") | ||
else: | ||
header_txt = self._header["uid"] | ||
log.info(f"Not a valid unit id - {header_txt}, ignoring!!") | ||
self.resetFrame() | ||
break | ||
else: | ||
log.info("Frame check failed, ignoring!!") | ||
if self.advanceToNextOccurrenceOfUnit(unit) == 0: | ||
break | ||
else: | ||
log.info(f"Frame - [{data}] not ready") | ||
break |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
import logging | ||
import struct | ||
|
||
from pymodbus.framer.rtu_framer import ModbusRtuFramer | ||
from pymodbus.utilities import checkCRC | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
|
||
class PatchedModbusRtuFramer(ModbusRtuFramer): | ||
def isFrameIntendedForUs(self, units: list[int]): | ||
try: | ||
# Always validate that the unit id and function code | ||
unit = self._buffer[0] | ||
fc = self._buffer[1] | ||
|
||
valid_unit_id = unit in units | ||
valid_function_code = fc in [2, 1, 5, 15, 4, 3, 6, 16, 43] | ||
|
||
if fc in [15, 16]: | ||
# These commands will have arbitrary payload lengths | ||
# Further validation is beneficial | ||
n_registers = int.from_bytes(self._buffer[4:6], byteorder="big") | ||
n_bytes = self._buffer[6] | ||
|
||
expected_number_of_bytes = n_registers * 2 | ||
|
||
valid_number_of_registers = n_registers <= 123 | ||
valid_number_of_bytes = n_bytes == expected_number_of_bytes | ||
return ( | ||
valid_unit_id | ||
and valid_function_code | ||
and valid_number_of_registers | ||
and valid_number_of_bytes | ||
) | ||
return valid_unit_id and valid_function_code | ||
|
||
except IndexError as e: | ||
return True | ||
|
||
def advanceToNextOccurrenceOfUnit(self, units: list[int]): | ||
j = None | ||
for i, b in enumerate(self._buffer): | ||
if b in units and i > 0: | ||
j = i | ||
break | ||
|
||
if j: | ||
log.debug("⏭") | ||
self._buffer = self._buffer[j:] | ||
else: | ||
log.debug("🗑") | ||
self._buffer = b"" | ||
|
||
self._header = {"uid": 0x00, "len": 0, "crc": b"\x00\x00"} | ||
return len(self._buffer) | ||
|
||
def checkFrame(self): | ||
try: | ||
self.populateHeader() | ||
frame_size = self._header["len"] | ||
|
||
if len(self._buffer) > frame_size: | ||
# This means there are bytes *after* a valid frame intended to us. | ||
# If there are bytes after that means we've probably de-sychronized | ||
# and the master has considered us as having timed out and moved on. | ||
# That or there is somehow a random sequence of bytes which looks like | ||
# a real command to us and magically a crc. | ||
# In either case, we must not respond. | ||
return False | ||
|
||
data = self._buffer[: frame_size - 2] | ||
crc = self._header["crc"] | ||
crc_val = (int(crc[0]) << 8) + int(crc[1]) | ||
return checkCRC(data, crc_val) | ||
except (IndexError, KeyError, struct.error): | ||
return False | ||
|
||
def processIncomingPacket(self, data, callback, unit, **kwargs): | ||
log.debug(f"🌟 {data.hex(':')}") | ||
if not isinstance(unit, (list, tuple)): | ||
unit = [unit] | ||
self.addToFrame(data) | ||
single = kwargs.get("single", False) | ||
while True: | ||
log.debug(f"🧪 {self._buffer.hex(':')}") | ||
if not self.isFrameIntendedForUs(unit): | ||
if self.advanceToNextOccurrenceOfUnit(unit) == 0: | ||
break | ||
elif self.isFrameReady(): | ||
if self.checkFrame(): | ||
if self._validate_unit_id(unit, single): | ||
log.debug(f"✅ {self._buffer.hex(':')}") | ||
self._process(callback) | ||
else: | ||
self.resetFrame() | ||
break | ||
else: | ||
log.debug("Frame check failed, ignoring!!") | ||
if self.advanceToNextOccurrenceOfUnit(unit) == 0: | ||
break | ||
else: | ||
log.debug(f"⌛ {self._buffer.hex(':')}") | ||
break |
Oops, something went wrong.