Skip to main content

iec61850_kit/common/
service.rs

1//! The two enumerations IEC 61850-7-2 service **tracking** is written in, and the classes it
2//! defines. The engine that fills them in is [`server::tracking`](crate::server::Tracking).
3//!
4//! Both lists are the standard's own, in the standard's own order ✅ ([`ServiceType`] from
5//! Table 26, [`ServiceError`] from Table 5). The **ordinals** are not: the name-to-number
6//! mapping belongs to IEC 61850-8-1, which is paywalled, so the server reads them out of the
7//! `EnumType` the SCL file declares and falls back to the standard's list position only when
8//! the file declares none.
9
10use alloc::string::String;
11use alloc::vec::Vec;
12
13/// The service a tracking data object is reporting on (IEC 61850-7-2 Table 26 ✅).
14///
15/// The whole list, not only the tracked half: §15.3.2 says a `GetBRCBValues` is not tracked,
16/// but the enumeration is what a client decodes against.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
18#[non_exhaustive]
19#[allow(missing_docs)] // each variant *is* its documentation: the name is the service.
20pub enum ServiceType {
21    GetServerDirectory,
22    Associate,
23    Abort,
24    Release,
25    GetLogicalDeviceDirectory,
26    GetAllDataValues,
27    GetDataValues,
28    SetDataValues,
29    GetDataDirectory,
30    GetDataDefinition,
31    GetDataSetValues,
32    SetDataSetValues,
33    CreateDataSet,
34    DeleteDataSet,
35    GetDataSetDirectory,
36    SelectActiveSG,
37    SelectEditSG,
38    SetEditSGValue,
39    ConfirmEditSGValues,
40    GetEditSGValue,
41    GetSGCBValues,
42    Report,
43    GetBRCBValues,
44    SetBRCBValues,
45    GetURCBValues,
46    SetURCBValues,
47    GetLCBValues,
48    SetLCBValues,
49    QueryLogByTime,
50    QueryLogAfter,
51    GetLogStatusValues,
52    SendGOOSEMessage,
53    GetGoCBValues,
54    SetGoCBValues,
55    GetGoReference,
56    GetGOOSEElementNumber,
57    SendMSVMessage,
58    GetMSVCBValues,
59    SetMSVCBValues,
60    SendUSVMessage,
61    GetUSVCBValues,
62    SetUSVCBValues,
63    Select,
64    SelectWithValue,
65    Cancel,
66    Operate,
67    CommandTermination,
68    TimeActivatedOperate,
69    GetFile,
70    SetFile,
71    DeleteFile,
72    GetFileAttributeValues,
73    TimeSynchronization,
74    /// Something the *server* did on its own: an association that ended and released a control
75    /// block, or a reservation that ran out. §15.3.2.2.2 names exactly those two.
76    InternalChange,
77}
78
79/// The names, in the order IEC 61850-7-2 Table 26 lists them ✅.
80///
81/// The order is load-bearing twice over: it is the fallback ordinal for a file that declares no
82/// `EnumType`, and it is what [`ServiceType::parse`] matches an `EnumVal` against.
83const SERVICE_TYPES: [(ServiceType, &str); 54] = [
84    (ServiceType::GetServerDirectory, "GetServerDirectory"),
85    (ServiceType::Associate, "Associate"),
86    (ServiceType::Abort, "Abort"),
87    (ServiceType::Release, "Release"),
88    (ServiceType::GetLogicalDeviceDirectory, "GetLogicalDeviceDirectory"),
89    (ServiceType::GetAllDataValues, "GetAllDataValues"),
90    (ServiceType::GetDataValues, "GetDataValues"),
91    (ServiceType::SetDataValues, "SetDataValues"),
92    (ServiceType::GetDataDirectory, "GetDataDirectory"),
93    (ServiceType::GetDataDefinition, "GetDataDefinition"),
94    (ServiceType::GetDataSetValues, "GetDataSetValues"),
95    (ServiceType::SetDataSetValues, "SetDataSetValues"),
96    (ServiceType::CreateDataSet, "CreateDataSet"),
97    (ServiceType::DeleteDataSet, "DeleteDataSet"),
98    (ServiceType::GetDataSetDirectory, "GetDataSetDirectory"),
99    (ServiceType::SelectActiveSG, "SelectActiveSG"),
100    (ServiceType::SelectEditSG, "SelectEditSG"),
101    (ServiceType::SetEditSGValue, "SetEditSGValue"),
102    (ServiceType::ConfirmEditSGValues, "ConfirmEditSGValues"),
103    (ServiceType::GetEditSGValue, "GetEditSGValue"),
104    (ServiceType::GetSGCBValues, "GetSGCBValues"),
105    (ServiceType::Report, "Report"),
106    (ServiceType::GetBRCBValues, "GetBRCBValues"),
107    (ServiceType::SetBRCBValues, "SetBRCBValues"),
108    (ServiceType::GetURCBValues, "GetURCBValues"),
109    (ServiceType::SetURCBValues, "SetURCBValues"),
110    (ServiceType::GetLCBValues, "GetLCBValues"),
111    (ServiceType::SetLCBValues, "SetLCBValues"),
112    (ServiceType::QueryLogByTime, "QueryLogByTime"),
113    (ServiceType::QueryLogAfter, "QueryLogAfter"),
114    (ServiceType::GetLogStatusValues, "GetLogStatusValues"),
115    (ServiceType::SendGOOSEMessage, "SendGOOSEMessage"),
116    (ServiceType::GetGoCBValues, "GetGoCBValues"),
117    (ServiceType::SetGoCBValues, "SetGoCBValues"),
118    (ServiceType::GetGoReference, "GetGoReference"),
119    (ServiceType::GetGOOSEElementNumber, "GetGOOSEElementNumber"),
120    (ServiceType::SendMSVMessage, "SendMSVMessage"),
121    (ServiceType::GetMSVCBValues, "GetMSVCBValues"),
122    (ServiceType::SetMSVCBValues, "SetMSVCBValues"),
123    (ServiceType::SendUSVMessage, "SendUSVMessage"),
124    (ServiceType::GetUSVCBValues, "GetUSVCBValues"),
125    (ServiceType::SetUSVCBValues, "SetUSVCBValues"),
126    (ServiceType::Select, "Select"),
127    (ServiceType::SelectWithValue, "SelectWithValue"),
128    (ServiceType::Cancel, "Cancel"),
129    (ServiceType::Operate, "Operate"),
130    (ServiceType::CommandTermination, "CommandTermination"),
131    (ServiceType::TimeActivatedOperate, "TimeActivatedOperate"),
132    (ServiceType::GetFile, "GetFile"),
133    (ServiceType::SetFile, "SetFile"),
134    (ServiceType::DeleteFile, "DeleteFile"),
135    (ServiceType::GetFileAttributeValues, "GetFileAttributeValues"),
136    (ServiceType::TimeSynchronization, "TimeSynchronization"),
137    (ServiceType::InternalChange, "InternalChange"),
138];
139
140impl ServiceType {
141    /// The name IEC 61850-7-2 gives it, which is also what an SCL `EnumVal` spells.
142    pub fn as_str(self) -> &'static str {
143        SERVICE_TYPES.iter().find(|(v, _)| *v == self).map_or("InternalChange", |(_, n)| *n)
144    }
145
146    /// The service of that name, if the standard has one.
147    pub fn parse(name: &str) -> Option<ServiceType> {
148        SERVICE_TYPES.iter().find(|(_, n)| *n == name).map(|(v, _)| *v)
149    }
150
151    /// Its position in Table 26 — the ordinal to use when the file declares no `EnumType`.
152    ///
153    /// This is a **fallback and not a claim**: the name-to-number mapping is IEC 61850-8-1's
154    /// and is paywalled, so a file that declares the enumeration wins, always.
155    pub fn table_ordinal(self) -> i64 {
156        SERVICE_TYPES.iter().position(|(v, _)| *v == self).map_or(0, |i| i as i64)
157    }
158}
159
160impl core::fmt::Display for ServiceType {
161    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
162        f.write_str(self.as_str())
163    }
164}
165
166/// The result a tracking data object reports (IEC 61850-7-2 Table 5 ✅).
167///
168/// `NoError` is not "nothing to say": a successful service is tracked too, because an operator
169/// asking who enabled a control block needs the yes as much as the no.
170#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
171#[non_exhaustive]
172#[allow(missing_docs)] // as above: the name is the error.
173pub enum ServiceError {
174    InstanceNotAvailable,
175    InstanceInUse,
176    AccessViolation,
177    AccessNotAllowedInCurrentState,
178    ParameterValueInappropriate,
179    ParameterValueInconsistent,
180    ClassNotSupported,
181    InstanceLockedByOtherClient,
182    ControlMustBeSelected,
183    TypeConflict,
184    FailedDueToCommunicationsConstraint,
185    FailedDueToServerConstraint,
186    NoError,
187}
188
189/// The names, in the order IEC 61850-7-2 Table 5 lists them ✅.
190const SERVICE_ERRORS: [(ServiceError, &str); 13] = [
191    (ServiceError::InstanceNotAvailable, "instance-not-available"),
192    (ServiceError::InstanceInUse, "instance-in-use"),
193    (ServiceError::AccessViolation, "access-violation"),
194    (ServiceError::AccessNotAllowedInCurrentState, "access-not-allowed-in-current-state"),
195    (ServiceError::ParameterValueInappropriate, "parameter-value-inappropriate"),
196    (ServiceError::ParameterValueInconsistent, "parameter-value-inconsistent"),
197    (ServiceError::ClassNotSupported, "class-not-supported"),
198    (ServiceError::InstanceLockedByOtherClient, "instance-locked-by-other-client"),
199    (ServiceError::ControlMustBeSelected, "control-must-be-selected"),
200    (ServiceError::TypeConflict, "type-conflict"),
201    (ServiceError::FailedDueToCommunicationsConstraint, "failed-due-to-communications-constraint"),
202    (ServiceError::FailedDueToServerConstraint, "failed-due-to-server-constraint"),
203    (ServiceError::NoError, "no-error"),
204];
205
206impl ServiceError {
207    /// The name IEC 61850-7-2 gives it, which is also what an SCL `EnumVal` spells.
208    pub fn as_str(self) -> &'static str {
209        SERVICE_ERRORS.iter().find(|(v, _)| *v == self).map_or("no-error", |(_, n)| *n)
210    }
211
212    /// The error of that name, if the standard has one.
213    pub fn parse(name: &str) -> Option<ServiceError> {
214        SERVICE_ERRORS.iter().find(|(_, n)| *n == name).map(|(v, _)| *v)
215    }
216
217    /// Its position in Table 5 — the ordinal for a file that declares no `EnumType`.
218    pub fn table_ordinal(self) -> i64 {
219        SERVICE_ERRORS.iter().position(|(v, _)| *v == self).map_or(0, |i| i as i64)
220    }
221
222    /// The tracking error an ISO 9506 `DataAccessError` code maps to.
223    ///
224    /// The MMS mapping refuses with a `DataAccessError` and the tracking object publishes a
225    /// 7-2 `ServiceError`, so one has to become the other. Where the tables do not line up the
226    /// answer is the nearest true *statement*, not the nearest number.
227    pub const fn from_data_access(code: i64) -> ServiceError {
228        match code {
229            // `object-invalidated`, `object-undefined`, `object-non-existent`
230            0 | 4 | 10 => ServiceError::InstanceNotAvailable,
231            // `temporarily-unavailable`
232            2 => ServiceError::AccessNotAllowedInCurrentState,
233            // `object-access-denied`
234            3 => ServiceError::AccessViolation,
235            // `invalid-address`, `object-value-invalid`
236            5 | 11 => ServiceError::ParameterValueInappropriate,
237            // `type-unsupported`, `type-inconsistent`
238            6 | 7 => ServiceError::TypeConflict,
239            // `object-attribute-inconsistent`
240            8 => ServiceError::ParameterValueInconsistent,
241            // `object-access-unsupported`
242            9 => ServiceError::ClassNotSupported,
243            // `hardware-fault`, and anything the table does not name.
244            _ => ServiceError::FailedDueToServerConstraint,
245        }
246    }
247}
248
249impl core::fmt::Display for ServiceError {
250    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
251        f.write_str(self.as_str())
252    }
253}
254
255/// The common data classes IEC 61850-7-2 §14/§15.3.2/§20.6.2 defines for tracking ✅.
256///
257/// A logical device holds **no more than one** data object of each (§14.1). IEC 61850-7-4 names
258/// them, which this crate does not need to know: the file declares the `cdc` and the server
259/// finds the object by that.
260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
261pub enum TrackingCdc {
262    /// Common service tracking — anything not covered by a more specific one.
263    Cst,
264    /// Buffered report control block.
265    Bts,
266    /// Unbuffered report control block.
267    Uts,
268    /// Log control block.
269    Lts,
270    /// A log, and the two queries over it.
271    Ots,
272    /// GOOSE control block.
273    Gts,
274    /// Multicast sampled-value control block.
275    Mts,
276    /// Unicast sampled-value control block.
277    Nts,
278    /// Setting group control block.
279    Sts,
280    /// Control services on a controllable object.
281    Cts,
282}
283
284impl TrackingCdc {
285    /// The `cdc` string an SCL `DOType` carries for it.
286    pub const fn as_str(self) -> &'static str {
287        match self {
288            TrackingCdc::Cst => "CST",
289            TrackingCdc::Bts => "BTS",
290            TrackingCdc::Uts => "UTS",
291            TrackingCdc::Lts => "LTS",
292            TrackingCdc::Ots => "OTS",
293            TrackingCdc::Gts => "GTS",
294            TrackingCdc::Mts => "MTS",
295            TrackingCdc::Nts => "NTS",
296            TrackingCdc::Sts => "STS",
297            TrackingCdc::Cts => "CTS",
298        }
299    }
300
301    /// The tracking class of that `cdc`, if it is one.
302    pub fn parse(cdc: &str) -> Option<TrackingCdc> {
303        [
304            TrackingCdc::Cst,
305            TrackingCdc::Bts,
306            TrackingCdc::Uts,
307            TrackingCdc::Lts,
308            TrackingCdc::Ots,
309            TrackingCdc::Gts,
310            TrackingCdc::Mts,
311            TrackingCdc::Nts,
312            TrackingCdc::Sts,
313            TrackingCdc::Cts,
314        ]
315        .into_iter()
316        .find(|c| c.as_str() == cdc)
317    }
318}
319
320/// One service, as a tracking data object records it.
321///
322/// The block-specific half — `rptID`, `goEna`, `actSG`, … — is deliberately absent: those are
323/// the control block's own attributes with a lower-case first letter, so the engine copies them
324/// from the block [`Tracked::obj_ref`] names.
325#[derive(Clone, Debug, PartialEq)]
326pub struct Tracked {
327    /// Which tracking data object records it.
328    pub cdc: TrackingCdc,
329    /// `objRef` — the control block that was accessed, or the object that was controlled.
330    pub obj_ref: String,
331    /// `serviceType`.
332    pub service: ServiceType,
333    /// `errorCode` — `NoError` for a service that worked, which is tracked too.
334    pub error: ServiceError,
335    /// `originatorID` — who asked. The peer's network address, which is what the transport
336    /// knows and the ACSI layer cannot invent (the same octets `Owner` carries).
337    pub originator: Vec<u8>,
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    #[test]
345    fn the_lists_are_the_standards_lists() {
346        // Round-trip every name, because the name is what an SCL `EnumVal` spells and the
347        // whole ordinal-from-the-file design rests on matching it.
348        for (v, n) in SERVICE_TYPES {
349            assert_eq!(ServiceType::parse(n), Some(v));
350            assert_eq!(v.as_str(), n);
351        }
352        for (v, n) in SERVICE_ERRORS {
353            assert_eq!(ServiceError::parse(n), Some(v));
354            assert_eq!(v.as_str(), n);
355        }
356        // The fallback ordinals are positions in Table 26 and Table 5.
357        assert_eq!(ServiceType::GetServerDirectory.table_ordinal(), 0);
358        assert_eq!(ServiceType::SetBRCBValues.table_ordinal(), 23);
359        assert_eq!(ServiceError::NoError.table_ordinal(), 12);
360        assert_eq!(ServiceType::parse("NoSuchService"), None);
361    }
362
363    #[test]
364    fn a_refused_service_keeps_its_meaning_across_the_two_tables() {
365        // The MMS mapping answers with a `DataAccessError` and the tracking object publishes a
366        // 7-2 `ServiceError`; what has to survive is the *statement*, not the number.
367        // The codes are ISO 9506's `DataAccessError`, and 0 is `object-invalidated` rather
368        // than success — a success never reaches here, because `Ok(())` is `NoError` directly.
369        assert_eq!(ServiceError::from_data_access(3), ServiceError::AccessViolation);
370        assert_eq!(ServiceError::from_data_access(10), ServiceError::InstanceNotAvailable);
371        assert_eq!(ServiceError::from_data_access(0), ServiceError::InstanceNotAvailable);
372        assert_eq!(ServiceError::from_data_access(7), ServiceError::TypeConflict);
373        // Anything the table does not name is a server constraint rather than a guess.
374        assert_eq!(ServiceError::from_data_access(99), ServiceError::FailedDueToServerConstraint);
375    }
376
377    #[test]
378    fn a_tracking_cdc_is_recognised_by_the_cdc_the_file_declares() {
379        assert_eq!(TrackingCdc::parse("BTS"), Some(TrackingCdc::Bts));
380        assert_eq!(TrackingCdc::parse("CTS"), Some(TrackingCdc::Cts));
381        // An ordinary data object is not a tracker, which is what stops the engine writing
382        // into a breaker position that happens to sit in the same logical device.
383        assert_eq!(TrackingCdc::parse("DPC"), None);
384    }
385}