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 a readout cannot read: 251 and 252 are reserved, 253
85    /// reaches a selected slave (read it as a secondary target), 255 is the broadcast
86    /// without reply.
87    InvalidAddress(u8),
88    /// A number of bits per second that is not one of the eight M-Bus baud rates.
89    InvalidBaud(u32),
90}
91
92/// Which cryptographic check failed. Says nothing about the key (constitution IV).
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94#[non_exhaustive]
95pub enum Check {
96    /// The decrypted payload does not start with `2F 2F` (wrong key, or tampered).
97    Marker,
98    /// The AFL message authentication code does not match, or the message control
99    /// announces one that is missing.
100    Mac,
101    /// The ELL payload CRC over the decrypted payload does not match.
102    PayloadCrc,
103    /// The encrypted part is not a whole number of 16-byte blocks, or shorter than
104    /// the configuration field announces.
105    Length,
106    /// Security mode 7 without the AFL message counter the key derivation needs.
107    MissingCounter,
108    /// The records rebuilt from a compact frame do not match its full-frame CRC.
109    FullFrameCrc,
110    /// The AES-CCM tag of a mode-10 telegram does not match.
111    Tag,
112}
113
114impl fmt::Display for Check {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        f.write_str(match self {
117            Self::Marker => "decrypted payload does not start with 2F 2F",
118            Self::Mac => "message authentication code mismatch",
119            Self::PayloadCrc => "ELL payload CRC mismatch",
120            Self::Length => "encrypted length is not a whole number of blocks, or longer than the data",
121            Self::MissingCounter => "mode 7 without AFL message counter",
122            Self::FullFrameCrc => "compact frame does not match its full-frame CRC",
123            Self::Tag => "AES-CCM tag mismatch",
124        })
125    }
126}
127
128impl fmt::Display for Error {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        match self {
131            Self::UnexpectedEnd => f.write_str("input ended in the middle of a value"),
132            Self::InvalidStart(b) => write!(f, "0x{b:02x} is not a frame start"),
133            Self::InvalidHeader => f.write_str("malformed long-frame header"),
134            Self::MissingStop => f.write_str("stop byte 0x16 missing"),
135            Self::Checksum { computed, found } => {
136                write!(f, "checksum 0x{found:02x} does not match computed 0x{computed:02x}")
137            }
138            Self::Crc { block, computed, found } => {
139                write!(f, "CRC of block {block} is 0x{found:04x}, computed 0x{computed:04x}")
140            }
141            Self::InvalidLength => f.write_str("length field inconsistent with the frame"),
142            Self::TooManyExtensions => f.write_str("more than 10 extension bytes"),
143            Self::ReservedDif(d) => write!(f, "reserved DIF 0x{d:02x}"),
144            Self::UnsupportedLvar(l) => write!(f, "LVAR 0x{l:02x} is reserved or unsupported"),
145            Self::UnsupportedCi(c) => write!(f, "CI field 0x{c:02x} is not supported yet"),
146            Self::OutputTooSmall => f.write_str("output buffer too small"),
147            Self::UnexpectedLayer(c) => {
148                write!(f, "CI 0x{c:02x} is not allowed at this point of the telegram")
149            }
150            Self::UnsupportedSecurity(m) => write!(f, "security mode {m} is not supported"),
151            Self::NoKey => f.write_str("no key for this meter"),
152            Self::UnknownFormat(s) => write!(f, "compact frame with unknown format signature 0x{s:04x}"),
153            Self::InvalidFormat => f.write_str("compact-frame layout with a special DIF or plain-text unit"),
154            Self::UnexpectedFragment { expected, found: 0 } => {
155                write!(f, "not a fragment (expected fragment {expected})")
156            }
157            Self::UnexpectedFragment { expected, found } => {
158                write!(f, "fragment {found} where fragment {expected} was expected")
159            }
160            Self::FragmentFromOtherMeter => f.write_str("fragment from another meter"),
161            Self::Verification(c) => write!(f, "verification failed: {c}"),
162            Self::InvalidAddress(a) => write!(f, "primary address {a} cannot be read"),
163            Self::InvalidBaud(n) => write!(f, "M-Bus has no baud rate {n} (300 to 38400)"),
164        }
165    }
166}
167
168/// Also without `std`: a `no_std` crate can wrap it as a `source`, and a binary can `?` it
169/// into `Box<dyn Error>` with `default-features = false`.
170impl core::error::Error for Error {}