Skip to main content

iec61850_kit/common/
error.rs

1use core::fmt;
2
3use alloc::string::String;
4
5/// The one error type of the crate.
6///
7/// Decoders never panic on input; every malformed byte becomes an [`Error::Decode`] with a
8/// stable reason and the byte offset it was found at.
9#[derive(Clone, Debug, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum Error {
12    /// The input did not decode. `offset` is measured from the start of the buffer handed
13    /// to the decoder.
14    Decode {
15        /// What was wrong.
16        reason: DecodeReason,
17        /// Byte offset of the problem.
18        offset: usize,
19    },
20    /// A configured limit (see [`crate::common::Limits`]) was exceeded before allocation.
21    LimitExceeded {
22        /// Which limit.
23        limit: &'static str,
24        /// The value that exceeded it.
25        value: usize,
26    },
27    /// The value cannot be encoded as requested (e.g. a string that is not ASCII in a
28    /// `VisibleString`, or a length above `u32::MAX`).
29    Encode(&'static str),
30    /// An object reference or SCL name is malformed.
31    InvalidReference(&'static str),
32    /// A referenced thing (IED, type, data set …) does not exist.
33    NotFound(&'static str),
34    /// A value is outside its domain (e.g. an APPID outside the GOOSE range).
35    InvalidValue(&'static str),
36    /// The SCL document is not well formed or violates the schema in a way the loader
37    /// cannot work around. The string is the loader's message.
38    Scl(String),
39    /// The transport failed: the socket errored, or the peer closed the connection under an
40    /// association that was still up.
41    Io(String),
42    /// The peer answered a confirmed request with an MMS `ServiceError`. `class` is the
43    /// `errorClass` choice tag (7 = access, 8 = initiate, …) and `code` the integer inside
44    /// it, which is what IEC 61850-8-1 maps the ACSI service errors onto.
45    Service {
46        /// The `errorClass` choice tag.
47        class: u32,
48        /// The integer that choice carries.
49        code: i64,
50    },
51    /// One value of a `Read` or `Write` failed with an MMS `DataAccessError`: 10 is
52    /// object-non-existent, 3 object-access-denied, 11 object-access-unsupported.
53    DataAccess(i64),
54    /// The peer **rejected** the PDU rather than failing the service: an unrecognised
55    /// service, an invoke identifier it cannot use, more requests outstanding than were
56    /// negotiated, or octets it could not read as a PDU at all. Distinct from
57    /// [`Error::Service`], which is a service that ran and failed.
58    ///
59    /// The reason is carried as its two wire numbers rather than as the typed
60    /// `RejectReason`, for the same reason [`Error::ControlRejected`] carries a bare
61    /// `add_cause`: this module is `common`, and an error type that names a `proto::mms`
62    /// type cannot be built without the `mms` feature. `RejectReason::from_parts(tag, code)`
63    /// turns the pair back into the named value, and the tag matters — the same code means
64    /// different things under different tags.
65    Rejected {
66        /// The request it rejects, when the peer named one.
67        invoke_id: Option<i64>,
68        /// The `rejectReason` choice tag: 1 confirmed-request, 2 confirmed-response,
69        /// 3 confirmed-error, 4 unconfirmed, 5 pdu-error, …
70        reason_tag: u32,
71        /// The integer inside that choice.
72        code: i64,
73    },
74    /// A control was refused or abandoned. `add_cause` is the IEC 61850-8-1 Table 77 value —
75    /// `AddCause::from_code` names it — and it is the field that turns "the breaker did not
76    /// close" into a diagnosis.
77    ControlRejected {
78        /// The `AddCause`.
79        add_cause: i64,
80    },
81}
82
83/// Why a decode failed.
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
85#[non_exhaustive]
86pub enum DecodeReason {
87    /// Fewer bytes than the encoding requires.
88    Truncated,
89    /// A BER length that cannot be represented or is not allowed here.
90    BadLength,
91    /// Indefinite-length encoding, which this decoder does not accept.
92    IndefiniteLength,
93    /// A tag that is not valid at this position.
94    UnexpectedTag,
95    /// A required element is missing.
96    MissingField,
97    /// A primitive value is malformed (empty integer, bad float exponent width, …).
98    BadValue,
99    /// Nesting deeper than the configured limit.
100    TooDeep,
101    /// Trailing bytes after a complete element where none are allowed.
102    TrailingBytes,
103    /// A value that is not ASCII in a `VisibleString`.
104    NotAscii,
105    /// The Ethernet frame is not a GOOSE/SV frame (wrong `EtherType`) or too short.
106    NotProcessBusFrame,
107}
108
109/// The ISO 9506-2 name of a `ServiceError`'s `errorClass` tag ✅ (`mms.asn`).
110pub const fn service_error_class(class: u32) -> Option<&'static str> {
111    Some(match class {
112        0 => "vmd-state",
113        1 => "application-reference",
114        2 => "definition",
115        3 => "resource",
116        4 => "service",
117        5 => "service-preempt",
118        6 => "time-resolution",
119        7 => "access",
120        8 => "initiate",
121        9 => "conclude",
122        10 => "cancel",
123        11 => "file",
124        12 => "others",
125        _ => return None,
126    })
127}
128
129/// The ISO 9506-2 name of a `DataAccessError` code ✅ (`mms.asn`).
130///
131/// A bare number is the most common thing a user of an IEC 61850 client is left holding, and
132/// `3` versus `10` is the difference between "you may not" and "it is not there" — two
133/// completely different next steps. Naming it costs a table.
134pub const fn data_access_reason(code: i64) -> Option<&'static str> {
135    Some(match code {
136        0 => "object-invalidated",
137        1 => "hardware-fault",
138        2 => "temporarily-unavailable",
139        3 => "object-access-denied",
140        4 => "object-undefined",
141        5 => "invalid-address",
142        6 => "type-unsupported",
143        7 => "type-inconsistent",
144        8 => "object-attribute-inconsistent",
145        9 => "object-access-unsupported",
146        10 => "object-non-existent",
147        11 => "object-value-invalid",
148        _ => return None,
149    })
150}
151
152/// `Result` with the crate's [`Error`].
153pub type Result<T> = core::result::Result<T, Error>;
154
155impl Error {
156    pub(crate) const fn decode(reason: DecodeReason, offset: usize) -> Self {
157        Error::Decode { reason, offset }
158    }
159}
160
161impl fmt::Display for Error {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        match self {
164            Error::Decode { reason, offset } => write!(f, "decode error at byte {offset}: {reason:?}"),
165            Error::LimitExceeded { limit, value } => write!(f, "limit `{limit}` exceeded by {value}"),
166            Error::Encode(what) => write!(f, "encode error: {what}"),
167            Error::InvalidReference(what) => write!(f, "invalid object reference: {what}"),
168            Error::NotFound(what) => write!(f, "not found: {what}"),
169            Error::InvalidValue(what) => write!(f, "invalid value: {what}"),
170            Error::Scl(msg) => write!(f, "SCL: {msg}"),
171            Error::Io(msg) => write!(f, "transport: {msg}"),
172            Error::Service { class, code } => match service_error_class(*class) {
173                Some(name) => write!(f, "MMS service error: {name} (class {class}), code {code}"),
174                None => write!(f, "MMS service error: class {class}, code {code}"),
175            },
176            Error::DataAccess(code) => match data_access_reason(*code) {
177                Some(name) => write!(f, "MMS data access error {code} ({name})"),
178                None => write!(f, "MMS data access error {code}"),
179            },
180            Error::Rejected { invoke_id, reason_tag, code } => match invoke_id {
181                Some(id) => write!(f, "the peer rejected invoke {id}: reason {reason_tag}/{code}"),
182                None => write!(f, "the peer rejected the PDU: reason {reason_tag}/{code}"),
183            },
184            Error::ControlRejected { add_cause } => write!(f, "control rejected, AddCause {add_cause}"),
185        }
186    }
187}
188
189#[cfg(feature = "std")]
190impl std::error::Error for Error {}
191
192/// Reading a file into a model, or a socket into an association, is the ordinary thing to do
193/// with this crate, and both start with an `io::Error`. Without this a caller's `?` has to be
194/// spelt out at every boundary, which is the sort of friction that pushes people to
195/// `unwrap()`.
196#[cfg(feature = "std")]
197impl From<std::io::Error> for Error {
198    fn from(e: std::io::Error) -> Error {
199        Error::Io(e.to_string())
200    }
201}