use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use crate::common::{Fc, split_index};
use crate::model::{BType, DataAttribute, DataObject, LogicalDevice, LogicalNode};
use crate::proto::mms::typespec::{Component, TypeSpec};
pub const SEP: char = '$';
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum VarKind {
Structure,
Array(u32),
Leaf(BType),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Variable {
pub name: String,
pub kind: VarKind,
pub fc: Option<Fc>,
pub children: Vec<Variable>,
}
impl Variable {
pub(crate) fn structure(name: impl Into<String>, fc: Option<Fc>, children: Vec<Variable>) -> Variable {
Variable { name: name.into(), kind: VarKind::Structure, fc, children }
}
pub fn leaf(name: impl Into<String>, fc: Option<Fc>, btype: BType) -> Variable {
Variable { name: name.into(), kind: VarKind::Leaf(btype), fc, children: Vec::new() }
}
pub(crate) fn array(name: impl Into<String>, fc: Option<Fc>, count: u32, element: Variable) -> Variable {
Variable { name: name.into(), kind: VarKind::Array(count), fc, children: alloc::vec![element] }
}
pub fn is_structure(&self) -> bool {
matches!(self.kind, VarKind::Structure)
}
pub const fn array_len(&self) -> Option<u32> {
match self.kind {
VarKind::Array(n) => Some(n),
VarKind::Structure | VarKind::Leaf(_) => None,
}
}
pub fn element(&self) -> Option<&Variable> {
self.array_len().and(self.children.first())
}
pub fn child(&self, name: &str) -> Option<&Variable> {
if self.array_len().is_some() {
return None;
}
self.children.iter().find(|c| c.name == name)
}
pub fn resolve<'a>(&'a self, path: &mut dyn Iterator<Item = &str>) -> Option<&'a Variable> {
let mut node = self;
for part in path {
let (name, index) = split_index(part);
node = node.child(name)?;
if let Some(i) = index {
node = node.at(i)?;
}
}
Some(node)
}
pub fn at(&self, index: u32) -> Option<&Variable> {
(index < self.array_len()?).then(|| self.element()).flatten()
}
pub fn type_spec(&self) -> TypeSpec {
match &self.kind {
VarKind::Structure => TypeSpec::Structure {
packed: false,
components: self.children.iter().map(|c| Component { name: Some(c.name.clone()), type_spec: c.type_spec() }).collect(),
},
VarKind::Array(n) => TypeSpec::Array {
packed: false,
elements: *n,
element_type: Box::new(self.element().map_or(TypeSpec::Structure { packed: false, components: Vec::new() }, Variable::type_spec)),
},
VarKind::Leaf(b) => type_of(b),
}
}
}
pub fn type_of(btype: &BType) -> TypeSpec {
match btype {
BType::Boolean => TypeSpec::Boolean,
BType::Int8 | BType::Enum => TypeSpec::Integer(8),
BType::Int16 => TypeSpec::Integer(16),
BType::Int24 => TypeSpec::Integer(24),
BType::Int32 => TypeSpec::Integer(32),
BType::Int64 => TypeSpec::Integer(64),
BType::Int8U => TypeSpec::Unsigned(8),
BType::Int16U => TypeSpec::Unsigned(16),
BType::Int24U => TypeSpec::Unsigned(24),
BType::Int32U => TypeSpec::Unsigned(32),
BType::Float32 => TypeSpec::FloatingPoint { format_width: 32, exponent_width: 8 },
BType::Float64 => TypeSpec::FloatingPoint { format_width: 64, exponent_width: 11 },
BType::Dbpos | BType::Tcmd => TypeSpec::BitString(2),
BType::PhyComAddr | BType::Struct | BType::Other(_) => TypeSpec::Structure { packed: false, components: Vec::new() },
BType::Quality => TypeSpec::BitString(-13),
BType::Check => TypeSpec::BitString(-2),
BType::TrgOps => TypeSpec::BitString(-6),
BType::OptFlds => TypeSpec::BitString(-10),
BType::Timestamp => TypeSpec::UtcTime,
BType::EntryTime => TypeSpec::BinaryTime(true),
BType::VisString32 => TypeSpec::VisibleString(-32),
BType::VisString64 => TypeSpec::VisibleString(-64),
BType::VisString65 => TypeSpec::VisibleString(-65),
BType::VisString129 | BType::ObjRef => TypeSpec::VisibleString(-129),
BType::VisString255 => TypeSpec::VisibleString(-255),
BType::Currency => TypeSpec::VisibleString(-3),
BType::Octet64 => TypeSpec::OctetString(-64),
BType::EntryID => TypeSpec::OctetString(-8),
BType::Octet6 => TypeSpec::OctetString(6),
BType::Octet16 => TypeSpec::OctetString(16),
BType::SvOptFlds | BType::LogOptFlds => TypeSpec::BitString(-8),
BType::Unicode255 => TypeSpec::MmsString(-255),
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Domain {
pub name: String,
pub nodes: Vec<Variable>,
}
impl Domain {
pub fn node(&self, name: &str) -> Option<&Variable> {
self.nodes.iter().find(|n| n.name == name)
}
pub fn resolve(&self, item: &str) -> Option<&Variable> {
let mut parts = item.split(SEP);
let node = self.node(parts.next()?)?;
node.resolve(&mut parts)
}
pub fn variable_names(&self) -> Vec<String> {
let mut out = Vec::new();
for node in &self.nodes {
push_names(node, &node.name, &mut out);
}
out.sort();
out
}
}
fn push_names(node: &Variable, prefix: &str, out: &mut Vec<String>) {
out.push(String::from(prefix));
if node.array_len().is_some() {
return;
}
for child in &node.children {
let mut name = String::with_capacity(prefix.len() + 1 + child.name.len());
name.push_str(prefix);
name.push(SEP);
name.push_str(&child.name);
push_names(child, &name, out);
}
}
pub fn domain_of(ld: &LogicalDevice, extra: &mut dyn FnMut(&LogicalNode) -> Vec<(Fc, Variable)>) -> Domain {
let mut nodes = Vec::with_capacity(ld.logical_nodes.len());
for ln in &ld.logical_nodes {
let mut by_fc: Vec<(Fc, Vec<Variable>)> = Vec::new();
for fc in functional_constraints(ln) {
let children: Vec<Variable> = ln.data_objects.iter().filter_map(|d| object_under(d, fc)).collect();
if !children.is_empty() {
by_fc.push((fc, children));
}
}
for (fc, variable) in extra(ln) {
match by_fc.iter_mut().find(|(f, _)| *f == fc) {
Some((_, list)) => list.push(variable),
None => by_fc.push((fc, alloc::vec![variable])),
}
}
by_fc.sort_by_key(|(fc, _)| fc.as_str());
let fcs = by_fc.into_iter().map(|(fc, children)| Variable::structure(fc.as_str(), Some(fc), children)).collect();
nodes.push(Variable::structure(ln.name.clone(), None, fcs));
}
Domain { name: ld.name.clone(), nodes }
}
fn functional_constraints(ln: &LogicalNode) -> Vec<Fc> {
let mut out: Vec<Fc> = Vec::new();
for d in &ln.data_objects {
collect_fcs(d, &mut out);
}
if out.contains(&Fc::SG) || out.contains(&Fc::SE) {
for fc in [Fc::SG, Fc::SE] {
if !out.contains(&fc) {
out.push(fc);
}
}
}
out.sort_by_key(|fc| fc.as_str());
out
}
fn collect_fcs(object: &DataObject, out: &mut Vec<Fc>) {
for a in &object.attributes {
if !out.contains(&a.fc) {
out.push(a.fc);
}
}
for s in &object.sub_objects {
collect_fcs(s, out);
}
}
fn object_under(object: &DataObject, fc: Fc) -> Option<Variable> {
let mut children: Vec<Variable> = object.attributes.iter().filter(|a| belongs_under(a.fc, fc)).map(|a| attribute_variable(a, fc)).collect();
children.extend(object.sub_objects.iter().filter_map(|s| object_under(s, fc)));
if children.is_empty() {
return None;
}
let element = Variable::structure(object.name.clone(), Some(fc), children);
Some(match object.count {
Some(n) => Variable::array(object.name.clone(), Some(fc), n, element),
None => element,
})
}
fn belongs_under(declared: Fc, fc: Fc) -> bool {
matches!((declared, fc), (Fc::SG | Fc::SE, Fc::SG | Fc::SE)) || declared == fc
}
pub fn phy_com_addr(name: impl Into<String>, fc: Option<Fc>) -> Variable {
Variable::structure(
name,
fc,
alloc::vec![
Variable::leaf("Addr", fc, BType::Octet6),
Variable::leaf("PRIORITY", fc, BType::Int8U),
Variable::leaf("VID", fc, BType::Int16U),
Variable::leaf("APPID", fc, BType::Int16U),
],
)
}
fn attribute_variable(a: &DataAttribute, fc: Fc) -> Variable {
let element = if a.children.is_empty() {
if a.btype == BType::PhyComAddr { phy_com_addr(a.name.clone(), Some(fc)) } else { Variable::leaf(a.name.clone(), Some(fc), a.btype.clone()) }
} else {
Variable::structure(a.name.clone(), Some(fc), a.children.iter().map(|c| attribute_variable(c, fc)).collect())
};
match a.count {
Some(n) => Variable::array(a.name.clone(), Some(fc), n, element),
None => element,
}
}
pub fn item_with(item: &str, selection: &[crate::common::Selector<'_>]) -> Option<String> {
use crate::common::Selector;
let mut out = String::from(item);
for step in selection {
match step {
Selector::Component(name) => {
out.push(SEP);
out.push_str(name);
}
Selector::Index(i) => {
let _ = core::fmt::Write::write_fmt(&mut out, format_args!("({i})"));
}
Selector::IndexRange { .. } | Selector::AllElements => return None,
}
}
Some(out)
}
pub fn split_item(item: &str) -> (&str, Option<Fc>, impl Iterator<Item = &str>) {
let mut parts = item.split(SEP);
let ln = parts.next().unwrap_or("");
let mut rest = parts.clone();
let fc = rest.next().and_then(Fc::parse);
if fc.is_some() { (ln, fc, rest) } else { (ln, None, parts) }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::IedModel;
use alloc::vec;
fn model() -> IedModel {
const ICD: &str = r#"<?xml version="1.0"?>
<SCL xmlns="http://www.iec.ch/61850/2003/SCL" version="2007" revision="B" release="4">
<Header id="t"/>
<IED name="IED1"><AccessPoint name="P1"><Server><LDevice inst="LD0">
<LN0 lnClass="LLN0" inst="" lnType="LLN0_T"/>
<LN lnClass="CSWI" inst="1" prefix="" lnType="CSWI_T"/>
</LDevice></Server></AccessPoint></IED>
<DataTypeTemplates>
<LNodeType id="LLN0_T" lnClass="LLN0"><DO name="Mod" type="INC_T"/></LNodeType>
<LNodeType id="CSWI_T" lnClass="CSWI"><DO name="Pos" type="DPC_T"/></LNodeType>
<DOType id="INC_T" cdc="INC">
<DA name="stVal" fc="ST" bType="Enum" type="Mod_E"/>
<DA name="q" fc="ST" bType="Quality"/>
<DA name="t" fc="ST" bType="Timestamp"/>
<DA name="ctlModel" fc="CF" bType="Enum" type="CtlModel_E"/>
</DOType>
<DOType id="DPC_T" cdc="DPC">
<DA name="stVal" fc="ST" bType="Dbpos"/>
<DA name="q" fc="ST" bType="Quality"/>
<DA name="Oper" fc="CO" bType="Struct" type="Oper_T"/>
</DOType>
<DAType id="Oper_T">
<BDA name="ctlVal" bType="Dbpos"/>
<BDA name="ctlNum" bType="INT8U"/>
<BDA name="T" bType="Timestamp"/>
<BDA name="Test" bType="BOOLEAN"/>
</DAType>
<EnumType id="Mod_E"><EnumVal ord="1">on</EnumVal></EnumType>
<EnumType id="CtlModel_E"><EnumVal ord="1">direct-with-normal-security</EnumVal></EnumType>
</DataTypeTemplates>
</SCL>"#;
IedModel::from_scl(ICD, Some("IED1")).expect("load")
}
fn domain() -> Domain {
let m = model();
domain_of(&m.logical_devices[0], &mut |_| Vec::new())
}
#[test]
fn the_namespace_is_flattened_and_sorted() {
let names = domain().variable_names();
for expected in [
"CSWI1",
"CSWI1$CO",
"CSWI1$CO$Pos",
"CSWI1$CO$Pos$Oper",
"CSWI1$CO$Pos$Oper$ctlVal",
"CSWI1$ST$Pos$stVal",
"LLN0",
"LLN0$CF",
"LLN0$CF$Mod$ctlModel",
"LLN0$ST$Mod$stVal",
"LLN0$ST$Mod$t",
] {
assert!(names.iter().any(|n| n == expected), "`{expected}` missing from {names:#?}");
}
let mut sorted = names.clone();
sorted.sort();
assert_eq!(names, sorted);
let lns: Vec<&String> = names.iter().filter(|n| !n.contains(SEP)).collect();
assert_eq!(lns, ["CSWI1", "LLN0"]);
}
#[test]
fn a_name_resolves_to_the_node_it_denotes() {
let d = domain();
assert_eq!(d.resolve("LLN0$ST$Mod$stVal").map(|v| v.kind.clone()), Some(VarKind::Leaf(BType::Enum)));
assert!(d.resolve("LLN0$ST$Mod").is_some_and(Variable::is_structure));
assert!(d.resolve("CSWI1$CO$Pos$Oper").is_some_and(Variable::is_structure));
assert!(d.resolve("LLN0$ST$Mod$nosuch").is_none());
assert!(d.resolve("LLN0$MX$Mod$stVal").is_none(), "the attribute is under ST, not MX");
assert!(d.resolve("NOPE").is_none());
}
#[test]
fn the_type_of_a_structure_is_its_components_in_order() {
let d = domain();
let oper = d.resolve("CSWI1$CO$Pos$Oper").expect("Oper").type_spec();
assert_eq!(oper.component_names(), ["ctlVal", "ctlNum", "T", "Test"]);
assert_eq!(oper.component("ctlVal"), Some(&TypeSpec::BitString(2)), "a position code is exactly two bits");
assert_eq!(oper.component("ctlNum"), Some(&TypeSpec::Unsigned(8)));
assert_eq!(oper.component("T"), Some(&TypeSpec::UtcTime));
assert_eq!(type_of(&BType::Quality), TypeSpec::BitString(-13));
assert_eq!(type_of(&BType::Dbpos), TypeSpec::BitString(2));
assert_eq!(type_of(&BType::Check), TypeSpec::BitString(-2));
assert_eq!(type_of(&BType::Enum), TypeSpec::Integer(8));
assert_eq!(type_of(&BType::EntryTime), TypeSpec::BinaryTime(true));
}
#[test]
fn control_blocks_join_the_tree_under_their_functional_constraint() {
let m = model();
let d = domain_of(&m.logical_devices[0], &mut |ln| {
if ln.name == "LLN0" {
vec![(Fc::RP, Variable::structure("urcb01", Some(Fc::RP), vec![Variable::leaf("RptEna", Some(Fc::RP), BType::Boolean)]))]
} else {
Vec::new()
}
});
let names = d.variable_names();
assert!(names.iter().any(|n| n == "LLN0$RP"));
assert!(names.iter().any(|n| n == "LLN0$RP$urcb01$RptEna"));
assert_eq!(d.resolve("LLN0$RP$urcb01$RptEna").map(|v| v.kind.clone()), Some(VarKind::Leaf(BType::Boolean)));
}
#[test]
fn an_item_name_splits_into_node_constraint_and_path() {
let (ln, fc, rest) = split_item("LLN0$ST$Mod$stVal");
assert_eq!((ln, fc), ("LLN0", Some(Fc::ST)));
assert_eq!(rest.collect::<Vec<_>>(), ["Mod", "stVal"]);
let (ln, fc, rest) = split_item("LLN0");
assert_eq!((ln, fc, rest.count()), ("LLN0", None, 0));
let (ln, fc, rest) = split_item("LLN0$dsTrip");
assert_eq!((ln, fc), ("LLN0", None));
assert_eq!(rest.collect::<Vec<_>>(), ["dsTrip"]);
}
}