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