Add support for string addresses to IECAddress class.

This commit is contained in:
2026-11-13 14:55:07 -06:00
parent de0d46bf29
commit 1ba83bdc56

View File

@@ -33,22 +33,33 @@ class AddressLength(StrEnum):
X = auto() # Explicit bit
class StringParity(StrEnum):
H = auto()
L = auto()
class Address:
"""Class for manipulating IEC 61131-3 and Modbus addresses."""
# Constants
IEC_PATTERN = (
r"^\s*" # Leading whitespace
r"%?([ikmsq])([dwx]?)" # Prefix
r"(\d{1,5})" # Register number
r"(?:\.(\d{0,2}))?" # Bit rank (optional)
r"%?([ikmsq])" # Capturing group 1: register type
r"([dwx]?)" # Capturing group 2: variable length
r"(\d{1,5})" # Capturing group 3: register number
r"(?:\.(\d{0,2}))?" # Capturing group 4: Bit rank
r"\s*$" # Trailing whitespace
)
MODBUS_PATTERN = (
r"^\s*" # Leading whitespace
r"(\d{1,6})" # Register number
r"(?:\.(\d{1,2}))?" # Bit rank (optional)
r"(\d{1,6})" # Capturing group 1: Register number
r"(?:" # Begin non-capturing group
r"\.(\d{1,2})" # Capturing group 2: Bit rank
r"|" # or
r"\.(\d+)" # Capturing group 3: String length
r"([hl])" # Capturing group 4: String parity
r")?" # End non-capturing group
r"\s*$" # Trailing whitespace
)
@@ -59,6 +70,8 @@ class Address:
address_length: AddressLength | str | None = AddressLength.W,
word: float | str = 0,
bit: float | str | None = None,
string_length: int | str = 0,
string_parity: StringParity | str = StringParity.L,
):
"""Initialize an IEC address object.
@@ -74,14 +87,22 @@ class Address:
AddressLength.W.
word : float | str
The word part of the address number. An integer, float, or
string that one of the former. If a floatDefault 0.
string that converts to one of the former. Default 0.
bit : int | str | None
The bit part of the address number. None or empty string for
addresses with no bit part; integer or a string that converts to an
integer for addresses that do have a bit part. Default None.
string_length: int | str
If this address is to be used for a string, the length of that
string in bytes. Default 0.
string_parity: StringParity | str
The byte order of the string. "H" for high; "L" for low. Not case-
sensitive. Default StringParity.L ("L").
"""
class_name = self.__class__.__name__
if isinstance(address_type, str):
if isinstance(address_type, AddressType):
self.address_type = address_type
else:
try:
self.address_type = AddressType.__members__[
address_type.upper()
@@ -90,8 +111,6 @@ class Address:
raise InvalidSpecError(
class_name, f"address type: {address_type.upper()}"
)
else:
self.address_type = address_type
if isinstance(address_length, str):
try:
self.address_length = (
@@ -131,6 +150,8 @@ class Address:
f"inclusive.",
)
self.bit = bit_int
self.string_length = int(string_length)
self.string_parity = string_parity
def __add__(self, other: Address | float) -> Address:
return self._combine(other, operator.add)
@@ -171,7 +192,12 @@ class Address:
# Constructors
@classmethod
def from_string(cls, spec: str) -> Address:
def from_string(
cls,
spec: str,
string_length: int | str = 0,
string_parity: StringParity | str = StringParity.L,
) -> Address:
"""Create an Address object based on a string representation of an IEC
address.
"""
@@ -183,7 +209,11 @@ class Address:
match = None
if match is None:
raise InvalidSpecError(cls.__class__.__name__, spec)
return cls(*match.groups())
return cls(
*match.groups(),
string_length=string_length,
string_parity=string_parity,
)
@classmethod
def from_modbus(
@@ -250,7 +280,14 @@ class Address:
str(spec),
"Modbus addresses must start with 0, 1, 3, or 4.",
)
return cls(address_type, address_length, word, bit)
return cls(
address_type,
address_length,
word,
bit,
string_length=match.group(3),
string_parity=match.group(4),
)
# Other class methods
@classmethod
@@ -264,15 +301,23 @@ class Address:
)
@classmethod
def iec_to_modbus(cls, iec_address: str, digits: int = 6) -> str:
def iec_to_modbus(
cls,
iec_address: str,
digits: int = 6,
string_length: int | str = 0,
string_parity: StringParity | str = StringParity.L,
) -> str:
"""Convert an address from IEC to Modbus without raising an error."""
try:
return cls.from_string(iec_address).to_modbus(digits)
# InvalidSpecError is raised if `value` is not an IEC address
return cls.from_string(
iec_address, string_length, string_parity
).to_modbus(digits)
# InvalidSpecError is raised if `iec_address` is not an IEC address
# (most likely it's already Modbus), so return it as-is.
except InvalidSpecError:
return iec_address
# ValueError is raised if `value` is blank.
# ValueError is raised if `iec_address` is blank.
except ValueError:
return ""
@@ -339,10 +384,9 @@ class Address:
f"This IEC address does not correspond to a valid "
f"Modbus address: %{self}."
)
return "".join(
(
first_digit,
f"{self.word:0{digits - 1}d}",
f".{self.bit:02d}" if self.bit is not None else "",
)
)
parts = [first_digit, f"{self.word:0{digits - 1}d}"]
if self.bit is not None:
parts.append(f".{self.bit:02d}")
elif self.string_length > 0:
parts.append(f".{self.string_length}{self.string_parity}")
return "".join(parts)