Skip to main content

iec61850_kit/common/
reference.rs

1use alloc::string::String;
2use alloc::vec::Vec;
3use core::fmt;
4
5use super::Error;
6
7/// Functional constraint (IEC 61850-7-2 §5.7).
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9#[allow(missing_docs)]
10pub enum Fc {
11    ST,
12    MX,
13    SP,
14    SV,
15    CF,
16    DC,
17    SG,
18    SE,
19    SR,
20    OR,
21    BL,
22    EX,
23    CO,
24    US,
25    MS,
26    RP,
27    BR,
28    LG,
29    GO,
30    GS,
31    XX,
32}
33
34impl Fc {
35    /// Parse the two-letter code as written in SCL and object references.
36    pub fn parse(s: &str) -> Option<Fc> {
37        Some(match s {
38            "ST" => Fc::ST,
39            "MX" => Fc::MX,
40            "SP" => Fc::SP,
41            "SV" => Fc::SV,
42            "CF" => Fc::CF,
43            "DC" => Fc::DC,
44            "SG" => Fc::SG,
45            "SE" => Fc::SE,
46            "SR" => Fc::SR,
47            "OR" => Fc::OR,
48            "BL" => Fc::BL,
49            "EX" => Fc::EX,
50            "CO" => Fc::CO,
51            "US" => Fc::US,
52            "MS" => Fc::MS,
53            "RP" => Fc::RP,
54            "BR" => Fc::BR,
55            "LG" => Fc::LG,
56            "GO" => Fc::GO,
57            "GS" => Fc::GS,
58            "XX" => Fc::XX,
59            _ => return None,
60        })
61    }
62
63    /// Whether a **client** may write a data attribute under this functional constraint
64    /// (IEC 61850-7-2 §5.7, Table 5).
65    ///
66    /// This is the difference between a server and a value store, and it is not a detail:
67    /// `ST` is *status information* — what the process reports — and `MX` is a measurand.
68    /// A server that lets a client write them lets it fake a breaker position without
69    /// touching the breaker, which is the control model bypassed in one `Write`. Real IEDs
70    /// answer `object-access-denied`, and so does this one; the **application** behind the
71    /// server writes them through its own path
72    /// ([`Txn`](crate::server::Txn)), which is where process data belongs.
73    ///
74    /// `CO` is absent on purpose: nothing under it is a plain attribute. `Oper`, `SBOw`,
75    /// `SBO` and `Cancel` are *services* with their own rules, and everything else under a
76    /// controllable object is a component of one of them.
77    pub const fn is_client_writable(self) -> bool {
78        match self {
79            // Settings, substitutions, configuration, descriptions, blocking and the editable
80            // copy of a setting group; and the control blocks, which are written to configure
81            // and enable them.
82            Fc::SP | Fc::SV | Fc::CF | Fc::DC | Fc::SE | Fc::BL | Fc::RP | Fc::BR | Fc::LG | Fc::GO | Fc::GS | Fc::MS | Fc::US => true,
83            // Status, measurands, the *active* setting group, service tracking, operate
84            // received, extended definitions — all of them are what the server reports.
85            Fc::ST | Fc::MX | Fc::SG | Fc::SR | Fc::OR | Fc::EX | Fc::CO | Fc::XX => false,
86        }
87    }
88
89    /// The two-letter code.
90    pub const fn as_str(self) -> &'static str {
91        match self {
92            Fc::ST => "ST",
93            Fc::MX => "MX",
94            Fc::SP => "SP",
95            Fc::SV => "SV",
96            Fc::CF => "CF",
97            Fc::DC => "DC",
98            Fc::SG => "SG",
99            Fc::SE => "SE",
100            Fc::SR => "SR",
101            Fc::OR => "OR",
102            Fc::BL => "BL",
103            Fc::EX => "EX",
104            Fc::CO => "CO",
105            Fc::US => "US",
106            Fc::MS => "MS",
107            Fc::RP => "RP",
108            Fc::BR => "BR",
109            Fc::LG => "LG",
110            Fc::GO => "GO",
111            Fc::GS => "GS",
112            Fc::XX => "XX",
113        }
114    }
115}
116
117impl fmt::Display for Fc {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        f.write_str(self.as_str())
120    }
121}
122
123/// One step *inside* a named variable: which part of its value a reference names.
124///
125/// A reference names a variable and, sometimes, a part of it. `MMXU1.TotW.mag.f` is a
126/// variable all the way down, because every component of it has a name in the MMS namespace.
127/// `MHAI1.HA.phsAHar(2).cVal.mag.f` is not: `phsAHar` is an **array**, MMS gives its elements
128/// no names, and everything from the index on has to be carried beside the name as an
129/// `alternateAccess` (`proto::mms::alternate`). This is the modelling half of that; the wire
130/// half lives with the codec.
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132pub enum Selector<'a> {
133    /// A named component of a structure — `cVal`, `mag`, `f`.
134    Component(&'a str),
135    /// One element of an array, counted from zero.
136    Index(u32),
137    /// A run of elements of an array.
138    IndexRange {
139        /// The first element.
140        low: u32,
141        /// How many.
142        count: u32,
143    },
144    /// Every element of an array. Distinct from *no* selection: it says the value is an array
145    /// and that the client knows it.
146    AllElements,
147}
148
149impl fmt::Display for Selector<'_> {
150    /// The IEC 61850 reference syntax: `.cVal` for a component, `(2)` for an index.
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        match self {
153            Selector::Component(name) => write!(f, ".{name}"),
154            Selector::Index(i) => write!(f, "({i})"),
155            Selector::IndexRange { low, count } => write!(f, "({low}..{})", low.saturating_add(*count).saturating_sub(1)),
156            Selector::AllElements => f.write_str("(*)"),
157        }
158    }
159}
160
161/// A parsed IEC 61850 object reference: `LDName/LNName.DO[.SDO][.DA[.BDA]]`, optionally
162/// with a functional constraint in the MMS form `LDName/LNName$FC$DO$DA`.
163///
164/// Borrows the input; nothing is allocated.
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166pub struct ObjectReference<'a> {
167    /// Logical device name (`IEDNameLDInst` or `ldName`).
168    pub ld: &'a str,
169    /// Logical node name (`prefix + class + inst`, e.g. `LLN0`, `MMXU1`).
170    pub ln: &'a str,
171    /// Functional constraint if the reference was in MMS form.
172    pub fc: Option<Fc>,
173    /// The path below the LN, without separators, e.g. `["Mod", "stVal"]`. Empty for an LN
174    /// reference.
175    path: &'a str,
176}
177
178impl<'a> ObjectReference<'a> {
179    /// Parse either form. Returns an error for empty components or illegal characters.
180    pub fn parse(s: &'a str) -> Result<Self, Error> {
181        let (ld, rest) = s.split_once('/').ok_or(Error::InvalidReference("missing `/` between LD and LN"))?;
182        if ld.is_empty() || !ld.bytes().all(is_name_byte) {
183            return Err(Error::InvalidReference("logical device name"));
184        }
185        let (ln, fc, path) = if let Some((ln, tail)) = rest.split_once('$') {
186            let (fc_str, path) = match tail.split_once('$') {
187                Some((fc, path)) => (fc, path),
188                None => (tail, ""),
189            };
190            let fc = Fc::parse(fc_str).ok_or(Error::InvalidReference("functional constraint"))?;
191            (ln, Some(fc), path)
192        } else {
193            match rest.split_once('.') {
194                Some((ln, path)) => (ln, None, path),
195                None => (rest, None, ""),
196            }
197        };
198        if ln.is_empty() || !ln.bytes().all(is_name_byte) {
199            return Err(Error::InvalidReference("logical node name"));
200        }
201        for part in path.split(['.', '$']) {
202            if path.is_empty() {
203                break;
204            }
205            // `name` or `name(index)`, and nothing else: a stray parenthesis in a reference is
206            // a typo that would otherwise become a name no server has.
207            let (name, index) = split_index(part);
208            if name.is_empty() || !name.bytes().all(is_name_byte) {
209                return Err(Error::InvalidReference("data object / attribute name"));
210            }
211            if index.is_none() && name.len() != part.len() {
212                return Err(Error::InvalidReference("array index"));
213            }
214        }
215        Ok(ObjectReference { ld, ln, fc, path })
216    }
217
218    /// The components below the LN (`DO`, `SDO`, `DA`, `BDA` …), in order.
219    pub fn path(&self) -> impl Iterator<Item = &'a str> + 'a {
220        self.parts().map(|(name, _)| name).take(self.named_len())
221    }
222
223    /// Every component below the LN with the array index that follows it, if any.
224    ///
225    /// `HA.phsAHar(2).cVal` is `[("HA", None), ("phsAHar", Some(2)), ("cVal", None)]`.
226    fn parts(&self) -> impl Iterator<Item = (&'a str, Option<u32>)> + 'a {
227        self.path.split(['.', '$']).filter(|s| !s.is_empty()).map(split_index)
228    }
229
230    /// How many components make up the MMS **name**: everything up to and including the first
231    /// one that carries an index.
232    ///
233    /// That is where the namespace stops. `MHAI1$MX$HA$phsAHar` is a named variable and
234    /// `phsAHar`'s elements are not, so an index and everything after it is a *selection*
235    /// rather than more of the name (IEC 61850-8-1 §7.3).
236    fn named_len(&self) -> usize {
237        let mut n = 0usize;
238        for (_, index) in self.parts() {
239            n += 1;
240            if index.is_some() {
241                break;
242            }
243        }
244        n
245    }
246
247    /// The part of this reference that is **not** a name: the array index it selects and
248    /// every component after it.
249    ///
250    /// Empty for the ordinary reference, which names a variable and nothing inside it. A
251    /// non-empty one has to travel beside the name as an ISO 9506 `alternateAccess`, and a
252    /// caller that drops it reads a whole array where it asked for one element.
253    pub fn selection(&self) -> Vec<Selector<'a>> {
254        let named = self.named_len();
255        let mut out = Vec::new();
256        for (n, (name, index)) in self.parts().enumerate() {
257            if n + 1 > named {
258                out.push(Selector::Component(name));
259            }
260            if let Some(i) = index {
261                out.push(Selector::Index(i));
262            }
263        }
264        out
265    }
266
267    /// The data object (first path component), if any.
268    pub fn data_object(&self) -> Option<&'a str> {
269        self.path().next()
270    }
271
272    /// Total length of the canonical dotted form, for the edition's limit
273    /// ([`crate::common::Edition::max_object_reference_len`]).
274    // A parsed reference is never empty, so there is no `is_empty` to pair with this.
275    #[allow(clippy::len_without_is_empty)]
276    pub fn len(&self) -> usize {
277        self.ld.len() + 1 + self.ln.len() + if self.path.is_empty() { 0 } else { 1 + self.path.len() }
278    }
279
280    /// True when this reference fits the object-reference limit of `edition`.
281    pub fn fits(&self, edition: crate::common::Edition) -> bool {
282        self.len() <= edition.max_object_reference_len()
283    }
284}
285
286impl ObjectReference<'_> {
287    /// The MMS domain and item this reference maps to (IEC 61850-8-1 §7.3).
288    ///
289    /// The logical device is the MMS **domain** and `LN$FC$DO$DA` is the **item** — the one
290    /// mapping every client service goes through, so it lives here rather than being spelt
291    /// out at each call site. A reference that already carries a functional constraint keeps
292    /// its own; `fc` is what a dotted reference is read with.
293    pub fn to_mms(&self, fc: Fc) -> (&str, String) {
294        self.to_mms_under(self.fc.unwrap_or(fc))
295    }
296
297    /// The same reference under a **different** functional constraint.
298    ///
299    /// [`ObjectReference::to_mms`] keeps whatever constraint the reference itself carried,
300    /// which is what a caller naming one leaf wants. This is the other case: one data object
301    /// seen through two constraints. `CSWI1$CO$Pos` is the controllable object and
302    /// `CSWI1$CF$Pos$ctlModel` is how it was engineered, and a client holding the first has
303    /// to be able to ask for the second — which is exactly what stops it guessing the
304    /// control model and building a sequence the server answers with `ObjectNotSelected`.
305    pub fn to_mms_under(&self, fc: Fc) -> (&str, String) {
306        let mut item = String::with_capacity(self.ln.len() + 3 + self.path.len() + 1);
307        item.push_str(self.ln);
308        item.push('$');
309        item.push_str(fc.as_str());
310        for part in self.path() {
311            item.push('$');
312            item.push_str(part);
313        }
314        (self.ld, item)
315    }
316}
317
318impl fmt::Display for ObjectReference<'_> {
319    /// Canonical dotted form; the MMS form if an FC is present.
320    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321        write!(f, "{}/{}", self.ld, self.ln)?;
322        // The raw path is printed, indices and all: a reference that selects an array element
323        // has to come back out as the reference that went in.
324        match self.fc {
325            Some(fc) => {
326                write!(f, "${fc}")?;
327                for p in self.path.split(['.', '$']).filter(|s| !s.is_empty()) {
328                    write!(f, "${p}")?;
329                }
330            }
331            None => {
332                for p in self.path.split(['.', '$']).filter(|s| !s.is_empty()) {
333                    write!(f, ".{p}")?;
334                }
335            }
336        }
337        Ok(())
338    }
339}
340
341const fn is_name_byte(b: u8) -> bool {
342    b.is_ascii_alphanumeric() || b == b'_'
343}
344
345/// Split `phsAHar(2)` into `("phsAHar", Some(2))`, and anything without a well-formed index
346/// into itself and `None`.
347///
348/// One place, because four layers ask the same question: the reference parser, the server's
349/// name resolution, the value store's leaf walk and the data-set member that carries an `ix`.
350/// Two spellings of "is this an array element" is two answers waiting to disagree.
351pub fn split_index(part: &str) -> (&str, Option<u32>) {
352    let Some(open) = part.find('(') else { return (part, None) };
353    let (name, rest) = part.split_at(open);
354    match rest.strip_prefix('(').and_then(|r| r.strip_suffix(')')).and_then(|d| d.parse::<u32>().ok()) {
355        Some(index) => (name, Some(index)),
356        None => (part, None),
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    extern crate alloc;
363    use super::*;
364    use alloc::string::ToString;
365    use alloc::vec::Vec;
366
367    /// One data object, two functional constraints. `to_mms` keeps the reference's own —
368    /// which is right for a caller naming a leaf — and `to_mms_under` replaces it, which is
369    /// the only way to ask a controllable object how it was engineered.
370    #[test]
371    fn a_controllable_object_can_be_asked_for_its_configuration() {
372        let co = ObjectReference::parse("IED1LD0/CSWI1$CO$Pos").unwrap();
373        assert_eq!(co.to_mms(Fc::CF), ("IED1LD0", String::from("CSWI1$CO$Pos")), "the reference's own constraint stands");
374        assert_eq!(co.to_mms_under(Fc::CF), ("IED1LD0", String::from("CSWI1$CF$Pos")), "…until it is deliberately replaced");
375        // A dotted reference has no constraint of its own, so both agree.
376        let dotted = ObjectReference::parse("IED1LD0/CSWI1.Pos").unwrap();
377        assert_eq!(dotted.to_mms(Fc::CF), dotted.to_mms_under(Fc::CF));
378    }
379
380    #[test]
381    fn the_mms_mapping_puts_the_functional_constraint_after_the_logical_node() {
382        let r = ObjectReference::parse("IED1LD0/MMXU1.TotW.mag.f").unwrap();
383        assert_eq!(r.to_mms(Fc::MX), ("IED1LD0", String::from("MMXU1$MX$TotW$mag$f")));
384        // A reference that already names its constraint keeps it.
385        let m = ObjectReference::parse("IED1LD0/LLN0$ST$Mod$stVal").unwrap();
386        assert_eq!(m.to_mms(Fc::MX), ("IED1LD0", String::from("LLN0$ST$Mod$stVal")));
387        // A logical node on its own is the LN with its constraint and nothing under it.
388        let ln = ObjectReference::parse("IED1LD0/LLN0").unwrap();
389        assert_eq!(ln.to_mms(Fc::ST), ("IED1LD0", String::from("LLN0$ST")));
390    }
391
392    #[test]
393    fn dotted_and_mms_forms() {
394        let r = ObjectReference::parse("IED1LD0/MMXU1.TotW.mag.f").unwrap();
395        assert_eq!((r.ld, r.ln, r.fc), ("IED1LD0", "MMXU1", None));
396        assert_eq!(r.path().collect::<Vec<_>>(), ["TotW", "mag", "f"]);
397        assert_eq!(r.to_string(), "IED1LD0/MMXU1.TotW.mag.f");
398
399        let m = ObjectReference::parse("IED1LD0/LLN0$ST$Mod$stVal").unwrap();
400        assert_eq!(m.fc, Some(Fc::ST));
401        assert_eq!(m.data_object(), Some("Mod"));
402        assert_eq!(m.to_string(), "IED1LD0/LLN0$ST$Mod$stVal");
403
404        let ln = ObjectReference::parse("IED1LD0/LLN0").unwrap();
405        assert_eq!(ln.path().count(), 0);
406        assert_eq!(ln.len(), 12);
407        assert!(ln.fits(crate::common::Edition::Ed1));
408
409        assert!(ObjectReference::parse("nolyslash").is_err());
410        assert!(ObjectReference::parse("LD/LN$ZZ$Mod").is_err());
411        assert!(ObjectReference::parse("LD/LN..x").is_err());
412        assert!(ObjectReference::parse("L D/LN").is_err());
413    }
414}