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
|
||||
|
||||
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 warnings
|
||||
from collections.abc import Callable
|
||||
from enum import IntFlag, StrEnum, auto
|
||||
from enum import Enum, StrEnum, auto
|
||||
from math import ceil, prod
|
||||
|
||||
import pandas as pd
|
||||
from numpy import nan
|
||||
|
||||
from AuDaGe.better_enum import AliasEnum, AliasEnumType
|
||||
from AuDaGe.frame import AuDaGeFrame
|
||||
|
||||
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
|
||||
|
||||
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):
|
||||
"""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()
|
||||
SIGNED = auto()
|
||||
UNSIGNED = auto()
|
||||
REAL = auto()
|
||||
DATE = auto()
|
||||
TIME = auto()
|
||||
DT = auto()
|
||||
TIME = 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 IECType:
|
||||
"""A representation of an IEC 61131-3 data type."""
|
||||
|
||||
# Dunder methods
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
iec_class: IECClass,
|
||||
length: int = 0,
|
||||
unit: DataUnit = DataUnit.BIT,
|
||||
round_function: Callable[[float], int] = ceil,
|
||||
length: int,
|
||||
array_bounds: ArrayBounds | None = None,
|
||||
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.iec_class = iec_class
|
||||
self.round = round_function
|
||||
self.length_bits = length * unit
|
||||
self.length = self.get_length
|
||||
self.length = length
|
||||
self.array_bounds = array_bounds
|
||||
self.array_type = array_type
|
||||
|
||||
def __eq__(self, other) -> bool:
|
||||
return all(
|
||||
this == that for this, that in zip(self.__dict__, other.__dict__)
|
||||
)
|
||||
|
||||
# Constructors
|
||||
@classmethod
|
||||
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]
|
||||
|
||||
@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
|
||||
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 | 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))
|
||||
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 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
|
||||
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 from_opcua(self, spec: str):
|
||||
pass
|
||||
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:
|
||||
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):
|
||||
"""Override some of the EnumType methods so that they include aliases."""
|
||||
def array_expansion(self, name: str, comment: str = "") -> AuDaGeFrame:
|
||||
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:
|
||||
"""The default Enum __contains__ method does not include aliases. This
|
||||
one does.
|
||||
# Internal methods
|
||||
@classmethod
|
||||
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)
|
||||
|
||||
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:
|
||||
# Function name for error messages.
|
||||
_name = "IECType._parse_array_spec"
|
||||
# Regular expression for parsing array specifications.
|
||||
SPEC_PATTERN = (
|
||||
# Array declaration: "arr(ay)" with variable whitespace before and
|
||||
@@ -246,174 +236,158 @@ class Array(IECType):
|
||||
# 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 = self.__class__.__name__
|
||||
self.spec = spec
|
||||
match = re.match(self.SPEC_PATTERN, spec, re.IGNORECASE)
|
||||
# Check whether the regex matches at all.
|
||||
if match is None:
|
||||
raise InvalidSpecError(class_name, spec)
|
||||
self.type_name = match.group(2)
|
||||
all_bounds = re.findall(
|
||||
self.BOUNDS_PATTERN, match.group(1), re.IGNORECASE
|
||||
match = re.match(SPEC_PATTERN, spec, re.IGNORECASE)
|
||||
# Check whether the regex matches at all.
|
||||
if match is None:
|
||||
raise InvalidSpecError(_name, spec)
|
||||
data_type = IECType.from_string(match.group(2))
|
||||
all_bounds = re.findall(BOUNDS_PATTERN, match.group(1), re.IGNORECASE)
|
||||
# Check that each dimension's upper bound is greater than or equal
|
||||
# to its lower bound.
|
||||
bounds_paired = tuple(itertools.batched(all_bounds, 2))
|
||||
try:
|
||||
for lbound, ubound in bounds_paired:
|
||||
if int(lbound) > int(ubound):
|
||||
raise InvalidSpecError(
|
||||
_name,
|
||||
spec,
|
||||
"The upper bound of at least one dimension is less "
|
||||
"than its lower bound.",
|
||||
)
|
||||
# ValueError is raised if the array bounds are not coercible to
|
||||
# integers.
|
||||
except ValueError:
|
||||
raise InvalidSpecError(
|
||||
_name,
|
||||
spec,
|
||||
"At least one bound is not an integer.",
|
||||
)
|
||||
# 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,
|
||||
spec,
|
||||
"The upper bound of at least one dimension is less "
|
||||
"than its lower bound.",
|
||||
)
|
||||
# ValueError is raised if the array bounds are not coercible to
|
||||
# integers.
|
||||
except ValueError:
|
||||
raise InvalidSpecError(
|
||||
class_name,
|
||||
spec,
|
||||
"At least one bound is not an integer.",
|
||||
)
|
||||
|
||||
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
|
||||
if data_type.length <= 0:
|
||||
length = UNKNOWN_LENGTH
|
||||
else:
|
||||
# Calculate the length of the array in bits.
|
||||
length_bits = (
|
||||
length = (
|
||||
prod(
|
||||
(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__(
|
||||
spec,
|
||||
IECClass.ARRAY,
|
||||
length_bits,
|
||||
DataUnit.BIT,
|
||||
round_function,
|
||||
*args,
|
||||
**kwargs,
|
||||
return cls(
|
||||
name=spec,
|
||||
iec_class=data_type.iec_class,
|
||||
length=length,
|
||||
array_bounds=bounds_paired,
|
||||
array_type=data_type,
|
||||
)
|
||||
|
||||
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)
|
||||
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):
|
||||
@classmethod
|
||||
def _parse_string_spec(cls, spec: str) -> IECType:
|
||||
"""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)
|
||||
_name = "IECType._parse_string_spec"
|
||||
STRING_SPEC_PATTERN = r"^\s*str(?:ing)?\s*\[(\d+)\]\s*$"
|
||||
match = re.match(STRING_SPEC_PATTERN, spec, re.IGNORECASE)
|
||||
try:
|
||||
length_bytes = int(match.group(1))
|
||||
if length_bytes <= 0:
|
||||
length = int(match.group(1)) * DataUnit.BYTE
|
||||
if length <= 0:
|
||||
raise InvalidSpecError(
|
||||
class_name,
|
||||
_name,
|
||||
spec,
|
||||
"The string length must be greater than zero.",
|
||||
)
|
||||
except AttributeError, ValueError:
|
||||
raise InvalidSpecError(class_name, spec)
|
||||
super().__init__(
|
||||
spec, IECClass.CHAR, length_bytes, DataUnit.BYTE, *args, **kwargs
|
||||
)
|
||||
raise InvalidSpecError(_name, spec)
|
||||
return cls(spec, IECClass.CHAR, length)
|
||||
|
||||
|
||||
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
|
||||
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
|
||||
)
|
||||
|
||||
|
||||
class IECtoOPCUA(StrEnum):
|
||||
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"
|
||||
|
||||
|
||||
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 = [
|
||||
("KNOWN_UDT", DataUnit.WORD, 10),
|
||||
("UNKNOWN_UDT", DataUnit.WORD, UNKNOWN_LENGTH),
|
||||
("UNKNOWN_UDT", DataUnit.BIT, UNKNOWN_LENGTH),
|
||||
]
|
||||
self.udt_lengths = {"KNOWN_UDT": 160}
|
||||
|
||||
@@ -39,9 +39,9 @@ class TestIEC(unittest.TestCase):
|
||||
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
|
||||
),
|
||||
IECType.from_string(
|
||||
data_type[0], self.udt_lengths
|
||||
).get_length(data_type[1]),
|
||||
data_type[2],
|
||||
data_type[0],
|
||||
)
|
||||
@@ -196,7 +196,7 @@ class TestAddress(unittest.TestCase):
|
||||
def test_eq(self):
|
||||
"""Test that the __eq__ method returns False for non-Address `other`."""
|
||||
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):
|
||||
@@ -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):
|
||||
def setUp(self):
|
||||
self.good_array_specs = [
|
||||
@@ -306,27 +265,13 @@ class TestArray(unittest.TestCase):
|
||||
"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):
|
||||
"""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]),
|
||||
IECType.from_string(spec[0]).get_length(spec[1], spec[2]),
|
||||
spec[3],
|
||||
spec[0],
|
||||
)
|
||||
@@ -335,48 +280,35 @@ class TestArray(unittest.TestCase):
|
||||
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") # noqa: F841
|
||||
# definition.to_csv(
|
||||
# resources.files(output).joinpath(
|
||||
# f"array_definition_{str.strip(spec[0])}.csv"
|
||||
# )
|
||||
# )
|
||||
array = IECType.from_string(spec[0])
|
||||
definition = array.array_expansion("test_name", "test_comment") # noqa: F841
|
||||
|
||||
|
||||
class TestString(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),
|
||||
("STRING[20]", IECType("STRING[20]", IECClass.CHAR, 160)),
|
||||
("string [80]\t", IECType("string [80]\t", IECClass.CHAR, 640)),
|
||||
(" string [10] ", IECType(" string [10] ", IECClass.CHAR, 80)),
|
||||
("\tSTRING[15]", IECType("\tSTRING[15]", IECClass.CHAR, 120)),
|
||||
("STRING [15]", IECType("STRING [15]", IECClass.CHAR, 120)),
|
||||
]
|
||||
error_string_specs = [
|
||||
("STRNG[20]", DataUnit.WORD, ceil, 10),
|
||||
("STRING10]", DataUnit.WORD, ceil, 5),
|
||||
("string[q]", DataUnit.BYTE, ceil, 0),
|
||||
("string[]", DataUnit.BIT, ceil, 0),
|
||||
("string[0]", DataUnit.BIT, ceil, 0),
|
||||
"STRNG[20]",
|
||||
"STRING10]",
|
||||
"string[q]",
|
||||
"string[]",
|
||||
"string[0]",
|
||||
]
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
for spec in good_string_specs + warning_string_specs:
|
||||
self.assertEqual(
|
||||
String(spec[0], spec[2]).get_length(spec[1]),
|
||||
spec[3],
|
||||
spec[0],
|
||||
)
|
||||
for spec in warning_string_specs:
|
||||
self.assertWarns(
|
||||
RuntimeWarning, String(spec[0], spec[2]).get_length, spec[1]
|
||||
for spec in good_string_specs:
|
||||
self.assertEqual(
|
||||
IECType.from_string(spec[0]),
|
||||
spec[1],
|
||||
spec[0],
|
||||
)
|
||||
for spec in error_string_specs:
|
||||
with self.assertRaises(InvalidSpecError, msg=spec[0]):
|
||||
String(spec[0])
|
||||
with self.assertRaises(InvalidSpecError, msg=spec):
|
||||
IECType.from_string(spec, allow_unknown=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user