diff --git a/src/AuDaGe/iec.py b/src/AuDaGe/iec.py index 2911e4a..0b68724 100644 --- a/src/AuDaGe/iec.py +++ b/src/AuDaGe/iec.py @@ -8,66 +8,382 @@ date: 2026-09-14 desc: Definitions for IEC 61131 programming paradigms. """ -from enum import IntEnum +import re +import warnings +from collections.abc import Callable +from enum import Enum, EnumType, IntEnum +from math import ceil from pandas import NA, Series from AuDaGe.audage_frame import AuDaGeFrame -WORD_LENGTH = 16 +class DataUnit(IntEnum): + """The length in bits of various data units.""" -class DataTypes(IntEnum): - """The IEC 61131-3 data types and their lengths in bits.""" - - # Binary - BOOL = 1 + BIT = 1 BYTE = 8 WORD = 16 - DWORD = 32 - LWORD = 64 + + +class IECType: + """A representation of an IEC 61131-3 data type.""" + + _length_bits: int + _length_bytes: int + _length_words: int + + def __init__( + self, + length_bits: int | None = None, + length_bytes: int | None = None, + length_words: int | None = None, + word_length: int = DataUnit.WORD, + round_function: Callable[[float], int] = ceil, + ): + """Initialize an object representing an IEC 61131-3 elementary data type. + + Parameters + ---------- + length_bits, length_bytes, length_words: 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] + 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.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." + ) + + def get_length(self, unit: DataUnit | int = DataUnit.WORD) -> 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.") + + 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 + + +class AliasEnumType(EnumType): + """Override some of the EnumType methods so that they include aliases.""" + + def __contains__(cls, member): + """The default Enum __contains__ method does not include aliases. This + one does. + """ + return member in cls.__members__ + + +# Disable Ruff warnings about duplicate values in this enum. +# ruff: disable[PIE796] +class IECTypes(Enum, metaclass=AliasEnumType): + """Dataclass of IEC 61131-3 elementary variable types.""" + + # Binary + BOOL = IECType(1) + BYTE = IECType(8) + WORD = IECType(16) + DWORD = IECType(32) + LWORD = IECType(64) # Signed Integer - SINT = 8 - INT = 16 - DINT = 32 - LINT = 64 + SINT = IECType(8) + INT = IECType(16) + DINT = IECType(32) + LINT = IECType(64) # Unsigned Integer - USINT = 8 - UINT = 16 - UDINT = 32 - ULINT = 64 + USINT = IECType(8) + UINT = IECType(16) + UDINT = IECType(32) + ULINT = IECType(64) # Float - REAL = 32 - LREAL = 64 + REAL = IECType(32) + LREAL = IECType(64) # Date/Time - DATE = 32 - LDATE = 64 - DT = 32 - LDT = 64 - TIME = 32 - LTIME = 64 - TOD = 32 - LTOD = 64 + DATE = IECType(32) + LDATE = IECType(64) + DT = IECType(32) + LDT = IECType(64) + TIME = IECType(32) + LTIME = IECType(64) + TOD = IECType(32) + LTOD = IECType(64) # Character - CHAR = 8 - WCHAR = 16 + CHAR = IECType(8) + WCHAR = IECType(16) + +# ruff: enable[PIE796] + + +class IECArray(IECType): + """An IEC 61131-3 array data type variable.""" + + ARRAY_SPEC_PATTERN = r"^\s*arr(?:ay)? *\[(\d+)\.{2,3}(\d+)\] *(?:of +)?(\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. + m = re.match(self.ARRAY_SPEC_PATTERN, self.spec, re.IGNORECASE) + # Parse the array specification. + start_index = int(m.groups()[0]) + end_index = int(m.groups()[1]) + data_type = m.groups()[2].upper() + # Calculate the length of the array in bits. + length_bits = ( + (end_index - start_index + 1) + * IECTypes[data_type].value.length_bits + ) # fmt: skip + 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 + m = re.match(self.ARRAY_SPEC_PATTERN, array_spec, re.IGNORECASE) + # Check whether the regex matches at all. + if m is None: + return False + # Check whether the data type is valid. + if not m.groups()[2].upper() in IECTypes: + return False + try: + # Check that the upper bound is greater than the lower bound. + if int(m.groups()[0]) > int(m.groups()[1]): + return False + # ValueError is raised if the array bounds are not integers. + except ValueError: + return False + # Return True if all the tests succeeded. + return True + + +class IECString(IECType): + """An IEC 61131-3 string data type variable.""" + + STRING_SPEC_PATTERN = r"^\s*str(?:ing)? *\[(\d+)\]\s*$" + + def __init__(self, spec: str, *args, **kwargs): + """Create an instance of IECString 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) + try: + length_bits = int(m.groups()[0]) * DataUnit.BYTE + 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 + + +class UDT(IECType): + """An IEC 61131-3 User-defined Data Type.""" + + def get_length(self, unit: DataUnit | int = DataUnit.WORD) -> int: + pass + + +def get_data_length( + data_type: str, + unit: DataUnit = DataUnit.WORD, + 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. + """ + if udt_lengths is None: + udt_lengths = {} + try: + return IECTypes[data_type].value.get_length(unit) + except KeyError: + pass + try: + match = data_type.strip()[0:3].lower() + if match == "arr": + return IECArray(data_type).get_length(unit) + if match == "str": + return IECString(data_type).get_length(unit) + except ValueError: + pass + try: + return udt_lengths[data_type] * DataUnit.WORD // unit + except KeyError: + pass + return -1 def iec_definitions() -> AuDaGeFrame: """Generate a DataFrame containing the standard IEC 61131-3 data types.""" - empty = Series([NA] * len(DataTypes.__members__)) + empty = Series([NA] * len(IECTypes)) return AuDaGeFrame( { "name": empty, "parent": empty, - "type": DataTypes.__members__, + "type": IECTypes, "address": empty, "bitrank": empty, "save": empty, "comment": empty, } ) - - -if __name__ == "__main__": - iec_definitions().to_csv("tests/output/iec_definitions.csv", index=False) diff --git a/tests/test_iec.py b/tests/test_iec.py index eddb236..a1c5f98 100644 --- a/tests/test_iec.py +++ b/tests/test_iec.py @@ -9,19 +9,107 @@ desc: Unit tests for the AuDaGe IEC module. """ import unittest +import warnings +from math import ceil, floor -from AuDaGe import iec +from AuDaGe.iec import * class TestIEC(unittest.TestCase): - """""" + """Module-level tests.""" + + def test_get_data_length(self): + data_types = [ + ("BOOL", DataUnit.BIT, 1), + ("CHAR", DataUnit.BIT, 8), + ("INT", DataUnit.BIT, 16), + ("BOOL", DataUnit.WORD, 1), + ("ARRAY [0..10] OF INT", DataUnit.WORD, 11), + ("STRING[10]", DataUnit.WORD, 5), + ("UNKNOWN_UDT", DataUnit.WORD, -1), + ] + for data_type in data_types: + self.assertEqual(get_data_length(data_type[0], data_type[1]), data_type[2]) def test_iec_definitions(self): - iec_definitions = iec.iec_definitions() - self.assertTrue(iec_definitions.is_valid()) - self.assertEqual( - iec_definitions.dataframe.shape, (len(iec.DataTypes.__members__), 7) + definitions = iec_definitions() + self.assertTrue(definitions.is_valid()) + self.assertEqual(definitions.shape, (len(IECTypes.__members__), 7)) + + +class TestIECArray(unittest.TestCase): + def test_array_length(self): + good_array_specs = [ + ("ARRAY [0..3] OF INT", DataUnit.WORD, ceil, 4), + ("array[15..20] of bool", DataUnit.BIT, ceil, 6), + ] + warning_array_specs = [ + ("array[15..20] of bool", DataUnit.WORD, ceil, 1), + ("array[15..20] of bool", DataUnit.WORD, floor, 0), + ] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + self.assertTrue( + all( + IECArray(spec[0]).get_length(spec[1], spec[2]) == spec[3] + for spec in good_array_specs + warning_array_specs + ) + ) + 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 + "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 + ) + self.assertTrue(all(IECArray(spec).is_valid() for spec in valid_array_specs)) + for spec in invalid_array_specs: + self.assertRaises(ValueError, IECArray, spec) + + +class TestIECString(unittest.TestCase): + def test_string_length(self): + good_string_specs = [ + ("STRING[20]", DataUnit.WORD, ceil, 10), + ("string [80]\t", DataUnit.BYTE, ceil, 80), + (" string [10] ", DataUnit.BIT, ceil, 80), + ] + warning_string_specs = [ + ("\tSTRING[15]", DataUnit.WORD, ceil, 8), + ("STRING [15]", DataUnit.WORD, floor, 7), + ] + error_string_specs = [ + ("STRNG[20]", DataUnit.WORD, ceil, 10), + ("STRING10]", DataUnit.WORD, ceil, 5), + ("string[]", DataUnit.BYTE, ceil, 0), + ] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + self.assertTrue( + all( + IECString(spec[0]).get_length(spec[1], spec[2]) == spec[3] + for spec in good_string_specs + warning_string_specs + ) + ) + for spec in warning_string_specs: + self.assertWarns( + RuntimeWarning, IECString(spec[0]).get_length, spec[1], spec[2] + ) + for spec in error_string_specs: + self.assertRaises(ValueError, IECString, spec[0]) if __name__ == "__main__":