Skip to main content

iec61850_kit/common/
flags.rs

1//! The IEC 61850-7-2 modelling types more than one layer shares.
2//!
3//! `TrgOps` says what makes a server send a report or write a log entry, `OptFlds` says which
4//! fields that report carries, and `ReasonCode` says what actually happened to one member.
5//! All three are bit strings whose **bit 0 is reserved**, numbered from the most significant
6//! bit of the first octet (IEC 61850-8-1 Tables 38 and 39).
7//!
8//! They live in `common` rather than beside the report codec because three layers need them
9//! and only one of those is MMS: the SCL loader reads a control block's engineered defaults
10//! into them ([`crate::model::ReportControl`]), the server evaluates triggers with them, and
11//! the report codec puts them on the wire. One definition, so a control block written from an
12//! SCD and a report decoded off the wire cannot disagree about which bit `dchg` is.
13//!
14//! The [`Value`](crate::proto::data::Value) conversions are in [`crate::proto::data`], which
15//! is where the type they convert to lives.
16
17use alloc::vec::Vec;
18
19/// A packed list of report options (`OptFlds`, IEC 61850-8-1 Table 38).
20///
21/// Ten bits, of which bit 0 is reserved. This is not a convenience: which fields a report
22/// carries is *entirely* determined by these bits, so decoding one without them is guessing.
23#[derive(Clone, Copy, Default, PartialEq, Eq)]
24pub struct OptFlds(u16);
25
26/// A packed list of report trigger options (`TrgOps`).
27///
28/// Six bits, bit 0 reserved: what makes the server send a report at all.
29#[derive(Clone, Copy, Default, PartialEq, Eq)]
30pub struct TrgOps(u8);
31
32/// Why one member was included in a report (`ReasonCode`), one per included value.
33///
34/// The same six bits as [`TrgOps`], answering the question the other way round: `TrgOps` is
35/// what the client asked to be told about, `ReasonCode` is what actually happened.
36#[derive(Clone, Copy, Default, PartialEq, Eq)]
37pub struct ReasonCode(u8);
38
39macro_rules! packed_bits {
40    ($t:ty, $width:expr, $($name:ident = $bit:expr, $set:ident, $doc:expr;)+) => {
41        impl $t {
42            /// No options set.
43            pub const NONE: $t = Self(0);
44            /// Significant bits on the wire, including the reserved bit 0.
45            pub const BITS: usize = $width;
46
47            $(
48                #[doc = $doc]
49                pub const fn $name(self) -> bool {
50                    self.0 & (1 << $bit) != 0
51                }
52
53                #[doc = concat!("Set [`Self::", stringify!($name), "`].")]
54                #[must_use]
55                pub const fn $set(mut self, on: bool) -> Self {
56                    if on { self.0 |= 1 << $bit } else { self.0 &= !(1 << $bit) }
57                    self
58                }
59            )+
60
61            /// True when nothing is set.
62            pub const fn is_empty(self) -> bool {
63                self.0 == 0
64            }
65
66            /// Read from the contents octets of a BER bit string, where bit 0 is the most
67            /// significant bit of the first octet.
68            pub fn from_bit_string(bytes: &[u8]) -> Self {
69                let mut v = 0u16;
70                for bit in 0..$width {
71                    let (octet, shift) = (bit / 8, 7 - (bit % 8));
72                    if bytes.get(octet).is_some_and(|b| b >> shift & 1 == 1) {
73                        v |= 1 << bit;
74                    }
75                }
76                #[allow(clippy::cast_possible_truncation)]
77                Self(v as _)
78            }
79
80            /// The contents octets of a BER bit string, and the number of unused bits in the
81            /// last one.
82            pub fn to_bit_string(self) -> (u8, Vec<u8>) {
83                let octets = usize::div_ceil($width, 8);
84                let mut out = alloc::vec![0u8; octets];
85                for bit in 0..$width {
86                    if u16::from(self.0) & (1 << bit) != 0 {
87                        let (octet, shift) = (bit / 8, 7 - (bit % 8));
88                        if let Some(b) = out.get_mut(octet) {
89                            *b |= 1 << shift;
90                        }
91                    }
92                }
93                (((octets * 8) - $width) as u8, out)
94            }
95        }
96
97        /// Named flags rather than a packed number: these end up in logs and in a `{:?}` of
98        /// every report, where `ReasonCode(32)` says nothing a reader can act on.
99        impl core::fmt::Debug for $t {
100            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
101                f.write_str(stringify!($t))?;
102                f.write_str("(")?;
103                let mut first = true;
104                $(
105                    if self.$name() {
106                        if !first {
107                            f.write_str(" | ")?;
108                        }
109                        first = false;
110                        f.write_str(stringify!($name))?;
111                    }
112                )+
113                if first {
114                    f.write_str("none")?;
115                }
116                f.write_str(")")
117            }
118        }
119    };
120}
121
122packed_bits!(OptFlds, 10,
123    sequence_number = 1, with_sequence_number, "`SqNum` is present.";
124    report_time_stamp = 2, with_report_time_stamp, "`TimeOfEntry` is present.";
125    reason_for_inclusion = 3, with_reason_for_inclusion, "A `ReasonCode` follows every value.";
126    data_set_name = 4, with_data_set_name, "`DatSet` is present.";
127    data_reference = 5, with_data_reference, "A reference precedes every value.";
128    buffer_overflow = 6, with_buffer_overflow, "`BufOvfl` is present (buffered control blocks).";
129    entry_id = 7, with_entry_id, "`EntryID` is present (buffered control blocks).";
130    conf_revision = 8, with_conf_revision, "`ConfRev` is present.";
131    segmentation = 9, with_segmentation, "`SubSeqNum` and `MoreSegmentsFollow` are present.";
132);
133
134packed_bits!(TrgOps, 6,
135    data_change = 1, with_data_change, "Report when a value changes.";
136    quality_change = 2, with_quality_change, "Report when a quality changes.";
137    data_update = 3, with_data_update, "Report on every update, changed or not.";
138    integrity = 4, with_integrity, "Report periodically, every `IntgPd` milliseconds.";
139    general_interrogation = 5, with_general_interrogation, "Report when the client asks (`GI`).";
140);
141
142packed_bits!(ReasonCode, 6,
143    data_change = 1, with_data_change, "A value changed.";
144    quality_change = 2, with_quality_change, "A quality changed.";
145    data_update = 3, with_data_update, "The value was updated without changing.";
146    integrity = 4, with_integrity, "The integrity period elapsed.";
147    general_interrogation = 5, with_general_interrogation, "The client asked (`GI`).";
148);
149
150impl TrgOps {
151    /// The trigger options a client usually wants: data change, quality change and general
152    /// interrogation — everything that is an *event*, without the periodic integrity scan.
153    pub const EVENTS: TrgOps = TrgOps(0b0010_0110);
154}
155
156/// The control model of a controllable object (`ctlModel`, IEC 61850-7-3).
157///
158/// It decides which services are legal: whether a select is required first, and whether the
159/// server answers the operate immediately or only after the switchgear has actually moved.
160#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
161pub enum ControlModel {
162    /// 0 — the object reports a status and cannot be operated.
163    StatusOnly,
164    /// 1 — write `Oper`; the response is the answer.
165    #[default]
166    DirectNormal,
167    /// 2 — read `SBO` to reserve, then write `Oper`.
168    SboNormal,
169    /// 3 — write `Oper`; the *final* answer is a `CommandTermination`.
170    DirectEnhanced,
171    /// 4 — write `SBOw` to reserve with the value, then `Oper`, then `CommandTermination`.
172    SboEnhanced,
173}
174
175impl ControlModel {
176    /// From the `ctlModel` enumeration value.
177    pub const fn from_code(code: i64) -> Option<ControlModel> {
178        Some(match code {
179            0 => ControlModel::StatusOnly,
180            1 => ControlModel::DirectNormal,
181            2 => ControlModel::SboNormal,
182            3 => ControlModel::DirectEnhanced,
183            4 => ControlModel::SboEnhanced,
184            _ => return None,
185        })
186    }
187
188    /// The `ctlModel` enumeration value.
189    pub const fn to_code(self) -> i64 {
190        match self {
191            ControlModel::StatusOnly => 0,
192            ControlModel::DirectNormal => 1,
193            ControlModel::SboNormal => 2,
194            ControlModel::DirectEnhanced => 3,
195            ControlModel::SboEnhanced => 4,
196        }
197    }
198
199    /// True when the object must be selected before it may be operated.
200    pub const fn needs_select(self) -> bool {
201        matches!(self, ControlModel::SboNormal | ControlModel::SboEnhanced)
202    }
203
204    /// True when the select carries the value (`SBOw`) rather than being a bare reservation
205    /// (`SBO`).
206    pub const fn select_carries_value(self) -> bool {
207        matches!(self, ControlModel::SboEnhanced)
208    }
209
210    /// True when the server owes a `CommandTermination` after the operate response.
211    pub const fn enhanced_security(self) -> bool {
212        matches!(self, ControlModel::DirectEnhanced | ControlModel::SboEnhanced)
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    /// These widths are the same in every edition (IEC 61850-8-1 encodes `OptFlds` in ten bits
221    /// and `TrgOps`/`ReasonCode` in six from Edition 1 on), which is why nothing in them is
222    /// mapped by edition the way `AddCause` is.
223    #[test]
224    fn report_bit_strings_have_one_width_in_every_edition() {
225        assert_eq!(OptFlds::BITS, 10);
226        assert_eq!(TrgOps::BITS, 6);
227        assert_eq!(ReasonCode::BITS, 6);
228    }
229}