Major IEC module refactor.
This commit is contained in:
@@ -11,13 +11,15 @@ desc: Definitions for IEC 61131 programming paradigms.
|
||||
import re
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from enum import Enum, EnumType, IntEnum
|
||||
from enum import Enum, EnumType, IntEnum, IntFlag, StrEnum, auto
|
||||
from math import ceil, prod
|
||||
|
||||
from pandas import NA, Series
|
||||
import pandas as pd
|
||||
|
||||
from AuDaGe.audage_frame import AuDaGeFrame
|
||||
|
||||
UNKNOWN_LENGTH = -1
|
||||
|
||||
|
||||
class DataUnit(IntEnum):
|
||||
"""The length in bits of various data units."""
|
||||
@@ -30,378 +32,408 @@ class DataUnit(IntEnum):
|
||||
QWORD = 64
|
||||
|
||||
|
||||
class IECType:
|
||||
"""A representation of an IEC 61131-3 data type."""
|
||||
class IECClass(StrEnum):
|
||||
"""Classes of IEC 61131-3 data types."""
|
||||
|
||||
_length_bits: int
|
||||
_length_bytes: int
|
||||
_length_words: int
|
||||
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 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,
|
||||
length_bits: int | None = None,
|
||||
length_bytes: int | None = None,
|
||||
length_words: int | None = None,
|
||||
word_length: int = DataUnit.WORD,
|
||||
source: str = "",
|
||||
message: str = "",
|
||||
spec: str = "",
|
||||
*args,
|
||||
**kwargs,
|
||||
):
|
||||
self.message = " ".join(
|
||||
(self.DEFAULT_MESSAGE.format(source=source, spec=spec), message)
|
||||
)
|
||||
super().__init__(self.message, *args, **kwargs)
|
||||
|
||||
|
||||
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 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.
|
||||
"""Initialize an object representing an IEC 61131-3 elementary data
|
||||
type.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
length_bits, length_bytes, length_words: int
|
||||
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.
|
||||
word_length: int
|
||||
The length of a word in the target controller architecture. Defaults
|
||||
to 16.
|
||||
round_function: Callable[[float], int]
|
||||
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.word_length = word_length
|
||||
self.name = name
|
||||
self.iec_class = iec_class
|
||||
self.round = round_function
|
||||
if length_bits is not None:
|
||||
self.length_bits = length_bits
|
||||
elif length_bytes is not None:
|
||||
self.length_bytes = length_bytes
|
||||
elif length_words is not None:
|
||||
self.length_words = length_words
|
||||
else:
|
||||
raise ValueError(
|
||||
"At least one of length_bits, length_bytes, or length_words "
|
||||
"must be provided."
|
||||
)
|
||||
self.length_bits = length * unit
|
||||
self.length = self.get_length
|
||||
|
||||
def get_length(self, unit: DataUnit | int = DataUnit.WORD) -> int:
|
||||
def get_length(
|
||||
self, unit: DataUnit | int = DataUnit.BIT, silent: bool = False
|
||||
) -> int:
|
||||
"""Get the data length of the type in the specified unit."""
|
||||
match unit:
|
||||
case DataUnit.BIT:
|
||||
return self.length_bits
|
||||
case DataUnit.BYTE:
|
||||
return self.length_bytes
|
||||
case DataUnit.WORD:
|
||||
return self.length_words
|
||||
case _:
|
||||
raise ValueError("Invalid data 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."""
|
||||
match unit:
|
||||
case DataUnit.BIT:
|
||||
self.length_bits = value
|
||||
case DataUnit.BYTE:
|
||||
self.length_bytes = value
|
||||
case DataUnit.WORD:
|
||||
self.length_words = value
|
||||
case _:
|
||||
raise ValueError("Invalid data unit.")
|
||||
|
||||
@property
|
||||
def length_bits(self) -> int:
|
||||
"""The length of the data type in bits."""
|
||||
return self._length_bits
|
||||
|
||||
@length_bits.setter
|
||||
def length_bits(self, value: int):
|
||||
"""Set the length of the data type in bits."""
|
||||
self._length_bits = value
|
||||
self._length_bytes = self.round(value / DataUnit.BYTE)
|
||||
self._length_words = self.round(value / self.word_length)
|
||||
|
||||
@property
|
||||
def length_bytes(self) -> int:
|
||||
"""The length of the data type in bytes."""
|
||||
return self._length_bytes
|
||||
|
||||
@length_bytes.setter
|
||||
def length_bytes(self, value: int):
|
||||
"""Set the length of the data type in bytes."""
|
||||
self._length_bits = value * DataUnit.BYTE
|
||||
self._length_bytes = value
|
||||
self._length_words = self.round(value * DataUnit.BYTE / self.word_length)
|
||||
|
||||
@property
|
||||
def length_words(self) -> int:
|
||||
"""The length of the data type in words."""
|
||||
return self._length_words
|
||||
|
||||
@length_words.setter
|
||||
def length_words(self, value: int):
|
||||
"""Set the length of the data type in words."""
|
||||
self._length_bits = value * self.word_length
|
||||
self._length_bytes = self.round(value * self.word_length / DataUnit.BYTE)
|
||||
self._length_words = value
|
||||
self.length_bits = value * unit
|
||||
|
||||
|
||||
class AliasEnumType(EnumType):
|
||||
class MetaElementaryTypes(EnumType):
|
||||
"""Override some of the EnumType methods so that they include aliases."""
|
||||
|
||||
def __contains__(cls, member):
|
||||
def __contains__(cls, name: str):
|
||||
"""The default Enum __contains__ method does not include aliases. This
|
||||
one does.
|
||||
"""
|
||||
return member in cls.__members__
|
||||
return cls.contains(name, include_array=True, include_string=True)
|
||||
|
||||
def __getitem__(cls, name):
|
||||
return cls.__members__[name.upper()]
|
||||
|
||||
def __iter__(cls):
|
||||
return cls.__members__
|
||||
"""The default Enum __iter__ method does not include aliases. This
|
||||
one does.
|
||||
"""
|
||||
return iter(cls.__members__)
|
||||
|
||||
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.
|
||||
# ruff: disable[PIE796]
|
||||
class IECTypes(Enum, metaclass=AliasEnumType):
|
||||
class ElementaryTypes(Enum, metaclass=MetaElementaryTypes):
|
||||
"""Dataclass of IEC 61131-3 elementary variable types."""
|
||||
|
||||
# Binary
|
||||
BOOL = IECType(1)
|
||||
BYTE = IECType(8)
|
||||
WORD = IECType(16)
|
||||
DWORD = IECType(32)
|
||||
LWORD = IECType(64)
|
||||
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(8)
|
||||
INT = IECType(16)
|
||||
DINT = IECType(32)
|
||||
LINT = IECType(64)
|
||||
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(8)
|
||||
UINT = IECType(16)
|
||||
UDINT = IECType(32)
|
||||
ULINT = IECType(64)
|
||||
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(32)
|
||||
LREAL = IECType(64)
|
||||
REAL = IECType("REAL", IECClass.REAL, 32)
|
||||
LREAL = IECType("LREAL", IECClass.REAL, 64)
|
||||
# Date/Time
|
||||
DATE = IECType(32)
|
||||
LDATE = IECType(64)
|
||||
DT = IECType(32)
|
||||
LDT = IECType(64)
|
||||
TIME = IECType(32)
|
||||
LTIME = IECType(64)
|
||||
TOD = IECType(32)
|
||||
LTOD = IECType(64)
|
||||
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(8)
|
||||
WCHAR = IECType(16)
|
||||
CHAR = IECType("CHAR", IECClass.CHAR, 8)
|
||||
WCHAR = IECType("WCHAR", IECClass.CHAR, 16)
|
||||
STRING = IECType("STRING", IECClass.CHAR, 128)
|
||||
|
||||
|
||||
# ruff: enable[PIE796]
|
||||
|
||||
|
||||
class IECArray(IECType):
|
||||
class Array(IECType):
|
||||
"""An IEC 61131-3 array data type variable."""
|
||||
|
||||
BOUNDS_PATTERN = r"\d+"
|
||||
ARRAY_SPEC_PATTERN = (
|
||||
r"^\s*arr(?:ay)?\s*\[((?:\d+\s*\.{2,3}\s*\d+\s*,?\s*)+)\]\s*(?:of\s+)?(\w+)\s*$"
|
||||
)
|
||||
|
||||
def __init__(self, spec: str, *args, **kwargs):
|
||||
"""Create an instance of IECArray based on an IEC 61131-3 array
|
||||
specification as a string. For maximum compatibility should be of the
|
||||
form "ARRAY [{m}..{n}] 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.
|
||||
"""
|
||||
if not self.is_valid(spec):
|
||||
raise ValueError("The provided array specification is not valid.")
|
||||
self.spec = spec
|
||||
super().__init__(0, *args, **kwargs)
|
||||
self.length_bits = self.get_length(DataUnit.BIT)
|
||||
|
||||
def get_length(
|
||||
self,
|
||||
unit: DataUnit | int = DataUnit.WORD,
|
||||
round_function: Callable[[float], int] | None = None,
|
||||
) -> int:
|
||||
"""Return the length of an IEC 61131-3 array defined by array_spec as
|
||||
measured in the data unit specified by unit.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
(Optional) unit (DataUnit | int): data unit to measure the array
|
||||
length in. Defaults to DataUnit.WORD (16 bits).
|
||||
(Optional) round_function (Callable): function to use to round the
|
||||
array length if it is not divisible by the length of {unit}.
|
||||
Defaults to math.ceil().
|
||||
|
||||
Output
|
||||
------
|
||||
(int): the length of the specified array in words.
|
||||
"""
|
||||
if round_function is None:
|
||||
round_function = self.round
|
||||
# Validate the array specification.
|
||||
match = re.match(self.ARRAY_SPEC_PATTERN, self.spec, re.IGNORECASE)
|
||||
bounds = re.findall(self.BOUNDS_PATTERN, match.groups()[0], re.IGNORECASE)
|
||||
# Parse the array specification.
|
||||
data_type = match.groups()[-1].upper()
|
||||
# Calculate the length of the array in bits.
|
||||
length_bits = (
|
||||
prod(
|
||||
(int(ubound) - int(lbound) + 1)
|
||||
for (lbound, ubound) in zip(bounds[::2], bounds[1::2])
|
||||
)
|
||||
* IECTypes[data_type].value.length_bits
|
||||
class ArraySpec:
|
||||
# Regular expression for parsing array specifications.
|
||||
ARRAY_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*$"
|
||||
)
|
||||
if length_bits % unit != 0:
|
||||
warnings.warn(
|
||||
f"Array length is not divisible by the selected unit. The "
|
||||
f"length will be rounded to the nearest unit by "
|
||||
f"{round_function.__name__}().",
|
||||
category=RuntimeWarning,
|
||||
)
|
||||
length_units = int(round_function(length_bits / unit))
|
||||
else:
|
||||
length_units = length_bits // unit
|
||||
return length_units
|
||||
|
||||
def is_valid(self, array_spec: str | None = None) -> bool:
|
||||
"""Check whether the given IEC 61131-3 array specification is valid.
|
||||
For maximum compatibility, array_spec should be a string or regular
|
||||
expression Match object of the form "ARRAY [{m}..{n}] 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.
|
||||
"""
|
||||
if array_spec is None:
|
||||
array_spec = self.spec
|
||||
match = re.match(self.ARRAY_SPEC_PATTERN, array_spec, re.IGNORECASE)
|
||||
# Check whether the regex matches at all.
|
||||
if match is None:
|
||||
return False
|
||||
bounds = re.findall(self.BOUNDS_PATTERN, match.groups()[0], re.IGNORECASE)
|
||||
# Check whether the data type is valid.
|
||||
if not match.groups()[-1].upper() in IECTypes:
|
||||
return False
|
||||
try:
|
||||
# Regular expression that matches integers within the bounds section of
|
||||
# an array specification.
|
||||
BOUNDS_PATTERN = r"\d+"
|
||||
|
||||
def __init__(self, spec: str):
|
||||
class_name = "Array" # self.__class__.__name__
|
||||
self.spec = spec
|
||||
match = re.match(self.ARRAY_SPEC_PATTERN, spec, re.IGNORECASE)
|
||||
# Check whether the regex matches at all.
|
||||
if match is None:
|
||||
raise InvalidSpecError(class_name, spec=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.
|
||||
for lbound, ubound in zip(bounds[::2], bounds[1::2]):
|
||||
if int(lbound) > int(ubound):
|
||||
return False
|
||||
# ValueError is raised if the array bounds are not coercible to integers.
|
||||
except ValueError:
|
||||
return False
|
||||
# Return True if all the tests succeeded.
|
||||
return True
|
||||
try:
|
||||
for lbound, ubound in self.bounds:
|
||||
if int(lbound) > int(ubound):
|
||||
raise InvalidSpecError(
|
||||
class_name,
|
||||
"The upper bound of at least one dimension is less "
|
||||
"than its lower bound.",
|
||||
spec,
|
||||
)
|
||||
# ValueError is raised if the array bounds are not coercible to
|
||||
# integers.
|
||||
except ValueError:
|
||||
raise InvalidSpecError(
|
||||
class_name, "At least one bound is not an integer.", spec
|
||||
)
|
||||
|
||||
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].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)
|
||||
data_length = get_data_length(self.spec.type_name)
|
||||
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(
|
||||
range(0, length * data_length, data_length), name="address"
|
||||
)
|
||||
columns["comment"] = pd.Series([comment] * length, name="comment")
|
||||
return AuDaGeFrame(columns)
|
||||
|
||||
|
||||
class IECString(IECType):
|
||||
class String(IECType):
|
||||
"""An IEC 61131-3 string data type variable."""
|
||||
|
||||
STRING_SPEC_PATTERN = r"^\s*str(?:ing)? *\[(\d+)\]\s*$"
|
||||
STRING_SPEC_PATTERN = r"^\s*str(?:ing)?\s*\[(\d+)\]\s*$"
|
||||
|
||||
def __init__(self, spec: str, *args, **kwargs):
|
||||
"""Create an instance of IECString based on an IEC 61131-3 string
|
||||
"""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.
|
||||
"""
|
||||
if not self.is_valid(spec):
|
||||
raise ValueError("The provided string specification is not valid.")
|
||||
self.spec = spec
|
||||
super().__init__(0, *args, **kwargs)
|
||||
self.length_bits = self.get_length(DataUnit.BIT)
|
||||
|
||||
def get_length(
|
||||
self,
|
||||
unit: DataUnit | int = DataUnit.WORD,
|
||||
round_function: Callable[[float], int] | None = None,
|
||||
) -> int:
|
||||
"""Return the length of an IEC 61131-3 string defined by string_spec as
|
||||
measured in the data unit specified by unit.
|
||||
|
||||
Input:
|
||||
(Optional) unit (DataUnit | int): data unit to measure the string
|
||||
length in. Defaults to DataUnit.WORD (16 bits).
|
||||
(Optional) round_function (Callable): function to use to round the
|
||||
string length if it is not divisible by the length of {unit}.
|
||||
Defaults to math.ceil().
|
||||
|
||||
Output:
|
||||
(int): the length of the specified array in words.
|
||||
"""
|
||||
if round_function is None:
|
||||
round_function = self.round
|
||||
m = re.match(self.STRING_SPEC_PATTERN, self.spec, re.IGNORECASE)
|
||||
class_name = self.__class__.__name__
|
||||
match = re.match(self.STRING_SPEC_PATTERN, spec, re.IGNORECASE)
|
||||
try:
|
||||
# 1 ASCII character == 1 byte.
|
||||
length_bits = int(m.groups()[0]) * DataUnit.BYTE
|
||||
length_bytes = int(match.group(1))
|
||||
if length_bytes <= 0:
|
||||
raise InvalidSpecError(
|
||||
class_name,
|
||||
"The string length must be greater than zero.",
|
||||
spec,
|
||||
)
|
||||
except (AttributeError, ValueError):
|
||||
raise ValueError("The provided string specification is invalid.")
|
||||
if length_bits % unit != 0:
|
||||
warnings.warn(
|
||||
f"Array length is not divisible by the selected unit. The "
|
||||
f"length will be rounded to the nearest unit by "
|
||||
f"{round_function.__name__}().",
|
||||
category=RuntimeWarning,
|
||||
)
|
||||
return round_function(length_bits / unit)
|
||||
|
||||
def is_valid(self, spec: str | None = None):
|
||||
if spec is None:
|
||||
spec = self.spec
|
||||
m = re.match(self.STRING_SPEC_PATTERN, spec, re.IGNORECASE)
|
||||
try:
|
||||
int(m.groups()[0])
|
||||
except (AttributeError, ValueError):
|
||||
return False
|
||||
return True
|
||||
raise InvalidSpecError(class_name, spec=spec)
|
||||
super().__init__(
|
||||
spec, IECClass.CHAR, length_bytes, DataUnit.BYTE, *args, **kwargs
|
||||
)
|
||||
|
||||
|
||||
class UDT(IECType):
|
||||
"""An IEC 61131-3 User-defined Data Type."""
|
||||
# class IECVariable:
|
||||
# """"""
|
||||
|
||||
def get_length(self, unit: DataUnit | int = DataUnit.WORD) -> int:
|
||||
pass
|
||||
# def __init__(
|
||||
# self, name: str, type_name: IECType | str, address: str, comment: str
|
||||
# ):
|
||||
# self.name = name
|
||||
# self.address = address
|
||||
# self.comment = comment
|
||||
# if isinstance(type_name, IECType):
|
||||
# self.type_name = type_name
|
||||
# else:
|
||||
# self.type_name = IECType(type_name)
|
||||
|
||||
|
||||
def get_data_length(
|
||||
data_type: str,
|
||||
unit: DataUnit = DataUnit.WORD,
|
||||
type_name: str,
|
||||
unit: DataUnit = DataUnit.BIT,
|
||||
udt_lengths: dict[str, int] | None = None,
|
||||
) -> int:
|
||||
"""Get the length of the specified data type as measured in the
|
||||
specified unit. Returns -1 if the data type is unknown.
|
||||
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.
|
||||
"""
|
||||
if udt_lengths is None:
|
||||
udt_lengths = {}
|
||||
try:
|
||||
return IECTypes[data_type].value.get_length(unit)
|
||||
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
|
||||
if data_type.lower().startswith("arr"):
|
||||
try:
|
||||
return IECArray(data_type).get_length(unit)
|
||||
except ValueError:
|
||||
pass
|
||||
if data_type.lower().startswith("str"):
|
||||
try:
|
||||
return IECString(data_type).get_length(unit)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
return udt_lengths[data_type] * DataUnit.WORD // unit
|
||||
except KeyError:
|
||||
return Array(type_name).get_length(unit)
|
||||
except ValueError:
|
||||
pass
|
||||
return -1
|
||||
|
||||
|
||||
def iec_definitions() -> AuDaGeFrame:
|
||||
"""Generate a DataFrame containing the standard IEC 61131-3 data types."""
|
||||
empty = Series([NA] * len(IECTypes))
|
||||
return AuDaGeFrame(
|
||||
{
|
||||
"name": empty,
|
||||
"parent": empty,
|
||||
"type": IECTypes,
|
||||
"address": empty,
|
||||
"bitrank": empty,
|
||||
"save": empty,
|
||||
"comment": empty,
|
||||
}
|
||||
)
|
||||
try:
|
||||
return String(type_name).get_length(unit)
|
||||
except ValueError:
|
||||
pass
|
||||
return unknown_length
|
||||
|
||||
@@ -10,81 +10,148 @@ desc: Unit tests for the AuDaGe IEC module.
|
||||
|
||||
import unittest
|
||||
import warnings
|
||||
from importlib import resources
|
||||
from math import ceil, floor
|
||||
|
||||
import output
|
||||
|
||||
from AuDaGe.iec import *
|
||||
|
||||
|
||||
class TestIEC(unittest.TestCase):
|
||||
"""Module-level tests."""
|
||||
|
||||
def test_get_data_length(self):
|
||||
data_types = [
|
||||
def setUp(self):
|
||||
self.elementary_data_types = [
|
||||
("BOOL", DataUnit.BIT, 1),
|
||||
("CHAR", DataUnit.BIT, 8),
|
||||
("INT", DataUnit.BIT, 16),
|
||||
("BOOL", DataUnit.WORD, 1),
|
||||
("ARRAY [1..10, 0..7] OF INT", DataUnit.WORD, 80),
|
||||
("STRING[10]", DataUnit.WORD, 5),
|
||||
("UNKNOWN_UDT", DataUnit.WORD, -1),
|
||||
]
|
||||
for data_type in data_types:
|
||||
self.udts = [
|
||||
("KNOWN_UDT", DataUnit.WORD, 10),
|
||||
("UNKNOWN_UDT", DataUnit.WORD, UNKNOWN_LENGTH),
|
||||
]
|
||||
self.udt_lengths = {"KNOWN_UDT": 160}
|
||||
|
||||
def test_get_data_length(self):
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
for data_type in self.elementary_data_types + self.udts:
|
||||
self.assertEqual(
|
||||
get_data_length(
|
||||
data_type[0], data_type[1], self.udt_lengths
|
||||
),
|
||||
data_type[2],
|
||||
data_type[0],
|
||||
)
|
||||
|
||||
|
||||
class TestIECType(unittest.TestCase):
|
||||
def test_set_length(self):
|
||||
test_type = IECType(
|
||||
"WORD", IECClass.BINARY, length=16, unit=DataUnit.BIT
|
||||
)
|
||||
self.assertEqual(test_type.get_length(DataUnit.WORD), 1)
|
||||
test_type.set_length(4, unit=DataUnit.BYTE)
|
||||
self.assertEqual(test_type.get_length(DataUnit.BIT), 32)
|
||||
|
||||
|
||||
class TestElementaryTypes(unittest.TestCase):
|
||||
def test_iter(self):
|
||||
count = 0
|
||||
for data_type in ElementaryTypes:
|
||||
count += 1
|
||||
self.assertNotEqual(count, 0)
|
||||
self.assertEqual(count, len(ElementaryTypes.__members__))
|
||||
|
||||
def test_contains(self):
|
||||
valid_types = [
|
||||
("bool", True),
|
||||
("INT", True),
|
||||
("STRING[20]", False),
|
||||
("string", True),
|
||||
("array [0..5] of int", False),
|
||||
]
|
||||
invalid_types = ["float", "UDT", "ARRAY [0..5] OF UDT"]
|
||||
for data_type in valid_types:
|
||||
# Test that all the valid_types return True for a permissive check.
|
||||
self.assertTrue(data_type[0] in ElementaryTypes, data_type)
|
||||
# Test that derived types return False for a strict check.
|
||||
self.assertEqual(
|
||||
get_data_length(data_type[0], data_type[1]), data_type[2], data_type[0]
|
||||
ElementaryTypes.contains(
|
||||
data_type[0], include_string=False, include_array=False
|
||||
),
|
||||
data_type[1],
|
||||
)
|
||||
|
||||
def test_iec_definitions(self):
|
||||
definitions = iec_definitions()
|
||||
self.assertTrue(definitions.is_valid())
|
||||
self.assertEqual(definitions.shape, (len(IECTypes.__members__), 7))
|
||||
for data_type in invalid_types:
|
||||
self.assertFalse(data_type in ElementaryTypes, data_type)
|
||||
|
||||
|
||||
class TestIECArray(unittest.TestCase):
|
||||
def test_array_length(self):
|
||||
good_array_specs = [
|
||||
class TestArray(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.good_array_specs = [
|
||||
("ARRAY [0..3] OF INT", DataUnit.WORD, ceil, 4),
|
||||
("ARRAY [0..0] OF REAL", DataUnit.WORD, ceil, 2),
|
||||
("ARRAY [0..3, 0..3] OF INT", DataUnit.WORD, ceil, 16),
|
||||
("array[15..20] of bool", DataUnit.BIT, ceil, 6),
|
||||
("ARRAY [0..1, 0..2, 0..3, 0..4] OF INT", DataUnit.WORD, ceil, 120),
|
||||
("arr[0..0]int", DataUnit.BYTE, ceil, 2),
|
||||
("ARRAY [0..3] OF UDT", DataUnit.BIT, ceil, -1),
|
||||
]
|
||||
warning_array_specs = [
|
||||
("array[15..20] of bool", DataUnit.WORD, ceil, 1),
|
||||
("array[15..20] of bool", DataUnit.WORD, floor, 0),
|
||||
self.warning_array_specs = [
|
||||
("array[6..12] of bool", DataUnit.WORD, ceil, 1),
|
||||
("array[1..8] of bool", DataUnit.WORD, floor, 0),
|
||||
(" \tarray[12..1234] of bool \t", DataUnit.WORD, floor, 76),
|
||||
]
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
for spec in good_array_specs + warning_array_specs:
|
||||
self.assertEqual(
|
||||
IECArray(spec[0]).get_length(spec[1], spec[2]), spec[3], spec[0]
|
||||
)
|
||||
for spec in warning_array_specs:
|
||||
self.assertWarns(
|
||||
RuntimeWarning, IECArray(spec[0]).get_length, spec[1], spec[2]
|
||||
)
|
||||
|
||||
def test_array_spec_is_valid(self):
|
||||
valid_array_specs = (
|
||||
"ARRAY [0..3] OF INT", # Uppercase, space, two dots
|
||||
"array[12...1234] of bool", # Lowercase, no space, three dots
|
||||
" \tarray[12..1234] of bool \t", # Superfluous whitespace
|
||||
"arr[0..0]int", # Minimal unambiguous specification, bounds equal
|
||||
)
|
||||
invalid_array_specs = (
|
||||
self.error_array_specs = (
|
||||
"fleebleflorp", # Nonsense
|
||||
"arry [0..5] of char", # Misspelling
|
||||
"array [..6] of word", # Missing index
|
||||
"array [1..2 of int", # Missing bracket
|
||||
"array [1..7] of float", # Invalid data type
|
||||
"array [5..1] of dint", # Lower bound greater than upper bound
|
||||
)
|
||||
for spec in valid_array_specs:
|
||||
self.assertTrue(IECArray(spec).is_valid(), spec)
|
||||
for spec in invalid_array_specs:
|
||||
self.assertRaises(ValueError, IECArray, spec)
|
||||
|
||||
def test_array(self):
|
||||
"""Test that Array raises DataUnitMismatchWarning when the length is not
|
||||
evenly divisible and InvalidSpecError for invalid specs.
|
||||
"""
|
||||
for spec in self.warning_array_specs:
|
||||
self.assertWarns(
|
||||
DataUnitMismatchWarning,
|
||||
Array(spec[0], round_function=spec[2]).get_length,
|
||||
spec[1],
|
||||
)
|
||||
for spec in self.error_array_specs:
|
||||
self.assertRaises(InvalidSpecError, Array, spec)
|
||||
|
||||
def test_get_length(self):
|
||||
"""Test get_length for both good and warning array specs."""
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
for spec in self.good_array_specs + self.warning_array_specs:
|
||||
self.assertEqual(
|
||||
Array(spec[0], round_function=spec[2]).get_length(spec[1]),
|
||||
spec[3],
|
||||
spec[0],
|
||||
)
|
||||
|
||||
def test_make_definition(self):
|
||||
with warnings.catch_warnings():
|
||||
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"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class TestIECString(unittest.TestCase):
|
||||
class TestString(unittest.TestCase):
|
||||
def test_string_length(self):
|
||||
good_string_specs = [
|
||||
("STRING[20]", DataUnit.WORD, ceil, 10),
|
||||
@@ -98,20 +165,24 @@ class TestIECString(unittest.TestCase):
|
||||
error_string_specs = [
|
||||
("STRNG[20]", DataUnit.WORD, ceil, 10),
|
||||
("STRING10]", DataUnit.WORD, ceil, 5),
|
||||
("string[]", DataUnit.BYTE, ceil, 0),
|
||||
("string[q]", DataUnit.BYTE, ceil, 0),
|
||||
("string[]", DataUnit.BIT, ceil, 0),
|
||||
("string[0]", DataUnit.BIT, ceil, 0),
|
||||
]
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
for spec in good_string_specs + warning_string_specs:
|
||||
self.assertEqual(
|
||||
IECString(spec[0]).get_length(spec[1], spec[2]), spec[3], spec[0]
|
||||
String(spec[0], spec[2]).get_length(spec[1]),
|
||||
spec[3],
|
||||
spec[0],
|
||||
)
|
||||
for spec in warning_string_specs:
|
||||
self.assertWarns(
|
||||
RuntimeWarning, IECString(spec[0]).get_length, spec[1], spec[2]
|
||||
RuntimeWarning, String(spec[0], spec[2]).get_length, spec[1]
|
||||
)
|
||||
for spec in error_string_specs:
|
||||
self.assertRaises(ValueError, IECString, spec[0])
|
||||
self.assertRaises(InvalidSpecError, String, spec[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user