Skip to main content

mbus_kit/
error.rs

1use core::fmt;
2
3/// Result type of this crate.
4pub type Result<T> = core::result::Result<T, Error>;
5
6/// Everything that can go wrong between the meter's bytes and a typed record.
7///
8/// Every variant is a property of the input, never of this crate's state.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum Error {
12    /// The input ended in the middle of a frame or record.
13    UnexpectedEnd,
14    /// The first byte is not a known frame start (`E5`, `10`, `68`).
15    InvalidStart(u8),
16    /// The two length bytes of a long frame differ, or the second `68` is missing.
17    InvalidHeader,
18    /// The stop byte (`16`) is missing.
19    MissingStop,
20    /// The wired checksum does not match.
21    Checksum {
22        /// Checksum computed over the frame.
23        computed: u8,
24        /// Checksum on the wire.
25        found: u8,
26    },
27    /// A wireless block CRC does not match.
28    Crc {
29        /// The block (0-based) whose CRC failed.
30        block: usize,
31        /// CRC computed over the block.
32        computed: u16,
33        /// CRC on the wire.
34        found: u16,
35    },
36    /// A length field is inconsistent with the frame.
37    InvalidLength,
38    /// More than 10 DIFE or VIFE bytes follow one another.
39    TooManyExtensions,
40    /// A reserved special-function DIF (`3F`…`6F`).
41    ReservedDif(u8),
42    /// An LVAR value in a reserved range.
43    UnsupportedLvar(u8),
44    /// The CI field announces something this crate does not parse yet.
45    UnsupportedCi(u8),
46    /// The output buffer is too small for what is being written.
47    OutputTooSmall,
48    /// A layer appears where it may not (e.g. a second ELL, or an AFL after the TPL).
49    UnexpectedLayer(u8),
50    /// The telegram is encrypted with a security mode this crate does not decrypt.
51    UnsupportedSecurity(u8),
52    /// No key for this meter in the key lookup.
53    NoKey,
54    /// A compact frame whose layout (format signature) is not known yet: wait for a full
55    /// frame of this meter and remember its [`Format`](crate::compact::Format).
56    UnknownFormat(u16),
57    /// A compact-frame layout that cannot describe values: a special DIF (manufacturer
58    /// data, filler) or a plain-text unit in it.
59    InvalidFormat,
60    /// A fragment that does not continue the message in progress: missing, repeated or
61    /// out of order (`found` is its fragment ID; 0 for a telegram that is not a fragment).
62    UnexpectedFragment {
63        /// The fragment ID expected next (1 when no message is open).
64        expected: u8,
65        /// The fragment ID received.
66        found: u8,
67    },
68    /// A fragment from another meter than the message in progress.
69    FragmentFromOtherMeter,
70    /// Decryption or authentication failed: the check that failed, never the key.
71    Verification(Check),
72    /// A wired primary address no slave answers from: 251 and 252 are reserved, 255 is
73    /// the broadcast without reply.
74    InvalidAddress(u8),
75}
76
77/// Which cryptographic check failed. Says nothing about the key (constitution IV).
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79#[non_exhaustive]
80pub enum Check {
81    /// The decrypted payload does not start with `2F 2F` (wrong key, or tampered).
82    Marker,
83    /// The AFL message authentication code does not match, or the message control
84    /// announces one that is missing.
85    Mac,
86    /// The ELL payload CRC over the decrypted payload does not match.
87    PayloadCrc,
88    /// The encrypted part is not a whole number of 16-byte blocks, or shorter than
89    /// the configuration field announces.
90    Length,
91    /// Security mode 7 without the AFL message counter the key derivation needs.
92    MissingCounter,
93    /// The records rebuilt from a compact frame do not match its full-frame CRC.
94    FullFrameCrc,
95    /// The AES-CCM tag of a mode-10 telegram does not match.
96    Tag,
97}
98
99impl fmt::Display for Check {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        f.write_str(match self {
102            Self::Marker => "decrypted payload does not start with 2F 2F",
103            Self::Mac => "message authentication code mismatch",
104            Self::PayloadCrc => "ELL payload CRC mismatch",
105            Self::Length => "encrypted length is not a whole number of blocks, or longer than the data",
106            Self::MissingCounter => "mode 7 without AFL message counter",
107            Self::FullFrameCrc => "compact frame does not match its full-frame CRC",
108            Self::Tag => "AES-CCM tag mismatch",
109        })
110    }
111}
112
113impl fmt::Display for Error {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        match self {
116            Self::UnexpectedEnd => f.write_str("input ended in the middle of a value"),
117            Self::InvalidStart(b) => write!(f, "0x{b:02x} is not a frame start"),
118            Self::InvalidHeader => f.write_str("malformed long-frame header"),
119            Self::MissingStop => f.write_str("stop byte 0x16 missing"),
120            Self::Checksum { computed, found } => {
121                write!(f, "checksum 0x{found:02x} does not match computed 0x{computed:02x}")
122            }
123            Self::Crc { block, computed, found } => {
124                write!(f, "CRC of block {block} is 0x{found:04x}, computed 0x{computed:04x}")
125            }
126            Self::InvalidLength => f.write_str("length field inconsistent with the frame"),
127            Self::TooManyExtensions => f.write_str("more than 10 extension bytes"),
128            Self::ReservedDif(d) => write!(f, "reserved DIF 0x{d:02x}"),
129            Self::UnsupportedLvar(l) => write!(f, "LVAR 0x{l:02x} is reserved or unsupported"),
130            Self::UnsupportedCi(c) => write!(f, "CI field 0x{c:02x} is not supported yet"),
131            Self::OutputTooSmall => f.write_str("output buffer too small"),
132            Self::UnexpectedLayer(c) => {
133                write!(f, "CI 0x{c:02x} is not allowed at this point of the telegram")
134            }
135            Self::UnsupportedSecurity(m) => write!(f, "security mode {m} is not supported"),
136            Self::NoKey => f.write_str("no key for this meter"),
137            Self::UnknownFormat(s) => write!(f, "compact frame with unknown format signature 0x{s:04x}"),
138            Self::InvalidFormat => f.write_str("compact-frame layout with a special DIF or plain-text unit"),
139            Self::UnexpectedFragment { expected, found: 0 } => {
140                write!(f, "not a fragment (expected fragment {expected})")
141            }
142            Self::UnexpectedFragment { expected, found } => {
143                write!(f, "fragment {found} where fragment {expected} was expected")
144            }
145            Self::FragmentFromOtherMeter => f.write_str("fragment from another meter"),
146            Self::Verification(c) => write!(f, "verification failed: {c}"),
147            Self::InvalidAddress(a) => write!(f, "no meter answers from primary address {a}"),
148        }
149    }
150}
151
152#[cfg(feature = "std")]
153impl std::error::Error for Error {}