Major IEC module refactor.

This commit is contained in:
Silcantar
2026-10-02 16:33:56 -05:00
parent bd254fe3e5
commit c59544e6a6
2 changed files with 447 additions and 344 deletions

View File

@@ -11,13 +11,15 @@ desc: Definitions for IEC 61131 programming paradigms.
import re import re
import warnings import warnings
from collections.abc import Callable 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 math import ceil, prod
from pandas import NA, Series import pandas as pd
from AuDaGe.audage_frame import AuDaGeFrame from AuDaGe.audage_frame import AuDaGeFrame
UNKNOWN_LENGTH = -1
class DataUnit(IntEnum): class DataUnit(IntEnum):
"""The length in bits of various data units.""" """The length in bits of various data units."""
@@ -30,378 +32,408 @@ class DataUnit(IntEnum):
QWORD = 64 QWORD = 64
class IECType: class IECClass(StrEnum):
"""A representation of an IEC 61131-3 data type.""" """Classes of IEC 61131-3 data types."""
_length_bits: int BINARY = auto()
_length_bytes: int INTEGER = auto()
_length_words: int 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__( def __init__(
self, self,
length_bits: int | None = None, source: str = "",
length_bytes: int | None = None, message: str = "",
length_words: int | None = None, spec: str = "",
word_length: int = DataUnit.WORD, *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, 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 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 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 must be provided. If several are provided, the first in the order
above takes priority. above takes priority.
word_length: int unit : DataUnit
The length of a word in the target controller architecture. Defaults The data unit to use to measure the length of the data type.
to 16. Defaults to DataUnit.WORD.
round_function: Callable[[float], int] round_function : Callable[[float], int]
The function to use to round the data length when it does not divide The function to use to round the data length when it does not divide
evenly by the selected unit. Defaults to math.ceil(). 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 self.round = round_function
if length_bits is not None: self.length_bits = length * unit
self.length_bits = length_bits self.length = self.get_length
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."
)
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.""" """Get the data length of the type in the specified unit."""
match unit: if self.length_bits % unit != 0 and not silent:
case DataUnit.BIT: warnings.warn(None, category=DataUnitMismatchWarning)
return self.length_bits return int(self.round(self.length_bits / unit))
case DataUnit.BYTE:
return self.length_bytes
case DataUnit.WORD:
return self.length_words
case _:
raise ValueError("Invalid data unit.")
def set_length(self, value: int, unit: DataUnit = DataUnit.BIT): def set_length(self, value: int, unit: DataUnit = DataUnit.BIT):
"""Set the data length of the type in the specified unit.""" """Set the data length of the type in the specified unit."""
match unit: self.length_bits = value * 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
class AliasEnumType(EnumType): class MetaElementaryTypes(EnumType):
"""Override some of the EnumType methods so that they include aliases.""" """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 """The default Enum __contains__ method does not include aliases. This
one does. 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): 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. # Disable Ruff warnings about duplicate values in this enum.
# ruff: disable[PIE796] class ElementaryTypes(Enum, metaclass=MetaElementaryTypes):
class IECTypes(Enum, metaclass=AliasEnumType):
"""Dataclass of IEC 61131-3 elementary variable types.""" """Dataclass of IEC 61131-3 elementary variable types."""
# Binary # Binary
BOOL = IECType(1) BOOL = IECType("BOOL", IECClass.BINARY, 1)
BYTE = IECType(8) EBOOL = IECType("EBOOL", IECClass.BINARY, 8)
WORD = IECType(16) BYTE = IECType("BYTE", IECClass.BINARY, 8)
DWORD = IECType(32) WORD = IECType("WORD", IECClass.BINARY, 16)
LWORD = IECType(64) DWORD = IECType("DWORD", IECClass.BINARY, 32)
LWORD = IECType("LWORD", IECClass.BINARY, 64)
# Signed Integer # Signed Integer
SINT = IECType(8) SINT = IECType("SINT", IECClass.INTEGER, 8)
INT = IECType(16) INT = IECType("INT", IECClass.INTEGER, 16)
DINT = IECType(32) DINT = IECType("DINT", IECClass.INTEGER, 32)
LINT = IECType(64) LINT = IECType("LINT", IECClass.INTEGER, 64)
# Unsigned Integer # Unsigned Integer
USINT = IECType(8) USINT = IECType("USINT", IECClass.INTEGER, 8)
UINT = IECType(16) UINT = IECType("UINT", IECClass.INTEGER, 16)
UDINT = IECType(32) UDINT = IECType("UDINT", IECClass.INTEGER, 32)
ULINT = IECType(64) ULINT = IECType("ULINT", IECClass.INTEGER, 64)
# Float # Float
REAL = IECType(32) REAL = IECType("REAL", IECClass.REAL, 32)
LREAL = IECType(64) LREAL = IECType("LREAL", IECClass.REAL, 64)
# Date/Time # Date/Time
DATE = IECType(32) DATE = IECType("DATE", IECClass.DATETIME, 32)
LDATE = IECType(64) LDATE = IECType("LDATE", IECClass.DATETIME, 64)
DT = IECType(32) DT = IECType("DT", IECClass.DATETIME, 32)
LDT = IECType(64) LDT = IECType("LDT", IECClass.DATETIME, 64)
TIME = IECType(32) TIME = IECType("TIME", IECClass.DATETIME, 32)
LTIME = IECType(64) LTIME = IECType("LTIME", IECClass.DATETIME, 64)
TOD = IECType(32) TOD = IECType("TOD", IECClass.DATETIME, 32)
LTOD = IECType(64) LTOD = IECType("LTOD", IECClass.DATETIME, 64)
# Character # Character
CHAR = IECType(8) CHAR = IECType("CHAR", IECClass.CHAR, 8)
WCHAR = IECType(16) WCHAR = IECType("WCHAR", IECClass.CHAR, 16)
STRING = IECType("STRING", IECClass.CHAR, 128)
# ruff: enable[PIE796] # ruff: enable[PIE796]
class IECArray(IECType): class Array(IECType):
"""An IEC 61131-3 array data type variable.""" """An IEC 61131-3 array data type variable."""
BOUNDS_PATTERN = r"\d+" class ArraySpec:
ARRAY_SPEC_PATTERN = ( # Regular expression for parsing array specifications.
r"^\s*arr(?:ay)?\s*\[((?:\d+\s*\.{2,3}\s*\d+\s*,?\s*)+)\]\s*(?:of\s+)?(\w+)\s*$" ARRAY_SPEC_PATTERN = (
) # Array declaration: "arr(ay)" with variable whitespace before and
# after.
def __init__(self, spec: str, *args, **kwargs): r"^\s*arr(?:ay)?\s*"
"""Create an instance of IECArray based on an IEC 61131-3 array # Bounds: for each dimension of the array, a pair of integers
specification as a string. For maximum compatibility should be of the # separated by "..(.)", with each pair delimited by commas with
form "ARRAY [{m}..{n}] OF {TYPE}" where m and n are integers, m < n, and # variable whitespace. All enclosed in square brackets.
TYPE is the name of an IEC 61131-3 data type. This function is tolerant r"\[((?:\d+\s*\.{2,3}\s*\d+\s*,?\s*)+)\]"
of some variation in the formatting of this specification and is not # Data type: optional "of" with whitespace, a word, and variable
case-sensitive. # whitespace at the end.
""" r"\s*(?:of\s+)?(\w+)\s*$"
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
) )
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: # Regular expression that matches integers within the bounds section of
"""Check whether the given IEC 61131-3 array specification is valid. # an array specification.
For maximum compatibility, array_spec should be a string or regular BOUNDS_PATTERN = r"\d+"
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 def __init__(self, spec: str):
type. This function is tolerant of some variation in the formatting of class_name = "Array" # self.__class__.__name__
this specification and is not case-sensitive. self.spec = spec
""" match = re.match(self.ARRAY_SPEC_PATTERN, spec, re.IGNORECASE)
if array_spec is None: # Check whether the regex matches at all.
array_spec = self.spec if match is None:
match = re.match(self.ARRAY_SPEC_PATTERN, array_spec, re.IGNORECASE) raise InvalidSpecError(class_name, spec=spec)
# Check whether the regex matches at all. self.type_name = match.group(2)
if match is None: all_bounds = re.findall(
return False self.BOUNDS_PATTERN, match.group(1), re.IGNORECASE
bounds = re.findall(self.BOUNDS_PATTERN, match.groups()[0], re.IGNORECASE) )
# Check whether the data type is valid. # Group the bounds of the array into pairs.
if not match.groups()[-1].upper() in IECTypes: self.bounds = list(zip(all_bounds[::2], all_bounds[1::2]))
return False
try:
# Check that each dimension's upper bound is greater than or equal # Check that each dimension's upper bound is greater than or equal
# to its lower bound. # to its lower bound.
for lbound, ubound in zip(bounds[::2], bounds[1::2]): try:
if int(lbound) > int(ubound): for lbound, ubound in self.bounds:
return False if int(lbound) > int(ubound):
# ValueError is raised if the array bounds are not coercible to integers. raise InvalidSpecError(
except ValueError: class_name,
return False "The upper bound of at least one dimension is less "
# Return True if all the tests succeeded. "than its lower bound.",
return True 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.""" """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): 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 specification as a string. For maximum compatibility should be of the
form "STRING [{n}]" where n is an integer. This function is tolerant of form "STRING [{n}]" where n is an integer. This function is tolerant of
some variation in the formatting of this specification and is not some variation in the formatting of this specification and is not
case-sensitive. case-sensitive.
""" """
if not self.is_valid(spec): class_name = self.__class__.__name__
raise ValueError("The provided string specification is not valid.") match = re.match(self.STRING_SPEC_PATTERN, spec, re.IGNORECASE)
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)
try: try:
# 1 ASCII character == 1 byte. length_bytes = int(match.group(1))
length_bits = int(m.groups()[0]) * DataUnit.BYTE if length_bytes <= 0:
raise InvalidSpecError(
class_name,
"The string length must be greater than zero.",
spec,
)
except (AttributeError, ValueError): except (AttributeError, ValueError):
raise ValueError("The provided string specification is invalid.") raise InvalidSpecError(class_name, spec=spec)
if length_bits % unit != 0: super().__init__(
warnings.warn( spec, IECClass.CHAR, length_bytes, DataUnit.BYTE, *args, **kwargs
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
class UDT(IECType): # class IECVariable:
"""An IEC 61131-3 User-defined Data Type.""" # """"""
def get_length(self, unit: DataUnit | int = DataUnit.WORD) -> int: # def __init__(
pass # 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( def get_data_length(
data_type: str, type_name: str,
unit: DataUnit = DataUnit.WORD, unit: DataUnit = DataUnit.BIT,
udt_lengths: dict[str, int] | None = None, udt_lengths: dict[str, int] | None = None,
) -> int: round_function: Callable[[float], int] = ceil,
"""Get the length of the specified data type as measured in the unknown_length: any = UNKNOWN_LENGTH,
specified unit. Returns -1 if the data type is unknown. ) -> 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: 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: except KeyError:
pass 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: try:
return udt_lengths[data_type] * DataUnit.WORD // unit return Array(type_name).get_length(unit)
except KeyError: except ValueError:
pass pass
return -1 try:
return String(type_name).get_length(unit)
except ValueError:
def iec_definitions() -> AuDaGeFrame: pass
"""Generate a DataFrame containing the standard IEC 61131-3 data types.""" return unknown_length
empty = Series([NA] * len(IECTypes))
return AuDaGeFrame(
{
"name": empty,
"parent": empty,
"type": IECTypes,
"address": empty,
"bitrank": empty,
"save": empty,
"comment": empty,
}
)

View File

@@ -10,81 +10,148 @@ desc: Unit tests for the AuDaGe IEC module.
import unittest import unittest
import warnings import warnings
from importlib import resources
from math import ceil, floor from math import ceil, floor
import output
from AuDaGe.iec import * from AuDaGe.iec import *
class TestIEC(unittest.TestCase): class TestIEC(unittest.TestCase):
"""Module-level tests.""" """Module-level tests."""
def test_get_data_length(self): def setUp(self):
data_types = [ self.elementary_data_types = [
("BOOL", DataUnit.BIT, 1), ("BOOL", DataUnit.BIT, 1),
("CHAR", DataUnit.BIT, 8), ("CHAR", DataUnit.BIT, 8),
("INT", DataUnit.BIT, 16), ("INT", DataUnit.BIT, 16),
("BOOL", DataUnit.WORD, 1), ("BOOL", DataUnit.WORD, 1),
("ARRAY [1..10, 0..7] OF INT", DataUnit.WORD, 80), ("ARRAY [1..10, 0..7] OF INT", DataUnit.WORD, 80),
("STRING[10]", DataUnit.WORD, 5), ("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( 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],
) )
for data_type in invalid_types:
def test_iec_definitions(self): self.assertFalse(data_type in ElementaryTypes, data_type)
definitions = iec_definitions()
self.assertTrue(definitions.is_valid())
self.assertEqual(definitions.shape, (len(IECTypes.__members__), 7))
class TestIECArray(unittest.TestCase): class TestArray(unittest.TestCase):
def test_array_length(self): def setUp(self):
good_array_specs = [ self.good_array_specs = [
("ARRAY [0..3] OF INT", DataUnit.WORD, ceil, 4), ("ARRAY [0..3] OF INT", DataUnit.WORD, ceil, 4),
("ARRAY [0..0] OF REAL", DataUnit.WORD, ceil, 2), ("ARRAY [0..0] OF REAL", DataUnit.WORD, ceil, 2),
("ARRAY [0..3, 0..3] OF INT", DataUnit.WORD, ceil, 16), ("ARRAY [0..3, 0..3] OF INT", DataUnit.WORD, ceil, 16),
("array[15..20] of bool", DataUnit.BIT, ceil, 6), ("array[15..20] of bool", DataUnit.BIT, ceil, 6),
("ARRAY [0..1, 0..2, 0..3, 0..4] OF INT", DataUnit.WORD, ceil, 120), ("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 = [ self.warning_array_specs = [
("array[15..20] of bool", DataUnit.WORD, ceil, 1), ("array[6..12] of bool", DataUnit.WORD, ceil, 1),
("array[15..20] of bool", DataUnit.WORD, floor, 0), ("array[1..8] of bool", DataUnit.WORD, floor, 0),
(" \tarray[12..1234] of bool \t", DataUnit.WORD, floor, 76),
] ]
with warnings.catch_warnings(): self.error_array_specs = (
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 = (
"fleebleflorp", # Nonsense "fleebleflorp", # Nonsense
"arry [0..5] of char", # Misspelling "arry [0..5] of char", # Misspelling
"array [..6] of word", # Missing index "array [..6] of word", # Missing index
"array [1..2 of int", # Missing bracket "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 "array [5..1] of dint", # Lower bound greater than upper bound
) )
for spec in valid_array_specs:
self.assertTrue(IECArray(spec).is_valid(), spec) def test_array(self):
for spec in invalid_array_specs: """Test that Array raises DataUnitMismatchWarning when the length is not
self.assertRaises(ValueError, IECArray, spec) 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): def test_string_length(self):
good_string_specs = [ good_string_specs = [
("STRING[20]", DataUnit.WORD, ceil, 10), ("STRING[20]", DataUnit.WORD, ceil, 10),
@@ -98,20 +165,24 @@ class TestIECString(unittest.TestCase):
error_string_specs = [ error_string_specs = [
("STRNG[20]", DataUnit.WORD, ceil, 10), ("STRNG[20]", DataUnit.WORD, ceil, 10),
("STRING10]", DataUnit.WORD, ceil, 5), ("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(): with warnings.catch_warnings():
warnings.simplefilter("ignore") warnings.simplefilter("ignore")
for spec in good_string_specs + warning_string_specs: for spec in good_string_specs + warning_string_specs:
self.assertEqual( 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: for spec in warning_string_specs:
self.assertWarns( 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: for spec in error_string_specs:
self.assertRaises(ValueError, IECString, spec[0]) self.assertRaises(InvalidSpecError, String, spec[0])
if __name__ == "__main__": if __name__ == "__main__":