Rewrite iec_type module to support converting to OPC UA types and to harmonize better with the rest of the project.
This commit is contained in:
@@ -6,233 +6,223 @@ by: Josh Lucas
|
|||||||
date: 2026-10-14
|
date: 2026-10-14
|
||||||
|
|
||||||
desc: Definitions for IEC 61131 data type paradigms.
|
desc: Definitions for IEC 61131 data type paradigms.
|
||||||
|
|
||||||
|
# IEC Type Attributes
|
||||||
|
- Name: str
|
||||||
|
- Class: IECClass
|
||||||
|
- Length (bits): int
|
||||||
|
- Array Bounds (Array only)
|
||||||
|
- Array Type (Array only): IECType
|
||||||
|
- Methods
|
||||||
|
- get_length
|
||||||
|
- from_opcua
|
||||||
|
- from_string
|
||||||
|
- to_opcua
|
||||||
|
- to_string
|
||||||
|
- expansion (Array and UDT only) -> DataFrame
|
||||||
|
|
||||||
|
# IEC Class Tree
|
||||||
|
- User-defined
|
||||||
|
- UDT
|
||||||
|
- Array of UDT
|
||||||
|
- Elementary
|
||||||
|
- Array
|
||||||
|
- 1D Array
|
||||||
|
- ND Array
|
||||||
|
- Scalar
|
||||||
|
- Custom-length string
|
||||||
|
- Basic
|
||||||
|
- Binary
|
||||||
|
- Int
|
||||||
|
- Real
|
||||||
|
- Date/Time
|
||||||
|
- Char
|
||||||
|
- Default-length string
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import itertools
|
||||||
import re
|
import re
|
||||||
import warnings
|
from enum import Enum, StrEnum, auto
|
||||||
from collections.abc import Callable
|
|
||||||
from enum import IntFlag, StrEnum, auto
|
|
||||||
from math import ceil, prod
|
from math import ceil, prod
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from numpy import nan
|
from numpy import nan
|
||||||
|
|
||||||
from AuDaGe.better_enum import AliasEnum, AliasEnumType
|
|
||||||
from AuDaGe.frame import AuDaGeFrame
|
from AuDaGe.frame import AuDaGeFrame
|
||||||
|
|
||||||
from .iec_common import *
|
from .iec_common import *
|
||||||
|
|
||||||
|
type ArrayBounds = Sequence[Sequence[int, int]]
|
||||||
|
|
||||||
|
DEFAULT_STRING_LENGTH = 16
|
||||||
|
"""Length of a default IEC string: 16 characters."""
|
||||||
|
|
||||||
UNKNOWN_LENGTH = -1
|
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):
|
class IECClass(StrEnum):
|
||||||
"""Classes of IEC 61131-3 data types."""
|
"""Classes of IEC 61131-3 data types."""
|
||||||
|
|
||||||
BINARY = auto()
|
BINARY = auto()
|
||||||
INTEGER = auto()
|
SIGNED = auto()
|
||||||
REAL = auto()
|
UNSIGNED = auto()
|
||||||
DATETIME = auto()
|
|
||||||
CHAR = auto()
|
|
||||||
ARRAY = auto()
|
|
||||||
UDT = auto()
|
|
||||||
|
|
||||||
|
|
||||||
class IECTypeFlag(IntFlag):
|
|
||||||
BINARY = auto()
|
|
||||||
INTEGER = auto()
|
|
||||||
REAL = auto()
|
REAL = auto()
|
||||||
DATE = auto()
|
DATE = auto()
|
||||||
TIME = auto()
|
|
||||||
DT = auto()
|
DT = auto()
|
||||||
|
TIME = auto()
|
||||||
TOD = auto()
|
TOD = auto()
|
||||||
CHAR = auto()
|
CHAR = auto()
|
||||||
UDT = 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:
|
class IECType:
|
||||||
"""A representation of an IEC 61131-3 data type."""
|
"""A representation of an IEC 61131-3 data type."""
|
||||||
|
|
||||||
|
# Dunder methods
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
name: str,
|
name: str,
|
||||||
iec_class: IECClass,
|
iec_class: IECClass,
|
||||||
length: int = 0,
|
length: int,
|
||||||
unit: DataUnit = DataUnit.BIT,
|
array_bounds: ArrayBounds | None = None,
|
||||||
round_function: Callable[[float], int] = ceil,
|
array_type: str | None = None,
|
||||||
):
|
):
|
||||||
"""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.name = name
|
||||||
self.iec_class = iec_class
|
self.iec_class = iec_class
|
||||||
self.round = round_function
|
self.length = length
|
||||||
self.length_bits = length * unit
|
self.array_bounds = array_bounds
|
||||||
self.length = self.get_length
|
self.array_type = array_type
|
||||||
|
|
||||||
def get_length(
|
def __eq__(self, other) -> bool:
|
||||||
self, unit: DataUnit | int = DataUnit.BIT, silent: bool = False
|
return all(
|
||||||
) -> int:
|
this == that for this, that in zip(self.__dict__, other.__dict__)
|
||||||
"""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):
|
# Constructors
|
||||||
"""Set the data length of the type in the specified unit."""
|
@classmethod
|
||||||
self.length_bits = value * unit
|
def from_opcua(
|
||||||
|
cls, spec: str, string_length: int = DEFAULT_STRING_LENGTH
|
||||||
|
) -> IECType:
|
||||||
|
spec_cleaned = spec.strip().upper()
|
||||||
|
if spec_cleaned == "STRING":
|
||||||
|
return cls(spec, IECClass.CHAR, string_length * DataUnit.BYTE)
|
||||||
|
return OPCUAtoIEC[spec_cleaned]
|
||||||
|
|
||||||
def from_opcua(self, spec: str):
|
@classmethod
|
||||||
|
def from_string(
|
||||||
|
cls,
|
||||||
|
spec: str,
|
||||||
|
udt_lengths: dict | None = None,
|
||||||
|
allow_unknown: bool = True,
|
||||||
|
) -> IECType:
|
||||||
|
if udt_lengths is None:
|
||||||
|
udt_lengths = {}
|
||||||
|
try:
|
||||||
|
return BasicTypes.__dict__[spec.upper()]
|
||||||
|
except KeyError:
|
||||||
pass
|
pass
|
||||||
|
try:
|
||||||
|
return cls._parse_array_spec(spec)
|
||||||
|
except InvalidSpecError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
return cls._parse_string_spec(spec)
|
||||||
|
except InvalidSpecError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
return cls(spec, IECClass.UDT, udt_lengths[spec])
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
|
if allow_unknown:
|
||||||
|
return cls(spec, IECClass.UDT, UNKNOWN_LENGTH)
|
||||||
|
raise InvalidSpecError(
|
||||||
|
"IECType.from_string",
|
||||||
|
spec,
|
||||||
|
"The provided spec does not match any known data type.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Instance methods
|
||||||
|
def get_length(
|
||||||
|
self,
|
||||||
|
unit: DataUnit = DataUnit.WORD,
|
||||||
|
round_function: Callable[float, float] = ceil,
|
||||||
|
) -> float:
|
||||||
|
"""Get the length of the data type in the specified unit and if
|
||||||
|
necessary round the value using the specified function.
|
||||||
|
"""
|
||||||
|
return round_function(self.length / unit)
|
||||||
|
|
||||||
|
def is_basic(self) -> bool:
|
||||||
|
"""Return whether this data type is basic, i.e. not a UDT, array, or
|
||||||
|
custom-length string.
|
||||||
|
"""
|
||||||
|
return self.is_scalar() and not self.is_custom_string()
|
||||||
|
|
||||||
|
def is_custom_string(self) -> bool:
|
||||||
|
"""Return whether this data type is a custom-length string."""
|
||||||
|
return (
|
||||||
|
self.iec_class == IECClass.CHAR
|
||||||
|
and self.length != DEFAULT_STRING_LENGTH * DataUnit.BYTE
|
||||||
|
)
|
||||||
|
|
||||||
|
def is_elementary(self) -> bool:
|
||||||
|
"""Return whether this data type is elementary, i.e. not a UDT."""
|
||||||
|
return self.iec_class != IECClass.UDT
|
||||||
|
|
||||||
|
def is_scalar(self) -> bool:
|
||||||
|
"""Return whether this data type is scalar, i.e. not a UDT or array."""
|
||||||
|
return self.is_elementary() and self.bounds is None
|
||||||
|
|
||||||
def to_opcua(self) -> str:
|
def to_opcua(self) -> str:
|
||||||
pass
|
if not self.is_scalar():
|
||||||
|
raise ValueError(
|
||||||
|
"The `to_opcua` method can only be called on scalar types."
|
||||||
|
)
|
||||||
|
spec_cleaned = self.name.split("[")[0].strip()
|
||||||
|
return IECtoOPCUA[spec_cleaned]
|
||||||
|
|
||||||
|
def to_string(self) -> str:
|
||||||
|
return self.name.upper()
|
||||||
|
|
||||||
class MetaElementaryTypes(AliasEnumType):
|
def array_expansion(self, name: str, comment: str = "") -> AuDaGeFrame:
|
||||||
"""Override some of the EnumType methods so that they include aliases."""
|
if self.array_bounds is None or self.array_type is None:
|
||||||
|
raise ValueError(
|
||||||
|
"The `array_expansion` method can only be called on an array "
|
||||||
|
"type."
|
||||||
|
)
|
||||||
|
all_indices = None
|
||||||
|
for i, (lbound, ubound) in enumerate(self.array_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 = {
|
||||||
|
"name": all_indices.apply(
|
||||||
|
lambda row: f"{name}[{','.join(str(dim) for dim in row)}]",
|
||||||
|
axis=1,
|
||||||
|
),
|
||||||
|
"type": self.array_type,
|
||||||
|
"address": nan,
|
||||||
|
"comment": comment,
|
||||||
|
"parent": self.name.upper(),
|
||||||
|
}
|
||||||
|
return AuDaGeFrame(columns)
|
||||||
|
|
||||||
def __contains__(cls, name: str) -> bool:
|
# Internal methods
|
||||||
"""The default Enum __contains__ method does not include aliases. This
|
@classmethod
|
||||||
one does.
|
def _parse_array_spec(cls, spec: str) -> IECType:
|
||||||
|
"""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 or UDT. This function
|
||||||
|
is tolerant of some variation in the formatting of this specification
|
||||||
|
and is not case-sensitive.
|
||||||
"""
|
"""
|
||||||
return cls.contains(name, include_array=True, include_string=True)
|
# Function name for error messages.
|
||||||
|
_name = "IECType._parse_array_spec"
|
||||||
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.
|
# Regular expression for parsing array specifications.
|
||||||
SPEC_PATTERN = (
|
SPEC_PATTERN = (
|
||||||
# Array declaration: "arr(ay)" with variable whitespace before and
|
# Array declaration: "arr(ay)" with variable whitespace before and
|
||||||
@@ -246,31 +236,23 @@ class Array(IECType):
|
|||||||
# whitespace at the end.
|
# whitespace at the end.
|
||||||
r"\s*(?:of\s+)?(\w+)\s*$"
|
r"\s*(?:of\s+)?(\w+)\s*$"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Regular expression that matches integers within the bounds section of
|
# Regular expression that matches integers within the bounds section of
|
||||||
# an array specification.
|
# an array specification.
|
||||||
BOUNDS_PATTERN = r"\d+"
|
BOUNDS_PATTERN = r"\d+"
|
||||||
|
match = re.match(SPEC_PATTERN, spec, re.IGNORECASE)
|
||||||
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.
|
# Check whether the regex matches at all.
|
||||||
if match is None:
|
if match is None:
|
||||||
raise InvalidSpecError(class_name, spec)
|
raise InvalidSpecError(_name, spec)
|
||||||
self.type_name = match.group(2)
|
data_type = IECType.from_string(match.group(2))
|
||||||
all_bounds = re.findall(
|
all_bounds = re.findall(BOUNDS_PATTERN, match.group(1), re.IGNORECASE)
|
||||||
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
|
# Check that each dimension's upper bound is greater than or equal
|
||||||
# to its lower bound.
|
# to its lower bound.
|
||||||
|
bounds_paired = tuple(itertools.batched(all_bounds, 2))
|
||||||
try:
|
try:
|
||||||
for lbound, ubound in self.bounds:
|
for lbound, ubound in bounds_paired:
|
||||||
if int(lbound) > int(ubound):
|
if int(lbound) > int(ubound):
|
||||||
raise InvalidSpecError(
|
raise InvalidSpecError(
|
||||||
class_name,
|
_name,
|
||||||
spec,
|
spec,
|
||||||
"The upper bound of at least one dimension is less "
|
"The upper bound of at least one dimension is less "
|
||||||
"than its lower bound.",
|
"than its lower bound.",
|
||||||
@@ -279,141 +261,133 @@ class Array(IECType):
|
|||||||
# integers.
|
# integers.
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise InvalidSpecError(
|
raise InvalidSpecError(
|
||||||
class_name,
|
_name,
|
||||||
spec,
|
spec,
|
||||||
"At least one bound is not an integer.",
|
"At least one bound is not an integer.",
|
||||||
)
|
)
|
||||||
|
if data_type.length <= 0:
|
||||||
def __init__(
|
length = UNKNOWN_LENGTH
|
||||||
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:
|
else:
|
||||||
# Calculate the length of the array in bits.
|
# Calculate the length of the array in bits.
|
||||||
length_bits = (
|
length = (
|
||||||
prod(
|
prod(
|
||||||
(int(ubound) - int(lbound) + 1)
|
(int(ubound) - int(lbound) + 1)
|
||||||
for (lbound, ubound) in self.spec.bounds
|
for (lbound, ubound) in bounds_paired
|
||||||
)
|
)
|
||||||
* ElementaryTypes[self.spec.type_name.upper()].value.length_bits
|
* data_type.length
|
||||||
)
|
)
|
||||||
super().__init__(
|
return cls(
|
||||||
spec,
|
name=spec,
|
||||||
IECClass.ARRAY,
|
iec_class=data_type.iec_class,
|
||||||
length_bits,
|
length=length,
|
||||||
DataUnit.BIT,
|
array_bounds=bounds_paired,
|
||||||
round_function,
|
array_type=data_type,
|
||||||
*args,
|
|
||||||
**kwargs,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def is_elementary(self) -> bool:
|
@classmethod
|
||||||
return self.spec.type_name in ElementaryTypes
|
def _parse_string_spec(cls, spec: str) -> IECType:
|
||||||
|
|
||||||
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
|
"""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.
|
||||||
"""
|
"""
|
||||||
class_name = self.__class__.__name__
|
_name = "IECType._parse_string_spec"
|
||||||
match = re.match(self.STRING_SPEC_PATTERN, spec, re.IGNORECASE)
|
STRING_SPEC_PATTERN = r"^\s*str(?:ing)?\s*\[(\d+)\]\s*$"
|
||||||
|
match = re.match(STRING_SPEC_PATTERN, spec, re.IGNORECASE)
|
||||||
try:
|
try:
|
||||||
length_bytes = int(match.group(1))
|
length = int(match.group(1)) * DataUnit.BYTE
|
||||||
if length_bytes <= 0:
|
if length <= 0:
|
||||||
raise InvalidSpecError(
|
raise InvalidSpecError(
|
||||||
class_name,
|
_name,
|
||||||
spec,
|
spec,
|
||||||
"The string length must be greater than zero.",
|
"The string length must be greater than zero.",
|
||||||
)
|
)
|
||||||
except AttributeError, ValueError:
|
except AttributeError, ValueError:
|
||||||
raise InvalidSpecError(class_name, spec)
|
raise InvalidSpecError(_name, spec)
|
||||||
super().__init__(
|
return cls(spec, IECClass.CHAR, length)
|
||||||
spec, IECClass.CHAR, length_bytes, DataUnit.BYTE, *args, **kwargs
|
|
||||||
|
|
||||||
|
class BasicTypes:
|
||||||
|
"""Enum of IEC 61131-3 basic variable types."""
|
||||||
|
|
||||||
|
# Binary
|
||||||
|
BOOL = IECType("BOOL", IECClass.BINARY, DataUnit.BIT)
|
||||||
|
EBOOL = IECType("EBOOL", IECClass.BINARY, DataUnit.BYTE)
|
||||||
|
BYTE = IECType("BYTE", IECClass.BINARY, DataUnit.BYTE)
|
||||||
|
WORD = IECType("WORD", IECClass.BINARY, DataUnit.WORD)
|
||||||
|
DWORD = IECType("DWORD", IECClass.BINARY, DataUnit.DWORD)
|
||||||
|
LWORD = IECType("LWORD", IECClass.BINARY, DataUnit.QWORD)
|
||||||
|
# Signed Integer
|
||||||
|
SINT = IECType("SINT", IECClass.SIGNED, DataUnit.BYTE)
|
||||||
|
INT = IECType("INT", IECClass.SIGNED, DataUnit.WORD)
|
||||||
|
DINT = IECType("DINT", IECClass.SIGNED, DataUnit.DWORD)
|
||||||
|
LINT = IECType("LINT", IECClass.SIGNED, DataUnit.QWORD)
|
||||||
|
# Unsigned Integer
|
||||||
|
USINT = IECType("USINT", IECClass.UNSIGNED, DataUnit.BYTE)
|
||||||
|
UINT = IECType("UINT", IECClass.UNSIGNED, DataUnit.WORD)
|
||||||
|
UDINT = IECType("UDINT", IECClass.UNSIGNED, DataUnit.DWORD)
|
||||||
|
ULINT = IECType("ULINT", IECClass.UNSIGNED, DataUnit.QWORD)
|
||||||
|
# Float
|
||||||
|
REAL = IECType("REAL", IECClass.REAL, DataUnit.DWORD)
|
||||||
|
LREAL = IECType("LREAL", IECClass.REAL, DataUnit.QWORD)
|
||||||
|
# Date/Time
|
||||||
|
DATE = IECType("DATE", IECClass.DATE, DataUnit.DWORD)
|
||||||
|
LDATE = IECType("LDATE", IECClass.DATE, DataUnit.QWORD)
|
||||||
|
DT = IECType("DT", IECClass.DT, DataUnit.DWORD)
|
||||||
|
LDT = IECType("LDT", IECClass.DT, DataUnit.QWORD)
|
||||||
|
TIME = IECType("TIME", IECClass.TIME, DataUnit.DWORD)
|
||||||
|
LTIME = IECType("LTIME", IECClass.TIME, DataUnit.QWORD)
|
||||||
|
TOD = IECType("TOD", IECClass.TOD, DataUnit.DWORD)
|
||||||
|
LTOD = IECType("LTOD", IECClass.TOD, DataUnit.QWORD)
|
||||||
|
# Character
|
||||||
|
CHAR = IECType("CHAR", IECClass.CHAR, DataUnit.BYTE)
|
||||||
|
WCHAR = IECType("WCHAR", IECClass.CHAR, DataUnit.WORD)
|
||||||
|
# String with the default length of 16 characters.
|
||||||
|
STRING = IECType(
|
||||||
|
"STRING", IECClass.CHAR, DEFAULT_STRING_LENGTH * DataUnit.BYTE
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def get_data_length(
|
class IECtoOPCUA(StrEnum):
|
||||||
type_name: str,
|
BOOL = "Boolean"
|
||||||
unit: DataUnit = DataUnit.BIT,
|
EBOOL = "Boolean"
|
||||||
udt_lengths: dict[str, int] | None = None,
|
BYTE = "Byte"
|
||||||
round_function: Callable[[float], int] = ceil,
|
WORD = "Word"
|
||||||
unknown_length: any = UNKNOWN_LENGTH,
|
DWORD = "DWord"
|
||||||
) -> any:
|
LWORD = "QWord"
|
||||||
"""Get the length of the specified data type as measured in the specified
|
SINT = "Char"
|
||||||
unit. Returns the value specified by `unknown_length` (default -1) if the
|
INT = "Short"
|
||||||
data type is unknown.
|
DINT = "Long"
|
||||||
"""
|
LINT = "LongLong"
|
||||||
try:
|
USINT = "Byte"
|
||||||
return udt_lengths[type_name] // unit
|
UINT = "Word"
|
||||||
# TypeError is raised if udt_lengths is None; KeyError is raised if
|
UDINT = "DWord"
|
||||||
# `type_name` does not exist in udt_lengths.
|
ULINT = "QWord"
|
||||||
except TypeError, KeyError:
|
REAL = "Float"
|
||||||
pass
|
LREAL = "Double"
|
||||||
try:
|
DATE = "DWord"
|
||||||
return ElementaryTypes[type_name].value.get_length(unit)
|
LDATE = "QWord"
|
||||||
except KeyError:
|
DT = "DWord"
|
||||||
pass
|
LDT = "QWord"
|
||||||
try:
|
TIME = "DWord"
|
||||||
return Array(type_name).get_length(unit)
|
LTIME = "QWord"
|
||||||
except ValueError:
|
TOD = "DWord"
|
||||||
pass
|
LTOD = "QWord"
|
||||||
try:
|
CHAR = "Char"
|
||||||
return String(type_name).get_length(unit)
|
WCHAR = "Word"
|
||||||
except ValueError:
|
STRING = "String"
|
||||||
pass
|
|
||||||
return unknown_length
|
|
||||||
|
class OPCUAtoIEC(Enum):
|
||||||
|
BOOLEAN = IECType("BOOL", IECClass.BINARY, DataUnit.BIT)
|
||||||
|
BYTE = IECType("BYTE", IECClass.BINARY, DataUnit.BYTE)
|
||||||
|
WORD = IECType("WORD", IECClass.BINARY, DataUnit.WORD)
|
||||||
|
DWORD = IECType("DWORD", IECClass.BINARY, DataUnit.DWORD)
|
||||||
|
QWORD = IECType("LWORD", IECClass.BINARY, DataUnit.QWORD)
|
||||||
|
CHAR = IECType("CHAR", IECClass.SIGNED, DataUnit.BYTE)
|
||||||
|
SHORT = IECType("INT", IECClass.SIGNED, DataUnit.WORD)
|
||||||
|
LONG = IECType("DINT", IECClass.SIGNED, DataUnit.DWORD)
|
||||||
|
LONGLONG = IECType("LINT", IECClass.SIGNED, DataUnit.QWORD)
|
||||||
|
FLOAT = IECType("REAL", IECClass.REAL, DataUnit.DWORD)
|
||||||
|
DOUBLE = IECType("LREAL", IECClass.REAL, DataUnit.QWORD)
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ class TestIEC(unittest.TestCase):
|
|||||||
]
|
]
|
||||||
self.udts = [
|
self.udts = [
|
||||||
("KNOWN_UDT", DataUnit.WORD, 10),
|
("KNOWN_UDT", DataUnit.WORD, 10),
|
||||||
("UNKNOWN_UDT", DataUnit.WORD, UNKNOWN_LENGTH),
|
("UNKNOWN_UDT", DataUnit.BIT, UNKNOWN_LENGTH),
|
||||||
]
|
]
|
||||||
self.udt_lengths = {"KNOWN_UDT": 160}
|
self.udt_lengths = {"KNOWN_UDT": 160}
|
||||||
|
|
||||||
@@ -39,9 +39,9 @@ class TestIEC(unittest.TestCase):
|
|||||||
warnings.simplefilter("ignore")
|
warnings.simplefilter("ignore")
|
||||||
for data_type in self.elementary_data_types + self.udts:
|
for data_type in self.elementary_data_types + self.udts:
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
get_data_length(
|
IECType.from_string(
|
||||||
data_type[0], data_type[1], self.udt_lengths
|
data_type[0], self.udt_lengths
|
||||||
),
|
).get_length(data_type[1]),
|
||||||
data_type[2],
|
data_type[2],
|
||||||
data_type[0],
|
data_type[0],
|
||||||
)
|
)
|
||||||
@@ -196,7 +196,7 @@ class TestAddress(unittest.TestCase):
|
|||||||
def test_eq(self):
|
def test_eq(self):
|
||||||
"""Test that the __eq__ method returns False for non-Address `other`."""
|
"""Test that the __eq__ method returns False for non-Address `other`."""
|
||||||
self.assertNotEqual(
|
self.assertNotEqual(
|
||||||
Address(*self.good_specs[0][1]), IECType("test", IECClass.BINARY)
|
Address(*self.good_specs[0][1]), IECType("test", IECClass.BINARY, 1)
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_init(self):
|
def test_init(self):
|
||||||
@@ -241,47 +241,6 @@ class TestAddress(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
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(
|
|
||||||
ElementaryTypes.contains(
|
|
||||||
data_type[0], include_string=False, include_array=False
|
|
||||||
),
|
|
||||||
data_type[1],
|
|
||||||
)
|
|
||||||
for data_type in invalid_types:
|
|
||||||
self.assertFalse(data_type in ElementaryTypes, data_type)
|
|
||||||
|
|
||||||
|
|
||||||
class TestArray(unittest.TestCase):
|
class TestArray(unittest.TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.good_array_specs = [
|
self.good_array_specs = [
|
||||||
@@ -306,27 +265,13 @@ class TestArray(unittest.TestCase):
|
|||||||
"array [5..1] of dint", # Lower bound greater than upper bound
|
"array [5..1] of dint", # Lower bound greater than upper bound
|
||||||
)
|
)
|
||||||
|
|
||||||
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:
|
|
||||||
with self.assertRaises(InvalidSpecError, msg=spec):
|
|
||||||
Array(spec)
|
|
||||||
|
|
||||||
def test_get_length(self):
|
def test_get_length(self):
|
||||||
"""Test get_length for both good and warning array specs."""
|
"""Test get_length for both good and warning array specs."""
|
||||||
with warnings.catch_warnings():
|
with warnings.catch_warnings():
|
||||||
warnings.simplefilter("ignore")
|
warnings.simplefilter("ignore")
|
||||||
for spec in self.good_array_specs + self.warning_array_specs:
|
for spec in self.good_array_specs + self.warning_array_specs:
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
Array(spec[0], round_function=spec[2]).get_length(spec[1]),
|
IECType.from_string(spec[0]).get_length(spec[1], spec[2]),
|
||||||
spec[3],
|
spec[3],
|
||||||
spec[0],
|
spec[0],
|
||||||
)
|
)
|
||||||
@@ -335,48 +280,35 @@ class TestArray(unittest.TestCase):
|
|||||||
with warnings.catch_warnings():
|
with warnings.catch_warnings():
|
||||||
warnings.simplefilter("ignore")
|
warnings.simplefilter("ignore")
|
||||||
for spec in self.good_array_specs + self.warning_array_specs:
|
for spec in self.good_array_specs + self.warning_array_specs:
|
||||||
array = Array(spec[0])
|
array = IECType.from_string(spec[0])
|
||||||
definition = array.make_definition("test_name", "test_comment") # noqa: F841
|
definition = array.array_expansion("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):
|
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]", IECType("STRING[20]", IECClass.CHAR, 160)),
|
||||||
("string [80]\t", DataUnit.BYTE, ceil, 80),
|
("string [80]\t", IECType("string [80]\t", IECClass.CHAR, 640)),
|
||||||
(" string [10] ", DataUnit.BIT, ceil, 80),
|
(" string [10] ", IECType(" string [10] ", IECClass.CHAR, 80)),
|
||||||
]
|
("\tSTRING[15]", IECType("\tSTRING[15]", IECClass.CHAR, 120)),
|
||||||
warning_string_specs = [
|
("STRING [15]", IECType("STRING [15]", IECClass.CHAR, 120)),
|
||||||
("\tSTRING[15]", DataUnit.WORD, ceil, 8),
|
|
||||||
("STRING [15]", DataUnit.WORD, floor, 7),
|
|
||||||
]
|
]
|
||||||
error_string_specs = [
|
error_string_specs = [
|
||||||
("STRNG[20]", DataUnit.WORD, ceil, 10),
|
"STRNG[20]",
|
||||||
("STRING10]", DataUnit.WORD, ceil, 5),
|
"STRING10]",
|
||||||
("string[q]", DataUnit.BYTE, ceil, 0),
|
"string[q]",
|
||||||
("string[]", DataUnit.BIT, ceil, 0),
|
"string[]",
|
||||||
("string[0]", DataUnit.BIT, ceil, 0),
|
"string[0]",
|
||||||
]
|
]
|
||||||
with warnings.catch_warnings():
|
for spec in good_string_specs:
|
||||||
warnings.simplefilter("ignore")
|
|
||||||
for spec in good_string_specs + warning_string_specs:
|
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
String(spec[0], spec[2]).get_length(spec[1]),
|
IECType.from_string(spec[0]),
|
||||||
spec[3],
|
spec[1],
|
||||||
spec[0],
|
spec[0],
|
||||||
)
|
)
|
||||||
for spec in warning_string_specs:
|
|
||||||
self.assertWarns(
|
|
||||||
RuntimeWarning, String(spec[0], spec[2]).get_length, spec[1]
|
|
||||||
)
|
|
||||||
for spec in error_string_specs:
|
for spec in error_string_specs:
|
||||||
with self.assertRaises(InvalidSpecError, msg=spec[0]):
|
with self.assertRaises(InvalidSpecError, msg=spec):
|
||||||
String(spec[0])
|
IECType.from_string(spec, allow_unknown=False)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in New Issue
Block a user