Split iec.py into submodules; add iec_address submodule.
This commit is contained in:
13
src/AuDaGe/iec/__init__.py
Normal file
13
src/AuDaGe/iec/__init__.py
Normal file
@@ -0,0 +1,13 @@
|
||||
"""
|
||||
AuDaGe IEC module init
|
||||
|
||||
name: __init__.py
|
||||
by: Josh Lucas
|
||||
date: 2026-10-14
|
||||
|
||||
desc: Definitions for IEC 61131 programming paradigms.
|
||||
"""
|
||||
|
||||
from .iec_address import *
|
||||
from .iec_common import *
|
||||
from .iec_type import *
|
||||
325
src/AuDaGe/iec/iec_address.py
Normal file
325
src/AuDaGe/iec/iec_address.py
Normal file
@@ -0,0 +1,325 @@
|
||||
"""
|
||||
AuDaGe IEC Address submodule
|
||||
|
||||
name: iec.py
|
||||
by: Josh Lucas
|
||||
date: 2026-10-14
|
||||
|
||||
desc: Definitions for IEC 61131 address paradigms.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import operator
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from enum import StrEnum, auto
|
||||
|
||||
from .iec_common import *
|
||||
|
||||
MAX_ADDRESS = 65535
|
||||
|
||||
|
||||
class AddressType(StrEnum):
|
||||
I = auto() # Input
|
||||
K = auto() # Module?
|
||||
M = auto() # Memory
|
||||
Q = auto() # Output
|
||||
S = auto() # System
|
||||
|
||||
|
||||
class AddressLength(StrEnum):
|
||||
D = auto() # Double word
|
||||
W = auto() # Word
|
||||
X = auto() # Explicit bit
|
||||
|
||||
|
||||
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"\s*$" # Trailing whitespace
|
||||
)
|
||||
|
||||
MODBUS_PATTERN = (
|
||||
r"^\s*" # Leading whitespace
|
||||
r"(\d{1,6})" # Register number
|
||||
r"(?:\.(\d{1,2}))?" # Bit rank (optional)
|
||||
r"\s*$" # Trailing whitespace
|
||||
)
|
||||
|
||||
# Dunder methods
|
||||
def __init__(
|
||||
self,
|
||||
address_type: AddressType | str = AddressType.M,
|
||||
address_length: AddressLength | str | None = AddressLength.W,
|
||||
word: float | str = 0,
|
||||
bit: int | str | None = None,
|
||||
):
|
||||
"""Initialize an IEC address object.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
address_type : AddressType | str
|
||||
The type of IEC address. A member of AddressType or a string
|
||||
corresponding to the name of one of the members. Default
|
||||
AddressType.M.
|
||||
address_length : AddressLength | str | None
|
||||
The length of the IEC address memory location. None or X for
|
||||
one-bit-length locations, W for word, or D for double word. Default
|
||||
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.
|
||||
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.
|
||||
"""
|
||||
class_name = self.__class__.__name__
|
||||
if isinstance(address_type, str):
|
||||
try:
|
||||
self.address_type = AddressType.__members__[
|
||||
address_type.upper()
|
||||
]
|
||||
except KeyError:
|
||||
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 = (
|
||||
AddressLength.__members__[address_length.upper()]
|
||||
if address_length
|
||||
else None
|
||||
)
|
||||
except KeyError:
|
||||
raise InvalidSpecError(
|
||||
class_name, f"address length: {address_length.upper()}"
|
||||
)
|
||||
else:
|
||||
self.address_length = address_length
|
||||
try:
|
||||
bit_int = int(bit)
|
||||
except TypeError, ValueError:
|
||||
bit_int = None
|
||||
word_float = float(word)
|
||||
if word_float % 1 != 0 and bit_int is not None:
|
||||
bit_int = int(word_float % 1 * 100)
|
||||
word_int = int(word_float)
|
||||
if word_int not in range(MAX_ADDRESS + 1):
|
||||
raise InvalidSpecError(
|
||||
class_name,
|
||||
f"address word: {word_int}",
|
||||
f"Address word must be between 0 and {MAX_ADDRESS}, inclusive.",
|
||||
)
|
||||
self.word = word_int
|
||||
if bit_int is not None and bit_int not in range(DataUnit.WORD):
|
||||
raise InvalidSpecError(
|
||||
class_name,
|
||||
f"address bit: {bit}",
|
||||
f"Address bit must be between 0 and {DataUnit.WORD - 1}, "
|
||||
f"inclusive.",
|
||||
)
|
||||
self.bit = bit_int
|
||||
|
||||
def __add__(self, other: Address | float) -> Address:
|
||||
return self._combine(other, operator.add)
|
||||
|
||||
def __eq__(self, other: any) -> bool:
|
||||
try:
|
||||
return all(
|
||||
self.__dict__[name] == other.__dict__[name]
|
||||
for name in self.__dict__
|
||||
)
|
||||
except KeyError:
|
||||
return False
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.to_string()
|
||||
|
||||
def __sub__(self, other: Address | float) -> Address:
|
||||
return self._combine(other, operator.sub)
|
||||
|
||||
# Private methods
|
||||
def _combine(self, other: Address | float, operator: Callable) -> Address:
|
||||
"""Common operations for adding and subtracting addresses."""
|
||||
address = copy.copy(self)
|
||||
if isinstance(other, Address):
|
||||
bit_add = other.bit
|
||||
word_add = other.word
|
||||
else:
|
||||
word_add = other // 1
|
||||
bit_add = (other % 1) * 100
|
||||
if address.bit is None:
|
||||
carry = 0
|
||||
else:
|
||||
(carry, address.bit) = divmod(
|
||||
operator(address.bit, bit_add), DataUnit.WORD
|
||||
)
|
||||
address.word = operator(address.word, word_add + carry)
|
||||
return address
|
||||
|
||||
# Constructors
|
||||
@classmethod
|
||||
def from_string(cls, spec: str) -> Address:
|
||||
"""Create an Address object based on a string representation of an IEC
|
||||
address.
|
||||
"""
|
||||
if isinstance(spec, Address):
|
||||
return spec
|
||||
try:
|
||||
match = re.match(cls.IEC_PATTERN, spec, flags=re.IGNORECASE)
|
||||
except TypeError:
|
||||
match = None
|
||||
print(spec)
|
||||
if match is None:
|
||||
raise InvalidSpecError(cls.__class__.__name__, spec)
|
||||
return cls(*match.groups())
|
||||
|
||||
@classmethod
|
||||
def from_modbus(
|
||||
cls, spec: str | float, digits: int = 5, explicit_bit: bool = False
|
||||
) -> Address:
|
||||
"""Create an Address object based on a Modbus address.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
spec : str | float
|
||||
Modbus address.
|
||||
digits : int
|
||||
Number of digits in the Modbus address format. Any spec with fewer
|
||||
digits than this is assumed to have implied leading zeroes and
|
||||
therefore be a 0x address. Note that this only affects the
|
||||
interpretation of addresses with fewer than this number of digits.
|
||||
Addresses with more than this number of digits are still interpreted
|
||||
correctly. Default 5.
|
||||
explicit_bit : bool
|
||||
Whether to use the 'X' indication of a bit-length IEC address.
|
||||
Default False.
|
||||
"""
|
||||
class_name = cls.__class__.__name__
|
||||
# Parse the Modbus address into word and bit parts.
|
||||
if isinstance(spec, str):
|
||||
match = re.match(cls.MODBUS_PATTERN, spec)
|
||||
if match is None:
|
||||
raise InvalidSpecError(class_name, spec)
|
||||
word_init = match.group(1)
|
||||
bit_init = match.group(2)
|
||||
else:
|
||||
word_init = str(spec // 1)
|
||||
bit_init = None if isinstance(spec, int) else (spec % 1) * 100
|
||||
# Determine the address type and length.
|
||||
if len(word_init) < digits or word_init.startswith("0"):
|
||||
address_type = AddressType.M
|
||||
address_length = AddressLength.X if explicit_bit else None
|
||||
word = word_init
|
||||
bit = None
|
||||
else:
|
||||
word = word_init[1:]
|
||||
bit = bit_init
|
||||
match word_init[0]:
|
||||
case "1":
|
||||
address_type = AddressType.I
|
||||
address_length = AddressLength.X if explicit_bit else None
|
||||
case "3":
|
||||
address_type = AddressType.I
|
||||
address_length = (
|
||||
AddressLength.X
|
||||
if (bit and explicit_bit)
|
||||
else AddressLength.W
|
||||
)
|
||||
case "4":
|
||||
address_type = AddressType.M
|
||||
address_length = (
|
||||
AddressLength.X
|
||||
if (bit and explicit_bit)
|
||||
else AddressLength.W
|
||||
)
|
||||
case _:
|
||||
raise InvalidSpecError(
|
||||
class_name,
|
||||
spec,
|
||||
"Modbus addresses must start with 0, 1, 3, or 4.",
|
||||
)
|
||||
return cls(address_type, address_length, word, bit)
|
||||
|
||||
# Other class methods
|
||||
@classmethod
|
||||
def is_iec(cls, spec: str) -> bool:
|
||||
return re.match(cls.IEC_PATTERN, spec, flags=re.IGNORECASE) is not None
|
||||
|
||||
@classmethod
|
||||
def is_modbus(cls, spec: str) -> bool:
|
||||
return (
|
||||
re.match(cls.MODBUS_PATTERN, spec, flags=re.IGNORECASE) is not None
|
||||
)
|
||||
|
||||
# Instance methods
|
||||
def is_even(self) -> bool:
|
||||
return self.word % 2 == 0 and not self.bit
|
||||
|
||||
def to_string(self, digits: int = 0) -> str:
|
||||
"""Output a string representation of the IEC address. If `digits` is
|
||||
set, the output address will be padded with leading zeroes to acheive
|
||||
the specified number of digits.
|
||||
"""
|
||||
return "".join(
|
||||
(
|
||||
"%",
|
||||
self.address_type.name,
|
||||
self.address_length.name if self.address_length else "",
|
||||
f"{int(self.word):0{digits}d}",
|
||||
f".{int(self.bit):02d}" if self.bit or self.bit == 0 else "",
|
||||
)
|
||||
)
|
||||
|
||||
def to_modbus(self, digits: int = 6) -> str:
|
||||
"""Output the closest Modbus equivalent of the IEC address as a string.
|
||||
The parameter `digits` specifies the length of the output address
|
||||
(default 6). Shorter addresses will have leading zeroes added to achieve
|
||||
this length.
|
||||
"""
|
||||
if self.word >= 10 ** (digits - 1):
|
||||
raise ValueError(
|
||||
f"This IEC address ({self}) is too large to fit into a Modbus "
|
||||
f"address with the specified number of digits ({digits})."
|
||||
)
|
||||
if self.address_length is None:
|
||||
if self.address_type == AddressType.M:
|
||||
first_digit = "0"
|
||||
elif self.address_type == AddressType.I:
|
||||
first_digit = "1"
|
||||
else:
|
||||
raise ValueError(
|
||||
f"This IEC address does not correspond to a valid "
|
||||
f"Modbus address: {self}."
|
||||
)
|
||||
else:
|
||||
match (self.address_type, self.address_length):
|
||||
case (AddressType.M, AddressLength.X):
|
||||
first_digit = "0"
|
||||
case (AddressType.I, AddressLength.X):
|
||||
first_digit = "1"
|
||||
case (AddressType.I, AddressLength.W):
|
||||
first_digit = "3"
|
||||
case (AddressType.M, AddressLength.W):
|
||||
first_digit = "4"
|
||||
case _:
|
||||
raise ValueError(
|
||||
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 else "",
|
||||
)
|
||||
)
|
||||
64
src/AuDaGe/iec/iec_common.py
Normal file
64
src/AuDaGe/iec/iec_common.py
Normal file
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
AuDaGe IEC Common submodule
|
||||
|
||||
name: iec_common.py
|
||||
by: Josh Lucas
|
||||
date: 2026-10-14
|
||||
|
||||
desc: Shared definitions for IEC 61131 programming paradigms.
|
||||
"""
|
||||
|
||||
from enum import IntEnum
|
||||
|
||||
|
||||
class DataUnit(IntEnum):
|
||||
"""The length in bits of various data units."""
|
||||
|
||||
BIT = 1
|
||||
NIBBLE = 4
|
||||
BYTE = 8
|
||||
WORD = 16
|
||||
DWORD = 32
|
||||
QWORD = 64
|
||||
|
||||
|
||||
class DataUnitMismatchWarning(RuntimeWarning):
|
||||
"""The length of the data type is not evenly divisible by the selected
|
||||
unit.
|
||||
"""
|
||||
|
||||
DEFAULT_MESSAGE = (
|
||||
"Data length is not evenly divisible by the selected unit. The length "
|
||||
"will be rounded to the nearest unit by {round_function}()."
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self, message: str | None = None, round_function: str = "math.ceil"
|
||||
):
|
||||
self.message = self.DEFAULT_MESSAGE if message is None else message
|
||||
super().__init__(self.message.format(round_function=round_function))
|
||||
|
||||
|
||||
class InvalidSpecError(ValueError):
|
||||
"""Error to be raised when an invalid specification is provided to Array or
|
||||
String classes.
|
||||
|
||||
Inherits from ValueError and implements a default message.
|
||||
"""
|
||||
|
||||
DEFAULT_MESSAGE = (
|
||||
"The provided {source} specification ({spec}) is not valid."
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
source: str = "",
|
||||
spec: str = "",
|
||||
message: str = "",
|
||||
*args,
|
||||
**kwargs,
|
||||
):
|
||||
self.message = " ".join(
|
||||
(self.DEFAULT_MESSAGE.format(source=source, spec=spec), message)
|
||||
)
|
||||
super().__init__(self.message, *args, **kwargs)
|
||||
419
src/AuDaGe/iec/iec_type.py
Normal file
419
src/AuDaGe/iec/iec_type.py
Normal file
@@ -0,0 +1,419 @@
|
||||
"""
|
||||
AuDaGe IEC Type submodule
|
||||
|
||||
name: iec.py
|
||||
by: Josh Lucas
|
||||
date: 2026-10-14
|
||||
|
||||
desc: Definitions for IEC 61131 data type paradigms.
|
||||
"""
|
||||
|
||||
import re
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from enum import IntFlag, StrEnum, auto
|
||||
from math import ceil, prod
|
||||
|
||||
import pandas as pd
|
||||
from numpy import nan
|
||||
|
||||
from AuDaGe.better_enum import AliasEnum, AliasEnumType
|
||||
from AuDaGe.frame import AuDaGeFrame
|
||||
|
||||
from .iec_common import *
|
||||
|
||||
UNKNOWN_LENGTH = -1
|
||||
|
||||
type_iec_to_opcua = {
|
||||
"BOOL": "Boolean",
|
||||
"EBOOL": "Boolean",
|
||||
"BYTE": "Byte",
|
||||
"WORD": "Word",
|
||||
"DWORD": "DWord",
|
||||
"LWORD": "QWord",
|
||||
"SINT": "Char",
|
||||
"INT": "Short",
|
||||
"DINT": "Long",
|
||||
"LINT": "LongLong",
|
||||
"USINT": "Byte",
|
||||
"UINT": "Word",
|
||||
"UDINT": "DWord",
|
||||
"ULINT": "QWord",
|
||||
"REAL": "Float",
|
||||
"LREAL": "Double",
|
||||
"DATE": "DWord",
|
||||
"LDATE": "QWord",
|
||||
"DT": "DWord",
|
||||
"LDT": "QWord",
|
||||
"TIME": "DWord",
|
||||
"LTIME": "QWord",
|
||||
"TOD": "DWord",
|
||||
"LTOD": "QWord",
|
||||
"CHAR": "Char",
|
||||
"WCHAR": "Word",
|
||||
"STRING": "String",
|
||||
}
|
||||
|
||||
type_opcua_to_iec = {
|
||||
"Boolean": "BOOL",
|
||||
"Byte": "BYTE",
|
||||
"Word": "WORD",
|
||||
"DWord": "DWORD",
|
||||
"QWord": "LWORD",
|
||||
"Char": "CHAR",
|
||||
"Short": "INT",
|
||||
"Long": "DINT",
|
||||
"LongLong": "LINT",
|
||||
"Float": "REAL",
|
||||
"Double": "LREAL",
|
||||
"String": "STRING",
|
||||
}
|
||||
|
||||
|
||||
class IECClass(StrEnum):
|
||||
"""Classes of IEC 61131-3 data types."""
|
||||
|
||||
BINARY = auto()
|
||||
INTEGER = auto()
|
||||
REAL = auto()
|
||||
DATETIME = auto()
|
||||
CHAR = auto()
|
||||
ARRAY = auto()
|
||||
UDT = auto()
|
||||
|
||||
|
||||
class IECTypeFlag(IntFlag):
|
||||
BINARY = auto()
|
||||
INTEGER = auto()
|
||||
REAL = auto()
|
||||
DATE = auto()
|
||||
TIME = auto()
|
||||
DT = auto()
|
||||
TOD = auto()
|
||||
CHAR = auto()
|
||||
UDT = auto()
|
||||
BIT = auto() # 1-bit
|
||||
SHORT = auto() # 8-bit
|
||||
DOUBLE = auto() # 32-bit
|
||||
LONG = auto() # 64-bit
|
||||
STRING = auto()
|
||||
ARRAY = auto()
|
||||
|
||||
|
||||
class IECType:
|
||||
"""A representation of an IEC 61131-3 data type."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
iec_class: IECClass,
|
||||
length: int = 0,
|
||||
unit: DataUnit = DataUnit.BIT,
|
||||
round_function: Callable[[float], int] = ceil,
|
||||
):
|
||||
"""Initialize an object representing an IEC 61131-3 elementary data
|
||||
type.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
class : IECClass
|
||||
The class of the data type (BINARY, INTEGER, etc.).
|
||||
length : int
|
||||
The length of the data type in the corresponding unit. One of these
|
||||
must be provided. If several are provided, the first in the order
|
||||
above takes priority.
|
||||
unit : DataUnit
|
||||
The data unit to use to measure the length of the data type.
|
||||
Defaults to DataUnit.WORD.
|
||||
round_function : Callable[[float], int]
|
||||
The function to use to round the data length when it does not divide
|
||||
evenly by the selected unit. Defaults to math.ceil().
|
||||
"""
|
||||
self.name = name
|
||||
self.iec_class = iec_class
|
||||
self.round = round_function
|
||||
self.length_bits = length * unit
|
||||
self.length = self.get_length
|
||||
|
||||
def get_length(
|
||||
self, unit: DataUnit | int = DataUnit.BIT, silent: bool = False
|
||||
) -> int:
|
||||
"""Get the data length of the type in the specified unit."""
|
||||
if self.length_bits % unit != 0 and not silent:
|
||||
warnings.warn(None, category=DataUnitMismatchWarning)
|
||||
return int(self.round(self.length_bits / unit))
|
||||
|
||||
def set_length(self, value: int, unit: DataUnit = DataUnit.BIT):
|
||||
"""Set the data length of the type in the specified unit."""
|
||||
self.length_bits = value * unit
|
||||
|
||||
def from_opcua(self, spec: str):
|
||||
pass
|
||||
|
||||
def to_opcua(self) -> str:
|
||||
pass
|
||||
|
||||
|
||||
class MetaElementaryTypes(AliasEnumType):
|
||||
"""Override some of the EnumType methods so that they include aliases."""
|
||||
|
||||
def __contains__(cls, name: str) -> bool:
|
||||
"""The default Enum __contains__ method does not include aliases. This
|
||||
one does.
|
||||
"""
|
||||
return cls.contains(name, include_array=True, include_string=True)
|
||||
|
||||
def contains(
|
||||
cls, name: str, include_array: bool = True, include_string: bool = True
|
||||
) -> bool:
|
||||
"""Like __contains__ but provides options to include or exclude strings
|
||||
and arrays from elementary types.
|
||||
"""
|
||||
if name.upper() in cls.__members__:
|
||||
return True
|
||||
try:
|
||||
# If `name` is a valid array spec, return whether it is elementary
|
||||
# or not.
|
||||
return Array(name).is_elementary() and include_array
|
||||
except InvalidSpecError:
|
||||
pass
|
||||
try:
|
||||
String(name)
|
||||
# The return below is only reached if String does not raise
|
||||
# InvalidSpecError.
|
||||
return include_string
|
||||
except InvalidSpecError:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
# Disable Ruff warnings about duplicate values in this enum.
|
||||
class ElementaryTypes(AliasEnum, metaclass=MetaElementaryTypes):
|
||||
"""Dataclass of IEC 61131-3 elementary variable types."""
|
||||
|
||||
# Binary
|
||||
BOOL = IECType("BOOL", IECClass.BINARY, 1)
|
||||
EBOOL = IECType("EBOOL", IECClass.BINARY, 8)
|
||||
BYTE = IECType("BYTE", IECClass.BINARY, 8)
|
||||
WORD = IECType("WORD", IECClass.BINARY, 16)
|
||||
DWORD = IECType("DWORD", IECClass.BINARY, 32)
|
||||
LWORD = IECType("LWORD", IECClass.BINARY, 64)
|
||||
# Signed Integer
|
||||
SINT = IECType("SINT", IECClass.INTEGER, 8)
|
||||
INT = IECType("INT", IECClass.INTEGER, 16)
|
||||
DINT = IECType("DINT", IECClass.INTEGER, 32)
|
||||
LINT = IECType("LINT", IECClass.INTEGER, 64)
|
||||
# Unsigned Integer
|
||||
USINT = IECType("USINT", IECClass.INTEGER, 8)
|
||||
UINT = IECType("UINT", IECClass.INTEGER, 16)
|
||||
UDINT = IECType("UDINT", IECClass.INTEGER, 32)
|
||||
ULINT = IECType("ULINT", IECClass.INTEGER, 64)
|
||||
# Float
|
||||
REAL = IECType("REAL", IECClass.REAL, 32)
|
||||
LREAL = IECType("LREAL", IECClass.REAL, 64)
|
||||
# Date/Time
|
||||
DATE = IECType("DATE", IECClass.DATETIME, 32)
|
||||
LDATE = IECType("LDATE", IECClass.DATETIME, 64)
|
||||
DT = IECType("DT", IECClass.DATETIME, 32)
|
||||
LDT = IECType("LDT", IECClass.DATETIME, 64)
|
||||
TIME = IECType("TIME", IECClass.DATETIME, 32)
|
||||
LTIME = IECType("LTIME", IECClass.DATETIME, 64)
|
||||
TOD = IECType("TOD", IECClass.DATETIME, 32)
|
||||
LTOD = IECType("LTOD", IECClass.DATETIME, 64)
|
||||
# Character
|
||||
CHAR = IECType("CHAR", IECClass.CHAR, 8)
|
||||
WCHAR = IECType("WCHAR", IECClass.CHAR, 16)
|
||||
STRING = IECType("STRING", IECClass.CHAR, 128)
|
||||
|
||||
|
||||
# ruff: enable[PIE796]
|
||||
|
||||
|
||||
class Array(IECType):
|
||||
"""An IEC 61131-3 array data type variable."""
|
||||
|
||||
class ArraySpec:
|
||||
# Regular expression for parsing array specifications.
|
||||
SPEC_PATTERN = (
|
||||
# Array declaration: "arr(ay)" with variable whitespace before and
|
||||
# after.
|
||||
r"^\s*arr(?:ay)?\s*"
|
||||
# Bounds: for each dimension of the array, a pair of integers
|
||||
# separated by "..(.)", with each pair delimited by commas with
|
||||
# variable whitespace. All enclosed in square brackets.
|
||||
r"\[((?:\d+\s*\.{2,3}\s*\d+\s*,?\s*)+)\]"
|
||||
# Data type: optional "of" with whitespace, a word, and variable
|
||||
# whitespace at the end.
|
||||
r"\s*(?:of\s+)?(\w+)\s*$"
|
||||
)
|
||||
|
||||
# Regular expression that matches integers within the bounds section of
|
||||
# an array specification.
|
||||
BOUNDS_PATTERN = r"\d+"
|
||||
|
||||
def __init__(self, spec: str):
|
||||
class_name = self.__class__.__name__
|
||||
self.spec = spec
|
||||
match = re.match(self.SPEC_PATTERN, spec, re.IGNORECASE)
|
||||
# Check whether the regex matches at all.
|
||||
if match is None:
|
||||
raise InvalidSpecError(class_name, spec)
|
||||
self.type_name = match.group(2)
|
||||
all_bounds = re.findall(
|
||||
self.BOUNDS_PATTERN, match.group(1), re.IGNORECASE
|
||||
)
|
||||
# Group the bounds of the array into pairs.
|
||||
self.bounds = list(zip(all_bounds[::2], all_bounds[1::2]))
|
||||
# Check that each dimension's upper bound is greater than or equal
|
||||
# to its lower bound.
|
||||
try:
|
||||
for lbound, ubound in self.bounds:
|
||||
if int(lbound) > int(ubound):
|
||||
raise InvalidSpecError(
|
||||
class_name,
|
||||
spec,
|
||||
"The upper bound of at least one dimension is less "
|
||||
"than its lower bound.",
|
||||
)
|
||||
# ValueError is raised if the array bounds are not coercible to
|
||||
# integers.
|
||||
except ValueError:
|
||||
raise InvalidSpecError(
|
||||
class_name,
|
||||
spec,
|
||||
"At least one bound is not an integer.",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
spec: str,
|
||||
round_function: Callable[[float], int] = ceil,
|
||||
*args,
|
||||
**kwargs,
|
||||
):
|
||||
"""Create an instance of Array based on an IEC 61131-3 array
|
||||
specification as a string. For maximum compatibility should be of the
|
||||
form "ARRAY [{bounds}] OF {TYPE}" where m and n are integers, m < n,
|
||||
and TYPE is the name of an IEC 61131-3 data type. This function is
|
||||
tolerant of some variation in the formatting of this specification and
|
||||
is not case-sensitive.
|
||||
"""
|
||||
self.spec = self.ArraySpec(spec)
|
||||
if not self.is_elementary():
|
||||
length_bits = -1
|
||||
else:
|
||||
# Calculate the length of the array in bits.
|
||||
length_bits = (
|
||||
prod(
|
||||
(int(ubound) - int(lbound) + 1)
|
||||
for (lbound, ubound) in self.spec.bounds
|
||||
)
|
||||
* ElementaryTypes[self.spec.type_name.upper()].value.length_bits
|
||||
)
|
||||
super().__init__(
|
||||
spec,
|
||||
IECClass.ARRAY,
|
||||
length_bits,
|
||||
DataUnit.BIT,
|
||||
round_function,
|
||||
*args,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def is_elementary(self) -> bool:
|
||||
return self.spec.type_name in ElementaryTypes
|
||||
|
||||
def make_definition(self, name: str, comment: str = "") -> AuDaGeFrame:
|
||||
dimensions = [
|
||||
int(ubound) - int(lbound) + 1
|
||||
for (lbound, ubound) in self.spec.bounds
|
||||
]
|
||||
length = prod(dimensions)
|
||||
all_indices = None
|
||||
for i, (lbound, ubound) in enumerate(self.spec.bounds):
|
||||
dim_indices = pd.Series(
|
||||
range(int(lbound), int(ubound) + 1), name=f"dim{i}"
|
||||
)
|
||||
if all_indices is None:
|
||||
all_indices = pd.DataFrame(dim_indices)
|
||||
continue
|
||||
all_indices = all_indices.join(dim_indices, how="cross")
|
||||
columns = {}
|
||||
columns["name"] = pd.Series(
|
||||
all_indices.apply(
|
||||
lambda row: f"{name}[{','.join(str(dim) for dim in row)}]",
|
||||
axis=1,
|
||||
),
|
||||
name="name",
|
||||
)
|
||||
columns["parent"] = pd.Series(
|
||||
[self.spec.spec.upper()] * length, name="parent"
|
||||
)
|
||||
columns["type"] = pd.Series([self.spec.type_name] * length, name="type")
|
||||
columns["address"] = pd.Series(
|
||||
[nan] * length,
|
||||
name="address",
|
||||
)
|
||||
columns["comment"] = pd.Series([comment] * length, name="comment")
|
||||
return AuDaGeFrame(columns)
|
||||
|
||||
|
||||
class String(IECType):
|
||||
"""An IEC 61131-3 string data type variable."""
|
||||
|
||||
STRING_SPEC_PATTERN = r"^\s*str(?:ing)?\s*\[(\d+)\]\s*$"
|
||||
|
||||
def __init__(self, spec: str, *args, **kwargs):
|
||||
"""Create an instance of String based on an IEC 61131-3 string
|
||||
specification as a string. For maximum compatibility should be of the
|
||||
form "STRING [{n}]" where n is an integer. This function is tolerant of
|
||||
some variation in the formatting of this specification and is not
|
||||
case-sensitive.
|
||||
"""
|
||||
class_name = self.__class__.__name__
|
||||
match = re.match(self.STRING_SPEC_PATTERN, spec, re.IGNORECASE)
|
||||
try:
|
||||
length_bytes = int(match.group(1))
|
||||
if length_bytes <= 0:
|
||||
raise InvalidSpecError(
|
||||
class_name,
|
||||
spec,
|
||||
"The string length must be greater than zero.",
|
||||
)
|
||||
except AttributeError, ValueError:
|
||||
raise InvalidSpecError(class_name, spec)
|
||||
super().__init__(
|
||||
spec, IECClass.CHAR, length_bytes, DataUnit.BYTE, *args, **kwargs
|
||||
)
|
||||
|
||||
|
||||
def get_data_length(
|
||||
type_name: str,
|
||||
unit: DataUnit = DataUnit.BIT,
|
||||
udt_lengths: dict[str, int] | None = None,
|
||||
round_function: Callable[[float], int] = ceil,
|
||||
unknown_length: any = UNKNOWN_LENGTH,
|
||||
) -> any:
|
||||
"""Get the length of the specified data type as measured in the specified
|
||||
unit. Returns the value specified by `unknown_length` (default -1) if the
|
||||
data type is unknown.
|
||||
"""
|
||||
try:
|
||||
return udt_lengths[type_name] // unit
|
||||
# TypeError is raised if udt_lengths is None; KeyError is raised if
|
||||
# `type_name` does not exist in udt_lengths.
|
||||
except TypeError, KeyError:
|
||||
pass
|
||||
try:
|
||||
return ElementaryTypes[type_name].value.get_length(unit)
|
||||
except KeyError:
|
||||
pass
|
||||
try:
|
||||
return Array(type_name).get_length(unit)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
return String(type_name).get_length(unit)
|
||||
except ValueError:
|
||||
pass
|
||||
return unknown_length
|
||||
@@ -10,11 +10,9 @@ desc: Unit tests for the AuDaGe IEC module.
|
||||
|
||||
import unittest
|
||||
import warnings
|
||||
from importlib import resources
|
||||
from importlib import resources # noqa: F401
|
||||
from math import ceil, floor
|
||||
|
||||
import output
|
||||
|
||||
from AuDaGe.iec import *
|
||||
|
||||
|
||||
@@ -49,6 +47,200 @@ class TestIEC(unittest.TestCase):
|
||||
)
|
||||
|
||||
|
||||
class TestAddress(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.good_specs = (
|
||||
(
|
||||
"%MW300.04",
|
||||
(AddressType.M, AddressLength.W, 300, 4),
|
||||
"%MW300.04",
|
||||
"%MW00300.04",
|
||||
"400300.04",
|
||||
),
|
||||
(
|
||||
"%MW300.4",
|
||||
(AddressType.M, AddressLength.W, 300, 4),
|
||||
"%MW300.04",
|
||||
"%MW00300.04",
|
||||
"400300.04",
|
||||
),
|
||||
(
|
||||
"%IW65535.15",
|
||||
(AddressType.I, AddressLength.W, 65535, 15),
|
||||
"%IW65535.15",
|
||||
"%IW65535.15",
|
||||
"365535.15",
|
||||
),
|
||||
(
|
||||
"%I12345",
|
||||
(AddressType.I, None, 12345, None),
|
||||
"%I12345",
|
||||
"%I12345",
|
||||
"112345",
|
||||
),
|
||||
(
|
||||
"%M6440",
|
||||
(AddressType.M, None, 6440, None),
|
||||
"%M6440",
|
||||
"%M06440",
|
||||
"006440",
|
||||
),
|
||||
(
|
||||
"%IX12345",
|
||||
(AddressType.I, AddressLength.X, 12345, None),
|
||||
"%IX12345",
|
||||
"%IX12345",
|
||||
"112345",
|
||||
),
|
||||
(
|
||||
"%MX6440",
|
||||
(AddressType.M, AddressLength.X, 6440, None),
|
||||
"%MX6440",
|
||||
"%MX06440",
|
||||
"006440",
|
||||
),
|
||||
)
|
||||
# Semi-good specs are valid IEC but not Modbus addresses.
|
||||
self.semi_good_specs = (
|
||||
("q03", (AddressType.Q, None, 3, None), "%Q3", "%Q00003"),
|
||||
(
|
||||
"%QW7676.12",
|
||||
(AddressType.Q, AddressLength.W, 7676, 12),
|
||||
"%QW7676.12",
|
||||
"%QW07676.12",
|
||||
),
|
||||
(
|
||||
"%kd0",
|
||||
(AddressType.K, AddressLength.D, 0, None),
|
||||
"%KD0",
|
||||
"%KD00000",
|
||||
),
|
||||
(
|
||||
"%sw751",
|
||||
(AddressType.S, AddressLength.W, 751, None),
|
||||
"%SW751",
|
||||
"%SW00751",
|
||||
),
|
||||
(
|
||||
"%s323",
|
||||
(AddressType.S, None, 323, None),
|
||||
"%S323",
|
||||
"%S00323",
|
||||
),
|
||||
)
|
||||
self.bad_specs = (
|
||||
"goobledygook",
|
||||
"%n300.4",
|
||||
"40012.3",
|
||||
"%M70000",
|
||||
"%sw1000.17",
|
||||
"%QF10",
|
||||
)
|
||||
self.bad_args = (("n", None, 300, 4), ("Q", "F", 10, None))
|
||||
self.good_modbus = (
|
||||
(
|
||||
"400001",
|
||||
6,
|
||||
False,
|
||||
(AddressType.M, AddressLength.W, 1, None),
|
||||
),
|
||||
(
|
||||
400001,
|
||||
6,
|
||||
False,
|
||||
(AddressType.M, AddressLength.W, 1, None),
|
||||
),
|
||||
(
|
||||
"400001",
|
||||
5,
|
||||
False,
|
||||
(AddressType.M, AddressLength.W, 1, None),
|
||||
),
|
||||
(
|
||||
"40001",
|
||||
5,
|
||||
False,
|
||||
(AddressType.M, AddressLength.W, 1, None),
|
||||
),
|
||||
(
|
||||
"40001",
|
||||
6,
|
||||
False,
|
||||
(AddressType.M, None, 40001, None),
|
||||
),
|
||||
(
|
||||
"40001",
|
||||
6,
|
||||
True,
|
||||
(AddressType.M, AddressLength.X, 40001, None),
|
||||
),
|
||||
("000012", 6, False, (AddressType.M, None, 12, None)),
|
||||
("12", 6, False, (AddressType.M, None, 12, None)),
|
||||
("12", 6, True, (AddressType.M, AddressLength.X, 12, None)),
|
||||
("100000", 6, False, (AddressType.I, None, 0, None)),
|
||||
(
|
||||
"100000",
|
||||
6,
|
||||
True,
|
||||
(AddressType.I, AddressLength.X, 0, None),
|
||||
),
|
||||
(
|
||||
"300123",
|
||||
6,
|
||||
False,
|
||||
(AddressType.I, AddressLength.W, 123, None),
|
||||
),
|
||||
)
|
||||
self.bad_modbus = ("200000", "goobledygook", 600000)
|
||||
|
||||
def test_eq(self):
|
||||
"""Test that the __eq__ method returns False for non-Address `other`."""
|
||||
self.assertNotEqual(
|
||||
Address(*self.good_specs[0][1]), IECType("test", IECClass.BINARY)
|
||||
)
|
||||
|
||||
def test_init(self):
|
||||
for args in self.bad_args:
|
||||
with self.assertRaises(InvalidSpecError, msg=args):
|
||||
Address(*args)
|
||||
|
||||
def test_from_string(self):
|
||||
for spec in self.good_specs + self.semi_good_specs:
|
||||
self.assertEqual(
|
||||
Address.from_string(spec[0]), Address(*spec[1]), spec[0]
|
||||
)
|
||||
for spec in self.bad_specs:
|
||||
with self.assertRaises(InvalidSpecError, msg=spec):
|
||||
Address.from_string(spec)
|
||||
|
||||
def test_from_modbus(self):
|
||||
for spec in self.good_modbus:
|
||||
self.assertEqual(
|
||||
Address.from_modbus(spec[0], spec[1], spec[2]),
|
||||
Address(*spec[3]),
|
||||
)
|
||||
for spec in self.bad_modbus:
|
||||
with self.assertRaises(InvalidSpecError, msg=spec):
|
||||
Address.from_modbus(spec)
|
||||
|
||||
def test_to_string(self):
|
||||
for spec in self.good_specs:
|
||||
self.assertEqual(str(Address(*spec[1])), spec[2], spec[0])
|
||||
self.assertEqual(Address(*spec[1]).to_string(5), spec[3], spec[0])
|
||||
|
||||
def test_to_modbus(self):
|
||||
for spec in self.good_specs:
|
||||
self.assertEqual(Address(*spec[1]).to_modbus(6), spec[4], spec[0])
|
||||
for spec in self.semi_good_specs:
|
||||
with self.assertRaises(ValueError, msg=spec[0]):
|
||||
Address(*spec[1]).to_modbus()
|
||||
# Test whether to_modbus errors when the address is to large to fit in
|
||||
# the specified number of digits.
|
||||
self.assertRaises(
|
||||
ValueError, Address(*self.good_specs[2][1]).to_modbus, 5
|
||||
)
|
||||
|
||||
|
||||
class TestIECType(unittest.TestCase):
|
||||
def test_set_length(self):
|
||||
test_type = IECType(
|
||||
@@ -125,7 +317,8 @@ class TestArray(unittest.TestCase):
|
||||
spec[1],
|
||||
)
|
||||
for spec in self.error_array_specs:
|
||||
self.assertRaises(InvalidSpecError, Array, spec)
|
||||
with self.assertRaises(InvalidSpecError, msg=spec):
|
||||
Array(spec)
|
||||
|
||||
def test_get_length(self):
|
||||
"""Test get_length for both good and warning array specs."""
|
||||
@@ -143,12 +336,12 @@ class TestArray(unittest.TestCase):
|
||||
warnings.simplefilter("ignore")
|
||||
for spec in self.good_array_specs + self.warning_array_specs:
|
||||
array = Array(spec[0])
|
||||
definition = array.make_definition("test_name", "test_comment")
|
||||
definition.to_csv(
|
||||
resources.files(output).joinpath(
|
||||
f"array_definition_{str.strip(spec[0])}.csv"
|
||||
)
|
||||
)
|
||||
definition = array.make_definition("test_name", "test_comment") # noqa: F841
|
||||
# definition.to_csv(
|
||||
# resources.files(output).joinpath(
|
||||
# f"array_definition_{str.strip(spec[0])}.csv"
|
||||
# )
|
||||
# )
|
||||
|
||||
|
||||
class TestString(unittest.TestCase):
|
||||
@@ -182,7 +375,8 @@ class TestString(unittest.TestCase):
|
||||
RuntimeWarning, String(spec[0], spec[2]).get_length, spec[1]
|
||||
)
|
||||
for spec in error_string_specs:
|
||||
self.assertRaises(InvalidSpecError, String, spec[0])
|
||||
with self.assertRaises(InvalidSpecError, msg=spec[0]):
|
||||
String(spec[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user