Remove redundant iec.py module.

This commit is contained in:
Joshua Lucas
2026-10-14 21:19:52 -05:00
parent dece5ce043
commit cdcb2af3c3

View File

@@ -1,439 +0,0 @@
"""
AuDaGe IEC module
name: iec.py
by: Josh Lucas
date: 2026-09-14
desc: Definitions for IEC 61131 programming paradigms.
"""
import re
import warnings
from collections.abc import Callable
from enum import Enum, EnumType, IntEnum, IntFlag, StrEnum, auto
from math import ceil, prod
import pandas as pd
from AuDaGe.audage_frame import AuDaGeFrame
UNKNOWN_LENGTH = -1
class DataUnit(IntEnum):
"""The length in bits of various data units."""
BIT = 1
NIBBLE = 4
BYTE = 8
WORD = 16
DWORD = 32
QWORD = 64
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 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 = "",
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.
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
class MetaElementaryTypes(EnumType):
"""Override some of the EnumType methods so that they include aliases."""
def __contains__(cls, name: str):
"""The default Enum __contains__ method does not include aliases. This
one does.
"""
return cls.contains(name, include_array=True, include_string=True)
def __getitem__(cls, name):
return cls.__members__[name.upper()]
def __iter__(cls):
"""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.
class ElementaryTypes(Enum, 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.
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*$"
)
# 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.
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 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,
"The string length must be greater than zero.",
spec,
)
except (AttributeError, ValueError):
raise InvalidSpecError(class_name, spec=spec)
super().__init__(
spec, IECClass.CHAR, length_bytes, DataUnit.BYTE, *args, **kwargs
)
# class IECVariable:
# """"""
# 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(
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