From c0689ed37ab1e59adaa7f4c39790ac106a9b3899 Mon Sep 17 00:00:00 2001 From: radevgit Date: Fri, 5 Dec 2025 12:27:56 +0200 Subject: [PATCH] plcmodel --- Cargo.lock | 11 + Cargo.toml | 2 + iectypes/Cargo.toml | 14 + iectypes/src/data_types.rs | 429 ++++++++++++++++++++++++++++ iectypes/src/keywords.rs | 255 +++++++++++++++++ iectypes/src/lib.rs | 30 ++ iectypes/src/literals.rs | 518 ++++++++++++++++++++++++++++++++++ plcmodel/Cargo.toml | 14 + plcmodel/src/body.rs | 207 ++++++++++++++ plcmodel/src/data_type.rs | 198 +++++++++++++ plcmodel/src/lib.rs | 47 +++ plcmodel/src/pou.rs | 113 ++++++++ plcmodel/src/project.rs | 97 +++++++ plcmodel/src/task.rs | 108 +++++++ plcmodel/src/variable.rs | 90 ++++++ plcmodel/tests/model_tests.rs | 124 ++++++++ 16 files changed, 2257 insertions(+) create mode 100644 iectypes/Cargo.toml create mode 100644 iectypes/src/data_types.rs create mode 100644 iectypes/src/keywords.rs create mode 100644 iectypes/src/lib.rs create mode 100644 iectypes/src/literals.rs create mode 100644 plcmodel/Cargo.toml create mode 100644 plcmodel/src/body.rs create mode 100644 plcmodel/src/data_type.rs create mode 100644 plcmodel/src/lib.rs create mode 100644 plcmodel/src/pou.rs create mode 100644 plcmodel/src/project.rs create mode 100644 plcmodel/src/task.rs create mode 100644 plcmodel/src/variable.rs create mode 100644 plcmodel/tests/model_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 3f88dd8..cd29df4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -141,6 +141,10 @@ dependencies = [ "winnow 0.7.14", ] +[[package]] +name = "iectypes" +version = "0.1.0" + [[package]] name = "indexmap" version = "2.12.1" @@ -217,6 +221,13 @@ dependencies = [ "toml", ] +[[package]] +name = "plcmodel" +version = "0.1.0" +dependencies = [ + "iectypes", +] + [[package]] name = "plcviz" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index 498ea0d..49e35dc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,8 @@ [workspace] resolver = "2" members = [ + "iectypes", + "plcmodel", "l5x", "iecst", "plceye", diff --git a/iectypes/Cargo.toml b/iectypes/Cargo.toml new file mode 100644 index 0000000..ac6f326 --- /dev/null +++ b/iectypes/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "iectypes" +version = "0.1.0" +edition = "2021" +license = "MIT" +publish = false +description = "IEC 61131-3 data types and literals" +repository = "https://github.com/radevgit/plc" +keywords = ["plc", "iec61131", "automation", "industrial"] +categories = ["parsing", "development-tools"] + +[dependencies] + +[dev-dependencies] diff --git a/iectypes/src/data_types.rs b/iectypes/src/data_types.rs new file mode 100644 index 0000000..7ac6106 --- /dev/null +++ b/iectypes/src/data_types.rs @@ -0,0 +1,429 @@ +//! IEC 61131-3 Elementary Data Types +//! +//! Reference: IEC 61131-3, Table 10 - Elementary data types + +use std::fmt; + +/// Elementary data types as defined in IEC 61131-3 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum DataType { + // Boolean + /// Boolean (1 bit) + Bool, + + // Integer types (signed) + /// Signed 8-bit integer (-128 to 127) + SInt, + /// Signed 16-bit integer (-32768 to 32767) + Int, + /// Signed 32-bit integer + DInt, + /// Signed 64-bit integer + LInt, + + // Integer types (unsigned) + /// Unsigned 8-bit integer (0 to 255) + USInt, + /// Unsigned 16-bit integer (0 to 65535) + UInt, + /// Unsigned 32-bit integer + UDInt, + /// Unsigned 64-bit integer + ULInt, + + // Floating point + /// 32-bit floating point (IEEE 754) + Real, + /// 64-bit floating point (IEEE 754) + LReal, + + // Duration + /// Time duration + Time, + /// Long time duration (64-bit) + LTime, + + // Date and time + /// Date (year, month, day) + Date, + /// Long date + LDate, + /// Time of day + TimeOfDay, + /// Long time of day + LTimeOfDay, + /// Date and time combined + DateTime, + /// Long date and time + LDateTime, + + // String types + /// Single-byte character string + String, + /// Wide (Unicode) character string + WString, + /// Single character + Char, + /// Wide character + WChar, + + // Bit string types + /// 8-bit bit string + Byte, + /// 16-bit bit string + Word, + /// 32-bit bit string + DWord, + /// 64-bit bit string + LWord, +} + +impl DataType { + /// Get the size in bits for this data type + pub fn size_bits(&self) -> usize { + match self { + DataType::Bool => 1, + + DataType::SInt | DataType::USInt | DataType::Byte | DataType::Char => 8, + + DataType::Int | DataType::UInt | DataType::Word | DataType::WChar => 16, + + DataType::DInt + | DataType::UDInt + | DataType::DWord + | DataType::Real + | DataType::Time + | DataType::Date + | DataType::TimeOfDay => 32, + + DataType::LInt + | DataType::ULInt + | DataType::LWord + | DataType::LReal + | DataType::LTime + | DataType::LDate + | DataType::LTimeOfDay + | DataType::DateTime + | DataType::LDateTime => 64, + + // Variable size - return 0 or a default + DataType::String | DataType::WString => 0, + } + } + + /// Get the size in bytes for this data type + pub fn size_bytes(&self) -> usize { + let bits = self.size_bits(); + if bits == 0 { + 0 + } else { + (bits + 7) / 8 + } + } + + /// Check if this is a numeric type + pub fn is_numeric(&self) -> bool { + matches!( + self, + DataType::SInt + | DataType::Int + | DataType::DInt + | DataType::LInt + | DataType::USInt + | DataType::UInt + | DataType::UDInt + | DataType::ULInt + | DataType::Real + | DataType::LReal + ) + } + + /// Check if this is an integer type + pub fn is_integer(&self) -> bool { + matches!( + self, + DataType::SInt + | DataType::Int + | DataType::DInt + | DataType::LInt + | DataType::USInt + | DataType::UInt + | DataType::UDInt + | DataType::ULInt + ) + } + + /// Check if this is a signed integer type + pub fn is_signed(&self) -> bool { + matches!( + self, + DataType::SInt | DataType::Int | DataType::DInt | DataType::LInt + ) + } + + /// Check if this is a floating point type + pub fn is_float(&self) -> bool { + matches!(self, DataType::Real | DataType::LReal) + } + + /// Check if this is a bit string type + pub fn is_bit_string(&self) -> bool { + matches!( + self, + DataType::Bool | DataType::Byte | DataType::Word | DataType::DWord | DataType::LWord + ) + } + + /// Check if this is a time-related type + pub fn is_time(&self) -> bool { + matches!( + self, + DataType::Time + | DataType::LTime + | DataType::Date + | DataType::LDate + | DataType::TimeOfDay + | DataType::LTimeOfDay + | DataType::DateTime + | DataType::LDateTime + ) + } + + /// Check if this is a string type + pub fn is_string(&self) -> bool { + matches!( + self, + DataType::String | DataType::WString | DataType::Char | DataType::WChar + ) + } + + /// Parse a data type from its IEC name (case-insensitive) + pub fn from_name(name: &str) -> Option { + match name.to_uppercase().as_str() { + "BOOL" => Some(DataType::Bool), + + "SINT" => Some(DataType::SInt), + "INT" => Some(DataType::Int), + "DINT" => Some(DataType::DInt), + "LINT" => Some(DataType::LInt), + + "USINT" => Some(DataType::USInt), + "UINT" => Some(DataType::UInt), + "UDINT" => Some(DataType::UDInt), + "ULINT" => Some(DataType::ULInt), + + "REAL" => Some(DataType::Real), + "LREAL" => Some(DataType::LReal), + + "TIME" => Some(DataType::Time), + "LTIME" => Some(DataType::LTime), + "DATE" => Some(DataType::Date), + "LDATE" => Some(DataType::LDate), + "TIME_OF_DAY" | "TOD" => Some(DataType::TimeOfDay), + "LTIME_OF_DAY" | "LTOD" => Some(DataType::LTimeOfDay), + "DATE_AND_TIME" | "DT" => Some(DataType::DateTime), + "LDATE_AND_TIME" | "LDT" => Some(DataType::LDateTime), + + "STRING" => Some(DataType::String), + "WSTRING" => Some(DataType::WString), + "CHAR" => Some(DataType::Char), + "WCHAR" => Some(DataType::WChar), + + "BYTE" => Some(DataType::Byte), + "WORD" => Some(DataType::Word), + "DWORD" => Some(DataType::DWord), + "LWORD" => Some(DataType::LWord), + + _ => None, + } + } + + /// Get the IEC name of this data type + pub fn name(&self) -> &'static str { + match self { + DataType::Bool => "BOOL", + + DataType::SInt => "SINT", + DataType::Int => "INT", + DataType::DInt => "DINT", + DataType::LInt => "LINT", + + DataType::USInt => "USINT", + DataType::UInt => "UINT", + DataType::UDInt => "UDINT", + DataType::ULInt => "ULINT", + + DataType::Real => "REAL", + DataType::LReal => "LREAL", + + DataType::Time => "TIME", + DataType::LTime => "LTIME", + DataType::Date => "DATE", + DataType::LDate => "LDATE", + DataType::TimeOfDay => "TIME_OF_DAY", + DataType::LTimeOfDay => "LTIME_OF_DAY", + DataType::DateTime => "DATE_AND_TIME", + DataType::LDateTime => "LDATE_AND_TIME", + + DataType::String => "STRING", + DataType::WString => "WSTRING", + DataType::Char => "CHAR", + DataType::WChar => "WCHAR", + + DataType::Byte => "BYTE", + DataType::Word => "WORD", + DataType::DWord => "DWORD", + DataType::LWord => "LWORD", + } + } +} + +impl fmt::Display for DataType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.name()) + } +} + +/// Variable scope/class as defined in IEC 61131-3 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum VarClass { + /// Local variables (VAR) + Local, + /// Input variables (VAR_INPUT) + Input, + /// Output variables (VAR_OUTPUT) + Output, + /// In/Out variables (VAR_IN_OUT) + InOut, + /// External variables (VAR_EXTERNAL) + External, + /// Global variables (VAR_GLOBAL) + Global, + /// Temporary variables (VAR_TEMP) + Temp, + /// Configuration variables (VAR_CONFIG) + Config, + /// Access variables (VAR_ACCESS) + Access, +} + +impl VarClass { + /// Parse from IEC keyword + pub fn from_keyword(kw: &str) -> Option { + match kw.to_uppercase().as_str() { + "VAR" => Some(VarClass::Local), + "VAR_INPUT" => Some(VarClass::Input), + "VAR_OUTPUT" => Some(VarClass::Output), + "VAR_IN_OUT" => Some(VarClass::InOut), + "VAR_EXTERNAL" => Some(VarClass::External), + "VAR_GLOBAL" => Some(VarClass::Global), + "VAR_TEMP" => Some(VarClass::Temp), + "VAR_CONFIG" => Some(VarClass::Config), + "VAR_ACCESS" => Some(VarClass::Access), + _ => None, + } + } + + /// Get the IEC keyword + pub fn keyword(&self) -> &'static str { + match self { + VarClass::Local => "VAR", + VarClass::Input => "VAR_INPUT", + VarClass::Output => "VAR_OUTPUT", + VarClass::InOut => "VAR_IN_OUT", + VarClass::External => "VAR_EXTERNAL", + VarClass::Global => "VAR_GLOBAL", + VarClass::Temp => "VAR_TEMP", + VarClass::Config => "VAR_CONFIG", + VarClass::Access => "VAR_ACCESS", + } + } +} + +impl fmt::Display for VarClass { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.keyword()) + } +} + +/// POU (Program Organization Unit) type +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PouType { + /// PROGRAM + Program, + /// FUNCTION + Function, + /// FUNCTION_BLOCK + FunctionBlock, +} + +impl PouType { + pub fn from_keyword(kw: &str) -> Option { + match kw.to_uppercase().as_str() { + "PROGRAM" => Some(PouType::Program), + "FUNCTION" => Some(PouType::Function), + "FUNCTION_BLOCK" | "FB" => Some(PouType::FunctionBlock), + _ => None, + } + } + + pub fn keyword(&self) -> &'static str { + match self { + PouType::Program => "PROGRAM", + PouType::Function => "FUNCTION", + PouType::FunctionBlock => "FUNCTION_BLOCK", + } + } +} + +impl fmt::Display for PouType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.keyword()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_data_type_sizes() { + assert_eq!(DataType::Bool.size_bits(), 1); + assert_eq!(DataType::Int.size_bits(), 16); + assert_eq!(DataType::DInt.size_bits(), 32); + assert_eq!(DataType::LReal.size_bits(), 64); + } + + #[test] + fn test_data_type_from_name() { + assert_eq!(DataType::from_name("INT"), Some(DataType::Int)); + assert_eq!(DataType::from_name("int"), Some(DataType::Int)); + assert_eq!(DataType::from_name("DINT"), Some(DataType::DInt)); + assert_eq!(DataType::from_name("TOD"), Some(DataType::TimeOfDay)); + assert_eq!(DataType::from_name("UNKNOWN"), None); + } + + #[test] + fn test_type_categories() { + assert!(DataType::Int.is_integer()); + assert!(DataType::Int.is_numeric()); + assert!(DataType::Int.is_signed()); + + assert!(DataType::UInt.is_integer()); + assert!(!DataType::UInt.is_signed()); + + assert!(DataType::Real.is_float()); + assert!(DataType::Real.is_numeric()); + assert!(!DataType::Real.is_integer()); + + assert!(DataType::Time.is_time()); + assert!(DataType::Word.is_bit_string()); + assert!(DataType::String.is_string()); + } + + #[test] + fn test_var_class() { + assert_eq!(VarClass::from_keyword("VAR_INPUT"), Some(VarClass::Input)); + assert_eq!(VarClass::Input.keyword(), "VAR_INPUT"); + } +} diff --git a/iectypes/src/keywords.rs b/iectypes/src/keywords.rs new file mode 100644 index 0000000..7feff09 --- /dev/null +++ b/iectypes/src/keywords.rs @@ -0,0 +1,255 @@ +//! IEC 61131-3 Reserved Words and Keywords +//! +//! Reference: IEC 61131-3, Annex B - Formal specification + +/// Check if a string is an IEC 61131-3 reserved keyword +pub fn is_keyword(s: &str) -> bool { + KEYWORDS.binary_search(&s.to_uppercase().as_str()).is_ok() +} + +/// Check if a string is a standard function name +pub fn is_standard_function(s: &str) -> bool { + STANDARD_FUNCTIONS + .binary_search(&s.to_uppercase().as_str()) + .is_ok() +} + +/// IEC 61131-3 Reserved Keywords (sorted for binary search) +pub static KEYWORDS: &[&str] = &[ + "ACTION", + "AND", + "ARRAY", + "AT", + "BY", + "CASE", + "CONFIGURATION", + "CONSTANT", + "DATE", + "DATE_AND_TIME", + "DINT", + "DO", + "DT", + "DWORD", + "ELSE", + "ELSIF", + "END_ACTION", + "END_CASE", + "END_CONFIGURATION", + "END_FOR", + "END_FUNCTION", + "END_FUNCTION_BLOCK", + "END_IF", + "END_PROGRAM", + "END_REPEAT", + "END_RESOURCE", + "END_STEP", + "END_STRUCT", + "END_TRANSITION", + "END_TYPE", + "END_VAR", + "END_WHILE", + "EXIT", + "FALSE", + "FOR", + "FROM", + "FUNCTION", + "FUNCTION_BLOCK", + "IF", + "INITIAL_STEP", + "INT", + "INTERVAL", + "LDATE", + "LDATE_AND_TIME", + "LDT", + "LINT", + "LREAL", + "LTIME", + "LTIME_OF_DAY", + "LTOD", + "LWORD", + "MOD", + "NON_RETAIN", + "NOT", + "OF", + "ON", + "OR", + "PRIORITY", + "PROGRAM", + "READ_ONLY", + "READ_WRITE", + "REAL", + "REPEAT", + "RESOURCE", + "RETAIN", + "RETURN", + "SINGLE", + "SINT", + "STEP", + "STRING", + "STRUCT", + "TASK", + "THEN", + "TIME", + "TIME_OF_DAY", + "TO", + "TOD", + "TRANSITION", + "TRUE", + "TYPE", + "UDINT", + "UINT", + "ULINT", + "UNTIL", + "USINT", + "VAR", + "VAR_ACCESS", + "VAR_CONFIG", + "VAR_EXTERNAL", + "VAR_GLOBAL", + "VAR_IN_OUT", + "VAR_INPUT", + "VAR_OUTPUT", + "VAR_TEMP", + "WHILE", + "WITH", + "WORD", + "WSTRING", + "XOR", +]; + +/// Standard Functions (sorted for binary search) +pub static STANDARD_FUNCTIONS: &[&str] = &[ + // Sorted alphabetically for binary_search + "ABS", + "ACOS", + "ADD", + "AND", + "ASIN", + "ATAN", + "BOOL_TO_BYTE", + "BOOL_TO_DINT", + "BOOL_TO_DWORD", + "BOOL_TO_INT", + "BOOL_TO_LINT", + "BOOL_TO_LREAL", + "BOOL_TO_LWORD", + "BOOL_TO_REAL", + "BOOL_TO_SINT", + "BOOL_TO_UDINT", + "BOOL_TO_UINT", + "BOOL_TO_ULINT", + "BOOL_TO_USINT", + "BOOL_TO_WORD", + "BYTE_TO_BOOL", + "BYTE_TO_DINT", + "BYTE_TO_INT", + "BYTE_TO_SINT", + "BYTE_TO_USINT", + "CONCAT", + "COS", + "CTD", + "CTU", + "CTUD", + "DELETE", + "DINT_TO_BOOL", + "DINT_TO_BYTE", + "DINT_TO_INT", + "DINT_TO_REAL", + "DINT_TO_SINT", + "DINT_TO_STRING", + "DIV", + "DWORD_TO_BOOL", + "DWORD_TO_DINT", + "DWORD_TO_REAL", + "EQ", + "EXP", + "EXPT", + "FIND", + "F_TRIG", + "GE", + "GT", + "INSERT", + "INT_TO_BOOL", + "INT_TO_BYTE", + "INT_TO_DINT", + "INT_TO_REAL", + "INT_TO_SINT", + "INT_TO_STRING", + "LE", + "LEFT", + "LEN", + "LIMIT", + "LN", + "LOG", + "LREAL_TO_DINT", + "LREAL_TO_INT", + "LREAL_TO_REAL", + "LREAL_TO_STRING", + "LT", + "MAX", + "MID", + "MIN", + "MOD", + "MOVE", + "MUL", + "MUX", + "NE", + "NEG", + "NOT", + "OR", + "REAL_TO_DINT", + "REAL_TO_INT", + "REAL_TO_LREAL", + "REAL_TO_STRING", + "REPLACE", + "RIGHT", + "ROL", + "ROR", + "RS", + "R_TRIG", + "SEL", + "SHL", + "SHR", + "SIN", + "SINT_TO_BOOL", + "SINT_TO_BYTE", + "SINT_TO_DINT", + "SINT_TO_INT", + "SQRT", + "SR", + "STRING_TO_DINT", + "STRING_TO_INT", + "STRING_TO_LREAL", + "STRING_TO_REAL", + "SUB", + "TAN", + "TOF", + "TON", + "TP", + "TRUNC", + "XOR", +]; + +/// IEC 61131-3 operator keywords +pub static OPERATORS: &[&str] = &["AND", "MOD", "NOT", "OR", "XOR"]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_is_keyword() { + assert!(is_keyword("IF")); + assert!(is_keyword("if")); + assert!(is_keyword("FUNCTION_BLOCK")); + assert!(!is_keyword("myVariable")); + } + + #[test] + fn test_is_standard_function() { + assert!(is_standard_function("ABS")); + assert!(is_standard_function("sin")); + assert!(is_standard_function("TON")); + assert!(!is_standard_function("MyFunc")); + } +} diff --git a/iectypes/src/lib.rs b/iectypes/src/lib.rs new file mode 100644 index 0000000..222c573 --- /dev/null +++ b/iectypes/src/lib.rs @@ -0,0 +1,30 @@ +//! IEC 61131-3 Data Types and Literals +//! +//! This crate provides common IEC 61131-3 type definitions used across +//! PLC programming tools. +//! +//! # Features +//! +//! - **Data Types**: Elementary types (BOOL, INT, REAL, STRING, TIME, etc.) +//! - **Literals**: Parsing of IEC literal formats (T#1s, 16#FF, etc.) +//! - **Keywords**: IEC 61131-3 reserved words +//! +//! # Example +//! +//! ``` +//! use iectypes::{DataType, TimeLiteral}; +//! +//! let dt = DataType::Int; +//! assert_eq!(dt.size_bits(), 16); +//! +//! let time = TimeLiteral::parse("T#1s500ms").unwrap(); +//! assert_eq!(time.to_milliseconds(), 1500); +//! ``` + +mod data_types; +mod keywords; +mod literals; + +pub use data_types::*; +pub use keywords::*; +pub use literals::*; diff --git a/iectypes/src/literals.rs b/iectypes/src/literals.rs new file mode 100644 index 0000000..5af64ca --- /dev/null +++ b/iectypes/src/literals.rs @@ -0,0 +1,518 @@ +//! IEC 61131-3 Literal Parsing +//! +//! Parses IEC literal formats: +//! - Time: T#1d2h3m4s5ms, TIME#500ms +//! - Numeric: 16#FF, 2#1010, 8#77 +//! - Typed: INT#100, REAL#3.14 + +use std::fmt; + +/// Time duration literal (T#, TIME#) +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct TimeLiteral { + /// Days + pub days: u32, + /// Hours + pub hours: u32, + /// Minutes + pub minutes: u32, + /// Seconds + pub seconds: u32, + /// Milliseconds + pub milliseconds: u32, + /// Microseconds + pub microseconds: u32, + /// Nanoseconds + pub nanoseconds: u32, + /// Negative duration + pub negative: bool, +} + +impl TimeLiteral { + /// Create a new zero duration + pub fn zero() -> Self { + Self::default() + } + + /// Create from milliseconds + pub fn from_milliseconds(ms: i64) -> Self { + let negative = ms < 0; + let ms = ms.unsigned_abs(); + + let days = (ms / (24 * 60 * 60 * 1000)) as u32; + let remaining = ms % (24 * 60 * 60 * 1000); + let hours = (remaining / (60 * 60 * 1000)) as u32; + let remaining = remaining % (60 * 60 * 1000); + let minutes = (remaining / (60 * 1000)) as u32; + let remaining = remaining % (60 * 1000); + let seconds = (remaining / 1000) as u32; + let milliseconds = (remaining % 1000) as u32; + + Self { + days, + hours, + minutes, + seconds, + milliseconds, + microseconds: 0, + nanoseconds: 0, + negative, + } + } + + /// Convert to total milliseconds + pub fn to_milliseconds(&self) -> i64 { + let ms = self.days as i64 * 24 * 60 * 60 * 1000 + + self.hours as i64 * 60 * 60 * 1000 + + self.minutes as i64 * 60 * 1000 + + self.seconds as i64 * 1000 + + self.milliseconds as i64; + + if self.negative { -ms } else { ms } + } + + /// Convert to total microseconds + pub fn to_microseconds(&self) -> i64 { + self.to_milliseconds() * 1000 + self.microseconds as i64 + } + + /// Convert to total nanoseconds + pub fn to_nanoseconds(&self) -> i128 { + self.to_microseconds() as i128 * 1000 + self.nanoseconds as i128 + } + + /// Parse a time literal string (T#1s, TIME#500ms, etc.) + pub fn parse(s: &str) -> Result { + let s = s.trim(); + + // Check prefix + let content = if let Some(rest) = s.strip_prefix("T#") { + rest + } else if let Some(rest) = s.strip_prefix("TIME#") { + rest + } else if let Some(rest) = s.strip_prefix("t#") { + rest + } else if let Some(rest) = s.strip_prefix("time#") { + rest + } else { + return Err(LiteralError::InvalidPrefix("T# or TIME#")); + }; + + // Check for negative + let (negative, content) = if let Some(rest) = content.strip_prefix('-') { + (true, rest) + } else { + (false, content) + }; + + let mut result = TimeLiteral { + negative, + ..Default::default() + }; + + // Parse components: 1d2h3m4s5ms6us7ns + let mut chars = content.chars().peekable(); + let mut num_str = String::new(); + + while let Some(c) = chars.next() { + if c.is_ascii_digit() || c == '.' || c == '_' { + if c != '_' { + num_str.push(c); + } + } else { + // Got a unit character + let unit = if c == 'm' || c == 'u' || c == 'n' { + // Could be ms, us, ns, or just m (minutes) or s + let mut unit = String::from(c); + if let Some(&next) = chars.peek() { + if next == 's' { + unit.push(chars.next().unwrap()); + } + } + unit + } else { + c.to_string() + }; + + if num_str.is_empty() { + continue; + } + + let value: f64 = num_str + .parse() + .map_err(|_| LiteralError::InvalidNumber(num_str.clone()))?; + + match unit.as_str() { + "d" => result.days = value as u32, + "h" => result.hours = value as u32, + "m" => result.minutes = value as u32, + "s" => { + result.seconds = value as u32; + // Handle fractional seconds + let frac = value - value.floor(); + if frac > 0.0 { + result.milliseconds = (frac * 1000.0) as u32; + } + } + "ms" => result.milliseconds = value as u32, + "us" => result.microseconds = value as u32, + "ns" => result.nanoseconds = value as u32, + _ => return Err(LiteralError::InvalidUnit(unit)), + } + + num_str.clear(); + } + } + + Ok(result) + } +} + +impl fmt::Display for TimeLiteral { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "T#")?; + if self.negative { + write!(f, "-")?; + } + let mut has_output = false; + if self.days > 0 { + write!(f, "{}d", self.days)?; + has_output = true; + } + if self.hours > 0 { + write!(f, "{}h", self.hours)?; + has_output = true; + } + if self.minutes > 0 { + write!(f, "{}m", self.minutes)?; + has_output = true; + } + if self.seconds > 0 || self.milliseconds > 0 { + if self.milliseconds > 0 { + write!(f, "{}s{}ms", self.seconds, self.milliseconds)?; + } else { + write!(f, "{}s", self.seconds)?; + } + has_output = true; + } + if self.microseconds > 0 { + write!(f, "{}us", self.microseconds)?; + has_output = true; + } + if self.nanoseconds > 0 { + write!(f, "{}ns", self.nanoseconds)?; + has_output = true; + } + if !has_output { + write!(f, "0s")?; + } + Ok(()) + } +} + +/// Numeric literal with optional base +#[derive(Debug, Clone, PartialEq)] +pub enum NumericLiteral { + /// Integer value + Integer(i64), + /// Floating point value + Real(f64), +} + +impl NumericLiteral { + /// Parse a numeric literal (supports 2#, 8#, 16# prefixes) + pub fn parse(s: &str) -> Result { + let s = s.trim().replace('_', ""); + + // Check for base prefix + if let Some(rest) = s.strip_prefix("16#") { + let value = i64::from_str_radix(rest, 16) + .map_err(|_| LiteralError::InvalidNumber(s.clone()))?; + return Ok(NumericLiteral::Integer(value)); + } + if let Some(rest) = s.strip_prefix("8#") { + let value = + i64::from_str_radix(rest, 8).map_err(|_| LiteralError::InvalidNumber(s.clone()))?; + return Ok(NumericLiteral::Integer(value)); + } + if let Some(rest) = s.strip_prefix("2#") { + let value = + i64::from_str_radix(rest, 2).map_err(|_| LiteralError::InvalidNumber(s.clone()))?; + return Ok(NumericLiteral::Integer(value)); + } + + // Check for float + if s.contains('.') || s.contains('e') || s.contains('E') { + let value: f64 = s.parse().map_err(|_| LiteralError::InvalidNumber(s))?; + return Ok(NumericLiteral::Real(value)); + } + + // Plain integer + let value: i64 = s.parse().map_err(|_| LiteralError::InvalidNumber(s))?; + Ok(NumericLiteral::Integer(value)) + } +} + +/// Direct address (I/O addressing) +/// Examples: %IX0.0, %QW10, %MD100 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DirectAddress { + /// Memory area: I (input), Q (output), M (memory) + pub area: MemoryArea, + /// Size: X (bit), B (byte), W (word), D (dword), L (lword) + pub size: MemorySize, + /// Address (byte offset) + pub address: u32, + /// Bit offset (for bit access) + pub bit: Option, +} + +/// Memory area for direct addressing +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MemoryArea { + /// Input (%I) + Input, + /// Output (%Q) + Output, + /// Memory/Marker (%M) + Memory, +} + +/// Memory size for direct addressing +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MemorySize { + /// Bit (X) + Bit, + /// Byte (B) + Byte, + /// Word (W) - 16 bits + Word, + /// Double word (D) - 32 bits + DWord, + /// Long word (L) - 64 bits + LWord, +} + +impl DirectAddress { + /// Parse a direct address string (%IX0.0, %QW10, etc.) + pub fn parse(s: &str) -> Result { + let s = s.trim(); + + if !s.starts_with('%') { + return Err(LiteralError::InvalidPrefix("%")); + } + + let s = &s[1..]; + let mut chars = s.chars(); + + // Parse area + let area = match chars.next() { + Some('I') | Some('i') => MemoryArea::Input, + Some('Q') | Some('q') => MemoryArea::Output, + Some('M') | Some('m') => MemoryArea::Memory, + _ => return Err(LiteralError::InvalidMemoryArea), + }; + + // Parse size (optional, default is bit for I/Q, byte for M) + let next = chars.next().ok_or(LiteralError::InvalidAddress)?; + let (size, first_digit) = match next { + 'X' | 'x' => (MemorySize::Bit, chars.next()), + 'B' | 'b' => (MemorySize::Byte, chars.next()), + 'W' | 'w' => (MemorySize::Word, chars.next()), + 'D' | 'd' => (MemorySize::DWord, chars.next()), + 'L' | 'l' => (MemorySize::LWord, chars.next()), + c if c.is_ascii_digit() => (MemorySize::Bit, Some(c)), + _ => return Err(LiteralError::InvalidMemorySize), + }; + + // Parse address + let mut addr_str = String::new(); + if let Some(c) = first_digit { + addr_str.push(c); + } + for c in chars { + if c == '.' { + break; + } + addr_str.push(c); + } + + let address: u32 = addr_str + .parse() + .map_err(|_| LiteralError::InvalidAddress)?; + + // Parse bit offset if present + let bit = if s.contains('.') { + let parts: Vec<&str> = s.split('.').collect(); + if parts.len() == 2 { + Some( + parts[1] + .parse() + .map_err(|_| LiteralError::InvalidAddress)?, + ) + } else { + None + } + } else { + None + }; + + Ok(DirectAddress { + area, + size, + address, + bit, + }) + } +} + +impl fmt::Display for DirectAddress { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let area = match self.area { + MemoryArea::Input => 'I', + MemoryArea::Output => 'Q', + MemoryArea::Memory => 'M', + }; + let size = match self.size { + MemorySize::Bit => 'X', + MemorySize::Byte => 'B', + MemorySize::Word => 'W', + MemorySize::DWord => 'D', + MemorySize::LWord => 'L', + }; + + if let Some(bit) = self.bit { + write!(f, "%{}{}{}.{}", area, size, self.address, bit) + } else { + write!(f, "%{}{}{}", area, size, self.address) + } + } +} + +/// Error type for literal parsing +#[derive(Debug, Clone, PartialEq)] +pub enum LiteralError { + /// Invalid prefix (expected T#, TIME#, etc.) + InvalidPrefix(&'static str), + /// Invalid number format + InvalidNumber(String), + /// Invalid unit (expected d, h, m, s, ms, etc.) + InvalidUnit(String), + /// Invalid memory area + InvalidMemoryArea, + /// Invalid memory size + InvalidMemorySize, + /// Invalid address format + InvalidAddress, +} + +impl fmt::Display for LiteralError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LiteralError::InvalidPrefix(expected) => { + write!(f, "invalid prefix, expected {}", expected) + } + LiteralError::InvalidNumber(s) => write!(f, "invalid number: {}", s), + LiteralError::InvalidUnit(s) => write!(f, "invalid unit: {}", s), + LiteralError::InvalidMemoryArea => write!(f, "invalid memory area (expected I, Q, M)"), + LiteralError::InvalidMemorySize => { + write!(f, "invalid memory size (expected X, B, W, D, L)") + } + LiteralError::InvalidAddress => write!(f, "invalid address format"), + } + } +} + +impl std::error::Error for LiteralError {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_time_literal_parse() { + let t = TimeLiteral::parse("T#1s").unwrap(); + assert_eq!(t.seconds, 1); + assert_eq!(t.to_milliseconds(), 1000); + + let t = TimeLiteral::parse("T#1s500ms").unwrap(); + assert_eq!(t.seconds, 1); + assert_eq!(t.milliseconds, 500); + assert_eq!(t.to_milliseconds(), 1500); + + let t = TimeLiteral::parse("TIME#1d2h3m4s").unwrap(); + assert_eq!(t.days, 1); + assert_eq!(t.hours, 2); + assert_eq!(t.minutes, 3); + assert_eq!(t.seconds, 4); + + let t = TimeLiteral::parse("T#-500ms").unwrap(); + assert!(t.negative); + assert_eq!(t.to_milliseconds(), -500); + } + + #[test] + fn test_time_literal_display() { + let t = TimeLiteral::from_milliseconds(1500); + assert_eq!(t.to_string(), "T#1s500ms"); + } + + #[test] + fn test_numeric_literal_parse() { + assert_eq!( + NumericLiteral::parse("100").unwrap(), + NumericLiteral::Integer(100) + ); + assert_eq!( + NumericLiteral::parse("16#FF").unwrap(), + NumericLiteral::Integer(255) + ); + assert_eq!( + NumericLiteral::parse("2#1010").unwrap(), + NumericLiteral::Integer(10) + ); + assert_eq!( + NumericLiteral::parse("8#77").unwrap(), + NumericLiteral::Integer(63) + ); + assert_eq!( + NumericLiteral::parse("3.14").unwrap(), + NumericLiteral::Real(3.14) + ); + assert_eq!( + NumericLiteral::parse("1_000_000").unwrap(), + NumericLiteral::Integer(1000000) + ); + } + + #[test] + fn test_direct_address_parse() { + let addr = DirectAddress::parse("%IX0.0").unwrap(); + assert_eq!(addr.area, MemoryArea::Input); + assert_eq!(addr.size, MemorySize::Bit); + assert_eq!(addr.address, 0); + assert_eq!(addr.bit, Some(0)); + + let addr = DirectAddress::parse("%QW10").unwrap(); + assert_eq!(addr.area, MemoryArea::Output); + assert_eq!(addr.size, MemorySize::Word); + assert_eq!(addr.address, 10); + assert_eq!(addr.bit, None); + + let addr = DirectAddress::parse("%MD100").unwrap(); + assert_eq!(addr.area, MemoryArea::Memory); + assert_eq!(addr.size, MemorySize::DWord); + assert_eq!(addr.address, 100); + } + + #[test] + fn test_direct_address_display() { + let addr = DirectAddress { + area: MemoryArea::Input, + size: MemorySize::Bit, + address: 0, + bit: Some(5), + }; + assert_eq!(addr.to_string(), "%IX0.5"); + } +} diff --git a/plcmodel/Cargo.toml b/plcmodel/Cargo.toml new file mode 100644 index 0000000..87c287a --- /dev/null +++ b/plcmodel/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "plcmodel" +version = "0.1.0" +edition = "2024" +rust-version = "1.85" +publish = false +description = "Vendor-neutral PLC model for IEC 61131-3 programs" +license = "MIT" +repository = "https://github.com/radevgit/plc" +keywords = ["plc", "iec-61131", "automation", "industrial"] +categories = ["data-structures", "parser-implementations"] + +[dependencies] +iectypes = { path = "../iectypes" } diff --git a/plcmodel/src/body.rs b/plcmodel/src/body.rs new file mode 100644 index 0000000..83d09c1 --- /dev/null +++ b/plcmodel/src/body.rs @@ -0,0 +1,207 @@ +//! Program body representations. + +/// The body/implementation of a POU. +/// +/// Different PLC programming languages have different representations, +/// but we normalize them for analysis purposes. +#[derive(Debug, Clone)] +pub enum Body { + /// Structured Text + St(String), + + /// Instruction List + Il(String), + + /// Ladder Diagram (normalized to rungs) + Ld(Vec), + + /// Function Block Diagram (normalized to networks) + Fbd(Vec), + + /// Sequential Function Chart + Sfc(SfcBody), + + /// Raw/unparsed content (for unknown formats) + Raw { language: String, content: String }, +} + +impl Body { + /// Check if the body is empty. + pub fn is_empty(&self) -> bool { + match self { + Body::St(s) | Body::Il(s) => s.trim().is_empty(), + Body::Ld(rungs) => rungs.is_empty(), + Body::Fbd(networks) => networks.is_empty(), + Body::Sfc(sfc) => sfc.steps.is_empty(), + Body::Raw { content, .. } => content.trim().is_empty(), + } + } + + /// Get the language name. + pub fn language(&self) -> &str { + match self { + Body::St(_) => "ST", + Body::Il(_) => "IL", + Body::Ld(_) => "LD", + Body::Fbd(_) => "FBD", + Body::Sfc(_) => "SFC", + Body::Raw { language, .. } => language, + } + } +} + +/// A ladder diagram rung. +#[derive(Debug, Clone)] +pub struct Rung { + /// Rung number (0-indexed) + pub number: u32, + + /// Optional rung comment + pub comment: Option, + + /// Instructions in this rung + pub instructions: Vec, + + /// Raw text representation (if available) + pub raw_text: Option, +} + +impl Rung { + /// Create an empty rung. + pub fn new(number: u32) -> Self { + Self { + number, + comment: None, + instructions: Vec::new(), + raw_text: None, + } + } +} + +/// An instruction within a rung or network. +#[derive(Debug, Clone)] +pub struct Instruction { + /// Instruction mnemonic (XIC, OTE, TON, etc.) + pub mnemonic: String, + + /// Operands/parameters + pub operands: Vec, + + /// Source position (if available) + pub position: Option, +} + +impl Instruction { + /// Create a simple instruction. + pub fn new(mnemonic: impl Into) -> Self { + Self { + mnemonic: mnemonic.into(), + operands: Vec::new(), + position: None, + } + } + + /// Add an operand. + pub fn with_operand(mut self, operand: Operand) -> Self { + self.operands.push(operand); + self + } +} + +/// An operand to an instruction. +#[derive(Debug, Clone)] +pub enum Operand { + /// Tag/variable reference + Tag(String), + + /// Literal value + Literal(String), + + /// Nested expression + Expression(String), +} + +/// Position in source. +#[derive(Debug, Clone, Copy)] +pub struct Position { + /// Rung or network number + pub rung: u32, + /// Position within the rung + pub column: u32, +} + +/// A FBD network. +#[derive(Debug, Clone)] +pub struct Network { + /// Network number + pub number: u32, + + /// Optional network comment/label + pub label: Option, + + /// Instructions/blocks in this network + pub instructions: Vec, +} + +impl Network { + /// Create an empty network. + pub fn new(number: u32) -> Self { + Self { + number, + label: None, + instructions: Vec::new(), + } + } +} + +/// Sequential Function Chart body. +#[derive(Debug, Clone, Default)] +pub struct SfcBody { + /// Steps in the SFC + pub steps: Vec, + + /// Transitions between steps + pub transitions: Vec, +} + +/// An SFC step. +#[derive(Debug, Clone)] +pub struct SfcStep { + /// Step name + pub name: String, + + /// Is this the initial step? + pub is_initial: bool, + + /// Actions associated with this step + pub actions: Vec, +} + +/// An action within an SFC step. +#[derive(Debug, Clone)] +pub struct SfcAction { + /// Action name + pub name: String, + + /// Action qualifier (N, S, R, P, etc.) + pub qualifier: String, + + /// Action body + pub body: Option>, +} + +/// An SFC transition. +#[derive(Debug, Clone)] +pub struct SfcTransition { + /// Transition name (optional) + pub name: Option, + + /// Source step(s) + pub from_steps: Vec, + + /// Target step(s) + pub to_steps: Vec, + + /// Transition condition + pub condition: String, +} diff --git a/plcmodel/src/data_type.rs b/plcmodel/src/data_type.rs new file mode 100644 index 0000000..7564e36 --- /dev/null +++ b/plcmodel/src/data_type.rs @@ -0,0 +1,198 @@ +//! User-defined data type definitions. + +/// A user-defined data type. +/// +/// Maps to: +/// - L5X: `` elements +/// - PLCopen: `` within `/` +#[derive(Debug, Clone)] +pub struct DataTypeDef { + /// Type name + pub name: String, + + /// Optional description + pub description: Option, + + /// The actual type definition + pub kind: DataTypeKind, +} + +/// The kind of user-defined type. +#[derive(Debug, Clone)] +pub enum DataTypeKind { + /// Alias to another type + Alias(String), + + /// Structure with named members + Struct(StructDef), + + /// Enumeration + Enum(EnumDef), + + /// Array type + Array(ArrayDef), + + /// Subrange type (INTEGER 0..100) + Subrange { + base_type: String, + lower: i64, + upper: i64, + }, +} + +impl DataTypeDef { + /// Create a struct type. + pub fn structure(name: impl Into, members: Vec) -> Self { + Self { + name: name.into(), + description: None, + kind: DataTypeKind::Struct(StructDef { members }), + } + } + + /// Create an enum type. + pub fn enumeration(name: impl Into, members: Vec) -> Self { + Self { + name: name.into(), + description: None, + kind: DataTypeKind::Enum(EnumDef { + base_type: None, + members, + }), + } + } + + /// Create an alias type. + pub fn alias(name: impl Into, target: impl Into) -> Self { + Self { + name: name.into(), + description: None, + kind: DataTypeKind::Alias(target.into()), + } + } +} + +/// Structure definition. +#[derive(Debug, Clone, Default)] +pub struct StructDef { + /// Structure members + pub members: Vec, +} + +/// A member of a structure. +#[derive(Debug, Clone)] +pub struct StructMember { + /// Member name + pub name: String, + + /// Data type + pub data_type: String, + + /// Initial value + pub initial_value: Option, + + /// Description + pub description: Option, + + /// Array dimensions (empty for scalar) + pub dimensions: Vec, +} + +impl StructMember { + /// Create a simple struct member. + pub fn new(name: impl Into, data_type: impl Into) -> Self { + Self { + name: name.into(), + data_type: data_type.into(), + initial_value: None, + description: None, + dimensions: Vec::new(), + } + } +} + +/// Enumeration definition. +#[derive(Debug, Clone, Default)] +pub struct EnumDef { + /// Base type (default DINT for most PLCs) + pub base_type: Option, + + /// Enumeration members + pub members: Vec, +} + +/// A member of an enumeration. +#[derive(Debug, Clone)] +pub struct EnumMember { + /// Member name + pub name: String, + + /// Explicit value (if specified) + pub value: Option, + + /// Description + pub description: Option, +} + +impl EnumMember { + /// Create an enum member. + pub fn new(name: impl Into) -> Self { + Self { + name: name.into(), + value: None, + description: None, + } + } + + /// Create an enum member with explicit value. + pub fn with_value(name: impl Into, value: i64) -> Self { + Self { + name: name.into(), + value: Some(value), + description: None, + } + } +} + +/// Array type definition. +#[derive(Debug, Clone)] +pub struct ArrayDef { + /// Element type + pub element_type: String, + + /// Dimensions with bounds + pub dimensions: Vec, +} + +/// An array dimension with lower and upper bounds. +#[derive(Debug, Clone)] +pub struct ArrayDimension { + /// Lower bound (usually 0 or 1) + pub lower: i32, + + /// Upper bound + pub upper: i32, +} + +impl ArrayDimension { + /// Create a zero-based dimension [0..size-1] + pub fn zero_based(size: u32) -> Self { + Self { + lower: 0, + upper: size as i32 - 1, + } + } + + /// Create a one-based dimension [1..size] + pub fn one_based(size: u32) -> Self { + Self { + lower: 1, + upper: size as i32, + } + } + + /// Get the size of this dimension. + pub fn size(&self) -> u32 { + (self.upper - self.lower + 1) as u32 + } +} diff --git a/plcmodel/src/lib.rs b/plcmodel/src/lib.rs new file mode 100644 index 0000000..2cc2d1d --- /dev/null +++ b/plcmodel/src/lib.rs @@ -0,0 +1,47 @@ +//! # plcmodel +//! +//! Vendor-neutral PLC model for IEC 61131-3 programs. +//! +//! This crate provides abstract representations that different PLC formats +//! (L5X, PLCopen XML, etc.) can map to, enabling format-independent analysis. +//! +//! ## Architecture +//! +//! ```text +//! ┌─────────┐ ┌─────────────┐ ┌──────────┐ +//! │ L5X │────▶│ │────▶│ plceye │ +//! └─────────┘ │ PlcModel │ │ analysis │ +//! ┌─────────┐ │ │ └──────────┘ +//! │ PLCopen │────▶│ │────▶│ plcviz │ +//! └─────────┘ └─────────────┘ └──────────┘ +//! ``` +//! +//! ## Key Types +//! +//! - [`Project`] - Top-level container for all PLC configuration +//! - [`Pou`] - Program Organization Unit (Program, Function, FunctionBlock) +//! - [`Variable`] - Variables with scope and data type +//! - [`DataTypeDef`] - User-defined types (struct, enum, array) +//! - [`Task`] - Task configuration for scheduling + +mod body; +mod data_type; +mod pou; +mod project; +mod task; +mod variable; + +pub use body::{Body, Instruction, Network, Operand, Position, Rung, SfcAction, SfcBody, SfcStep, SfcTransition}; +pub use data_type::{ArrayDef, ArrayDimension, DataTypeDef, DataTypeKind, EnumDef, EnumMember, StructDef, StructMember}; +pub use pou::{Pou, PouInterface}; +pub use project::{Configuration, Project, Resource}; +pub use task::{Task, TaskTrigger}; +pub use variable::Variable; + +/// Trait for types that can be converted to the common PLC model. +/// +/// Implemented by format-specific parsers (L5X, PLCopen, etc.) +pub trait ToPlcModel { + /// Convert this type to a vendor-neutral [`Project`]. + fn to_plc_model(&self) -> Project; +} diff --git a/plcmodel/src/pou.rs b/plcmodel/src/pou.rs new file mode 100644 index 0000000..04d15bf --- /dev/null +++ b/plcmodel/src/pou.rs @@ -0,0 +1,113 @@ +//! Program Organization Unit (POU) definitions. + +use crate::{Body, Variable}; +use iectypes::PouType; + +/// A Program Organization Unit. +/// +/// POUs are the building blocks of IEC 61131-3 programs: +/// - **Program**: Stateful, scheduled by tasks +/// - **Function Block**: Stateful, instantiated and called +/// - **Function**: Stateless, returns a value +/// +/// Maps to: +/// - L5X: `` for Programs, `` for FBs +/// - PLCopen: `` element with pouType attribute +#[derive(Debug, Clone)] +pub struct Pou { + /// POU name (identifier) + pub name: String, + + /// Type: Program, Function, or FunctionBlock + pub pou_type: PouType, + + /// Optional description + pub description: Option, + + /// Interface (variable declarations) + pub interface: PouInterface, + + /// Program body (the actual code) + pub body: Option, +} + +impl Pou { + /// Create a new POU with the given name and type. + pub fn new(name: impl Into, pou_type: PouType) -> Self { + Self { + name: name.into(), + pou_type, + description: None, + interface: PouInterface::default(), + body: None, + } + } + + /// Check if this POU has any code. + pub fn is_empty(&self) -> bool { + self.body.as_ref().is_none_or(|b| b.is_empty()) + } + + /// Get all variables (input, output, local, etc.) + pub fn all_variables(&self) -> impl Iterator { + self.interface.all_variables() + } + + /// Find a variable by name. + pub fn find_variable(&self, name: &str) -> Option<&Variable> { + self.interface.find_variable(name) + } +} + +/// Interface section of a POU - variable declarations grouped by scope. +#[derive(Debug, Clone, Default)] +pub struct PouInterface { + /// Input parameters (VAR_INPUT) + pub inputs: Vec, + + /// Output parameters (VAR_OUTPUT) + pub outputs: Vec, + + /// In/Out parameters (VAR_IN_OUT) + pub in_outs: Vec, + + /// Local variables (VAR) + pub locals: Vec, + + /// Temporary variables (VAR_TEMP) + pub temps: Vec, + + /// External references (VAR_EXTERNAL) + pub externals: Vec, + + /// Return type for Functions + pub return_type: Option, +} + +impl PouInterface { + /// Get all variables across all scopes. + pub fn all_variables(&self) -> impl Iterator { + self.inputs + .iter() + .chain(self.outputs.iter()) + .chain(self.in_outs.iter()) + .chain(self.locals.iter()) + .chain(self.temps.iter()) + .chain(self.externals.iter()) + } + + /// Find a variable by name in any scope. + pub fn find_variable(&self, name: &str) -> Option<&Variable> { + self.all_variables().find(|v| v.name == name) + } + + /// Total variable count. + pub fn variable_count(&self) -> usize { + self.inputs.len() + + self.outputs.len() + + self.in_outs.len() + + self.locals.len() + + self.temps.len() + + self.externals.len() + } +} diff --git a/plcmodel/src/project.rs b/plcmodel/src/project.rs new file mode 100644 index 0000000..6992bfe --- /dev/null +++ b/plcmodel/src/project.rs @@ -0,0 +1,97 @@ +//! Project and configuration structures. + +use crate::{DataTypeDef, Pou, Task}; + +/// A PLC project - top-level container. +/// +/// Maps to: +/// - L5X: `` with `` +/// - PLCopen: `` element +#[derive(Debug, Clone, Default)] +pub struct Project { + /// Project name + pub name: String, + + /// Optional description + pub description: Option, + + /// User-defined data types + pub data_types: Vec, + + /// Program Organization Units (Programs, Functions, FBs) + pub pous: Vec, + + /// Configuration (hardware, tasks, resources) + pub configuration: Option, + + /// Source format (e.g., "L5X", "PLCopen") + pub source_format: Option, +} + +impl Project { + /// Create an empty project with the given name. + pub fn new(name: impl Into) -> Self { + Self { + name: name.into(), + ..Default::default() + } + } + + /// Find a POU by name. + pub fn find_pou(&self, name: &str) -> Option<&Pou> { + self.pous.iter().find(|p| p.name == name) + } + + /// Find a data type definition by name. + pub fn find_data_type(&self, name: &str) -> Option<&DataTypeDef> { + self.data_types.iter().find(|dt| dt.name == name) + } + + /// Get all programs (POUs with type Program). + pub fn programs(&self) -> impl Iterator { + self.pous + .iter() + .filter(|p| matches!(p.pou_type, iectypes::PouType::Program)) + } + + /// Get all function blocks. + pub fn function_blocks(&self) -> impl Iterator { + self.pous + .iter() + .filter(|p| matches!(p.pou_type, iectypes::PouType::FunctionBlock)) + } + + /// Get all functions. + pub fn functions(&self) -> impl Iterator { + self.pous + .iter() + .filter(|p| matches!(p.pou_type, iectypes::PouType::Function)) + } +} + +/// Hardware/resource configuration. +/// +/// Maps to: +/// - L5X: Controller modules and tasks +/// - PLCopen: `` element +#[derive(Debug, Clone, Default)] +pub struct Configuration { + /// Configuration name + pub name: String, + + /// Resources (CPUs/PLCs in the configuration) + pub resources: Vec, +} + +/// A resource within a configuration (typically a PLC or CPU). +#[derive(Debug, Clone, Default)] +pub struct Resource { + /// Resource name + pub name: String, + + /// Tasks scheduled on this resource + pub tasks: Vec, + + /// Global variables for this resource + pub global_vars: Vec, +} diff --git a/plcmodel/src/task.rs b/plcmodel/src/task.rs new file mode 100644 index 0000000..59ee670 --- /dev/null +++ b/plcmodel/src/task.rs @@ -0,0 +1,108 @@ +//! Task configuration. + +/// A task definition for scheduling POUs. +/// +/// Maps to: +/// - L5X: `` elements +/// - PLCopen: `` within resources +#[derive(Debug, Clone)] +pub struct Task { + /// Task name + pub name: String, + + /// Optional description + pub description: Option, + + /// Task priority (lower = higher priority, typically 1-15) + pub priority: u8, + + /// What triggers the task + pub trigger: TaskTrigger, + + /// Watchdog time in milliseconds + pub watchdog_ms: Option, + + /// Programs assigned to this task + pub programs: Vec, +} + +impl Task { + /// Create a periodic task. + pub fn periodic(name: impl Into, period_ms: u32) -> Self { + Self { + name: name.into(), + description: None, + priority: 10, + trigger: TaskTrigger::Periodic { period_ms }, + watchdog_ms: None, + programs: Vec::new(), + } + } + + /// Create a continuous task. + pub fn continuous(name: impl Into) -> Self { + Self { + name: name.into(), + description: None, + priority: 15, // Lowest priority + trigger: TaskTrigger::Continuous, + watchdog_ms: None, + programs: Vec::new(), + } + } + + /// Create an event-triggered task. + pub fn event(name: impl Into, trigger_tag: impl Into) -> Self { + Self { + name: name.into(), + description: None, + priority: 5, + trigger: TaskTrigger::Event { + trigger_tag: trigger_tag.into(), + }, + watchdog_ms: None, + programs: Vec::new(), + } + } + + /// Add a program to this task. + pub fn with_program(mut self, program: impl Into) -> Self { + self.programs.push(program.into()); + self + } +} + +/// What triggers task execution. +#[derive(Debug, Clone)] +pub enum TaskTrigger { + /// Runs at a fixed time interval + Periodic { + /// Period in milliseconds + period_ms: u32, + }, + + /// Runs continuously (free-running) + Continuous, + + /// Triggered by an event/tag + Event { + /// Tag that triggers this task + trigger_tag: String, + }, + + /// Triggered by motion group updates + MotionGroup { + /// Motion group name + group_name: String, + }, +} + +impl TaskTrigger { + /// Get the period in ms, if this is a periodic task. + pub fn period_ms(&self) -> Option { + match self { + TaskTrigger::Periodic { period_ms } => Some(*period_ms), + _ => None, + } + } +} diff --git a/plcmodel/src/variable.rs b/plcmodel/src/variable.rs new file mode 100644 index 0000000..8c9609b --- /dev/null +++ b/plcmodel/src/variable.rs @@ -0,0 +1,90 @@ +//! Variable definitions. + +use iectypes::VarClass; + +/// A variable declaration. +/// +/// Maps to: +/// - L5X: `` elements +/// - PLCopen: `` within interface sections +#[derive(Debug, Clone)] +pub struct Variable { + /// Variable name + pub name: String, + + /// Data type (as string, may be user-defined) + pub data_type: String, + + /// Variable class (Input, Output, Local, etc.) + pub var_class: VarClass, + + /// Initial value expression (if any) + pub initial_value: Option, + + /// Optional description/comment + pub description: Option, + + /// Direct address binding (%I0.0, %QW10, etc.) + pub address: Option, + + /// Array dimensions [10], [3,4], etc. Empty for scalar. + pub dimensions: Vec, + + /// Is this variable a constant? + pub is_constant: bool, + + /// Is this variable retained across power cycles? + pub is_retain: bool, +} + +impl Variable { + /// Create a new local variable. + pub fn new(name: impl Into, data_type: impl Into) -> Self { + Self { + name: name.into(), + data_type: data_type.into(), + var_class: VarClass::Local, + initial_value: None, + description: None, + address: None, + dimensions: Vec::new(), + is_constant: false, + is_retain: false, + } + } + + /// Create an input variable. + pub fn input(name: impl Into, data_type: impl Into) -> Self { + let mut var = Self::new(name, data_type); + var.var_class = VarClass::Input; + var + } + + /// Create an output variable. + pub fn output(name: impl Into, data_type: impl Into) -> Self { + let mut var = Self::new(name, data_type); + var.var_class = VarClass::Output; + var + } + + /// Create an in/out variable. + pub fn in_out(name: impl Into, data_type: impl Into) -> Self { + let mut var = Self::new(name, data_type); + var.var_class = VarClass::InOut; + var + } + + /// Check if this is an array type. + pub fn is_array(&self) -> bool { + !self.dimensions.is_empty() + } + + /// Get total array size (product of dimensions). + pub fn array_size(&self) -> u32 { + if self.dimensions.is_empty() { + 1 + } else { + self.dimensions.iter().product() + } + } +} diff --git a/plcmodel/tests/model_tests.rs b/plcmodel/tests/model_tests.rs new file mode 100644 index 0000000..0fd26b7 --- /dev/null +++ b/plcmodel/tests/model_tests.rs @@ -0,0 +1,124 @@ +//! Tests for plcmodel crate. + +use iectypes::PouType; +use plcmodel::*; + +#[test] +fn test_project_creation() { + let mut project = Project::new("TestProject"); + project.description = Some("A test project".into()); + + assert_eq!(project.name, "TestProject"); + assert_eq!(project.description.as_deref(), Some("A test project")); + assert!(project.pous.is_empty()); +} + +#[test] +fn test_pou_creation() { + let mut pou = Pou::new("MainProgram", PouType::Program); + pou.description = Some("Main control program".into()); + + assert_eq!(pou.name, "MainProgram"); + assert!(matches!(pou.pou_type, PouType::Program)); + assert!(pou.is_empty()); +} + +#[test] +fn test_pou_interface() { + let mut pou = Pou::new("Motor_FB", PouType::FunctionBlock); + + pou.interface.inputs.push(Variable::input("Enable", "BOOL")); + pou.interface.inputs.push(Variable::input("Speed", "REAL")); + pou.interface.outputs.push(Variable::output("Running", "BOOL")); + pou.interface.locals.push(Variable::new("Timer", "TON")); + + assert_eq!(pou.interface.variable_count(), 4); + assert!(pou.find_variable("Enable").is_some()); + assert!(pou.find_variable("Running").is_some()); + assert!(pou.find_variable("NonExistent").is_none()); +} + +#[test] +fn test_variable_array() { + let mut var = Variable::new("Data", "INT"); + var.dimensions = vec![10, 20]; + + assert!(var.is_array()); + assert_eq!(var.array_size(), 200); +} + +#[test] +fn test_data_type_struct() { + let dt = DataTypeDef::structure( + "MotorData", + vec![ + StructMember::new("Speed", "REAL"), + StructMember::new("Running", "BOOL"), + StructMember::new("Faults", "DINT"), + ], + ); + + assert_eq!(dt.name, "MotorData"); + if let DataTypeKind::Struct(s) = &dt.kind { + assert_eq!(s.members.len(), 3); + } else { + panic!("Expected struct"); + } +} + +#[test] +fn test_data_type_enum() { + let dt = DataTypeDef::enumeration( + "MachineState", + vec![ + EnumMember::with_value("Stopped", 0), + EnumMember::with_value("Running", 1), + EnumMember::with_value("Faulted", 2), + ], + ); + + assert_eq!(dt.name, "MachineState"); + if let DataTypeKind::Enum(e) = &dt.kind { + assert_eq!(e.members.len(), 3); + assert_eq!(e.members[1].value, Some(1)); + } else { + panic!("Expected enum"); + } +} + +#[test] +fn test_task_creation() { + let task = Task::periodic("MainTask", 10) + .with_program("MainProgram") + .with_program("SafetyProgram"); + + assert_eq!(task.name, "MainTask"); + assert_eq!(task.trigger.period_ms(), Some(10)); + assert_eq!(task.programs.len(), 2); +} + +#[test] +fn test_body_empty() { + assert!(Body::St("".into()).is_empty()); + assert!(Body::St(" \n ".into()).is_empty()); + assert!(!Body::St("x := 1;".into()).is_empty()); + assert!(Body::Ld(vec![]).is_empty()); +} + +#[test] +fn test_project_pou_filtering() { + let mut project = Project::new("Test"); + project.pous.push(Pou::new("MainProg", PouType::Program)); + project.pous.push(Pou::new("Util", PouType::Function)); + project + .pous + .push(Pou::new("Motor_FB", PouType::FunctionBlock)); + project.pous.push(Pou::new("Safety", PouType::Program)); + + assert_eq!(project.programs().count(), 2); + assert_eq!(project.functions().count(), 1); + assert_eq!(project.function_blocks().count(), 1); + + assert!(project.find_pou("Motor_FB").is_some()); + assert!(project.find_pou("NonExistent").is_none()); +}