Skip to main content

mbus_kit/
wired.rs

1//! Wired M-Bus link layer (EN 13757-2, the FT1.2 format of IEC 60870-5-2).
2//!
3//! ```text
4//! E5                                      single character (ACK)
5//! 10 C A CS 16                            short frame
6//! 68 L L 68 C A CI [data…] CS 16          control (L = 3) and long frame
7//! ```
8//!
9//! `L` counts the bytes from `C` to the last data byte. `CS` is their arithmetic sum
10//! modulo 256 (for a short frame, `C + A`).
11
12use crate::{Error, Result};
13
14/// The single-character acknowledgement.
15pub const ACK: u8 = 0xE5;
16const SHORT_START: u8 = 0x10;
17const LONG_START: u8 = 0x68;
18const STOP: u8 = 0x16;
19
20/// C-field values a master sends.
21pub mod control {
22    /// `SND_NKE`: initialise the slave (reset the FCB).
23    pub const SND_NKE: u8 = 0x40;
24    /// `SND_UD`: send user data to the slave (FCB clear).
25    pub const SND_UD: u8 = 0x53;
26    /// `REQ_UD2`: request class 2 data, i.e. the meter reading (FCB clear).
27    pub const REQ_UD2: u8 = 0x5B;
28    /// The frame count bit, toggled between successive requests.
29    pub const FCB: u8 = 0x20;
30    /// `RSP_UD`: a slave's response (lower nibble 8; ACD and DFC bits may be set).
31    pub const RSP_UD: u8 = 0x08;
32}
33
34/// The primary address that addresses every slave (no reply expected).
35pub const BROADCAST: u8 = 0xFF;
36/// The primary address that addresses the selected slave (secondary addressing).
37pub const NETWORK_LAYER: u8 = 0xFD;
38
39/// A wired M-Bus frame.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum Frame<'a> {
42    /// `E5`: acknowledgement.
43    Ack,
44    /// A short frame: a request without data.
45    Short {
46        /// C field.
47        c: u8,
48        /// Primary address.
49        a: u8,
50    },
51    /// A long (or control, when `data` is empty) frame.
52    Long {
53        /// C field.
54        c: u8,
55        /// Primary address.
56        a: u8,
57        /// CI field: what the data is.
58        ci: u8,
59        /// The application data after the CI field.
60        data: &'a [u8],
61    },
62}
63
64fn sum(bytes: &[u8]) -> u8 {
65    bytes.iter().fold(0u8, |s, &b| s.wrapping_add(b))
66}
67
68impl<'a> Frame<'a> {
69    /// Parse one frame at the start of `buf`.
70    ///
71    /// Returns `Ok(None)` when `buf` holds the beginning of a valid frame but not all of
72    /// it yet (read more and call again), and the frame with the number of bytes it
73    /// used otherwise.
74    pub fn parse(buf: &'a [u8]) -> Result<Option<(Self, usize)>> {
75        let Some(&start) = buf.first() else { return Ok(None) };
76        match start {
77            ACK => Ok(Some((Self::Ack, 1))),
78            SHORT_START => {
79                let Some(&[_, c, a, cs, stop]) = buf.get(..5).and_then(|s| <&[u8; 5]>::try_from(s).ok())
80                else {
81                    return Ok(None);
82                };
83                check(sum(&[c, a]), cs, stop)?;
84                Ok(Some((Self::Short { c, a }, 5)))
85            }
86            LONG_START => {
87                let Some(&[_, l1, l2, s2]) = buf.get(..4).and_then(|s| <&[u8; 4]>::try_from(s).ok()) else {
88                    return Ok(None);
89                };
90                if l1 != l2 || s2 != LONG_START || l1 < 3 {
91                    return Err(Error::InvalidHeader);
92                }
93                let l = usize::from(l1);
94                let total = l + 6;
95                let Some(frame) = buf.get(..total) else { return Ok(None) };
96                let user = frame.get(4..4 + l).ok_or(Error::UnexpectedEnd)?;
97                let cs = frame.get(4 + l).copied().ok_or(Error::UnexpectedEnd)?;
98                let stop = frame.get(5 + l).copied().ok_or(Error::UnexpectedEnd)?;
99                check(sum(user), cs, stop)?;
100                let (&c, rest) = user.split_first().ok_or(Error::UnexpectedEnd)?;
101                let (&a, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
102                let (&ci, data) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
103                Ok(Some((Self::Long { c, a, ci, data }, total)))
104            }
105            other => Err(Error::InvalidStart(other)),
106        }
107    }
108
109    /// Write the frame into `out`. Returns the number of bytes written.
110    pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
111        match *self {
112            Self::Ack => {
113                *out.first_mut().ok_or(Error::OutputTooSmall)? = ACK;
114                Ok(1)
115            }
116            Self::Short { c, a } => {
117                let bytes = [SHORT_START, c, a, sum(&[c, a]), STOP];
118                out.get_mut(..5).ok_or(Error::OutputTooSmall)?.copy_from_slice(&bytes);
119                Ok(5)
120            }
121            Self::Long { c, a, ci, data } => {
122                let l = data.len().checked_add(3).filter(|&l| l <= 255).ok_or(Error::InvalidLength)?;
123                let total = l + 6;
124                let frame = out.get_mut(..total).ok_or(Error::OutputTooSmall)?;
125                let l8 = u8::try_from(l).map_err(|_| Error::InvalidLength)?;
126                let (head, rest) = frame.split_at_mut(7);
127                head.copy_from_slice(&[LONG_START, l8, l8, LONG_START, c, a, ci]);
128                let (body, tail) = rest.split_at_mut(data.len());
129                body.copy_from_slice(data);
130                let cs = sum(&[c, a, ci]).wrapping_add(sum(data));
131                tail.copy_from_slice(&[cs, STOP]);
132                Ok(total)
133            }
134        }
135    }
136}
137
138/// What [`scan`] found in a receive buffer.
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub enum Scan<'a> {
141    /// A valid frame starting `skip` bytes into the buffer and using `len` bytes. Drop
142    /// `skip + len` bytes before scanning again.
143    Frame {
144        /// The frame.
145        frame: Frame<'a>,
146        /// Bytes of noise before it.
147        skip: usize,
148        /// Bytes the frame uses.
149        len: usize,
150    },
151    /// No complete frame yet: drop `skip` bytes of noise, keep the rest, read more.
152    NeedMore {
153        /// Bytes that cannot start a frame and can be dropped.
154        skip: usize,
155    },
156}
157
158/// Find the first valid frame in a receive buffer that may begin with noise, an echo or
159/// the tail of a broken frame (what a level converter delivers on a real bus).
160///
161/// Every byte that cannot start a valid frame is skipped. The first start byte whose frame
162/// is still incomplete wins: the rest may be arriving, and its data can contain bytes that
163/// look like a frame of their own (an `E5`, a `10 … 16`). A stray start byte in front of a
164/// reply is resolved as soon as enough bytes arrive to show its frame is invalid (wrong
165/// length bytes, checksum or stop byte). Checksums are verified for every frame.
166pub fn scan(buf: &[u8]) -> Scan<'_> {
167    for start in 0..buf.len() {
168        let Some(rest) = buf.get(start..) else { break };
169        match Frame::parse(rest) {
170            Ok(Some((frame, len))) => return Scan::Frame { frame, skip: start, len },
171            Ok(None) => return Scan::NeedMore { skip: start },
172            Err(_) => {}
173        }
174    }
175    Scan::NeedMore { skip: buf.len() }
176}
177
178fn check(computed: u8, found: u8, stop: u8) -> Result<()> {
179    if computed != found {
180        return Err(Error::Checksum { computed, found });
181    }
182    if stop != STOP {
183        return Err(Error::MissingStop);
184    }
185    Ok(())
186}
187
188/// `SND_NKE` to a primary address: reset the slave's link layer.
189pub const fn snd_nke(address: u8) -> Frame<'static> {
190    Frame::Short { c: control::SND_NKE, a: address }
191}
192
193/// `REQ_UD2` to a primary address: ask for the meter reading. Toggle `fcb` between
194/// successive requests to the same slave.
195pub const fn req_ud2(address: u8, fcb: bool) -> Frame<'static> {
196    Frame::Short { c: control::REQ_UD2 | if fcb { control::FCB } else { 0 }, a: address }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn short_frame_round_trip() {
205        let mut out = [0u8; 8];
206        let n = req_ud2(5, true).encode(&mut out).unwrap();
207        assert_eq!(&out[..n], &[0x10, 0x7B, 0x05, 0x80, 0x16]);
208        assert_eq!(Frame::parse(&out[..n]).unwrap(), Some((req_ud2(5, true), 5)));
209    }
210
211    #[test]
212    fn incomplete_frames_ask_for_more() {
213        let mut out = [0u8; 16];
214        let n = Frame::Long { c: 0x08, a: 1, ci: 0x72, data: &[1, 2, 3] }.encode(&mut out).unwrap();
215        for cut in 0..n {
216            assert_eq!(Frame::parse(&out[..cut]).unwrap(), None, "cut at {cut}");
217        }
218        assert!(Frame::parse(&out[..n]).unwrap().is_some());
219    }
220
221    #[test]
222    fn scan_skips_noise_and_false_starts() {
223        let mut buf = [0u8; 32];
224        let n = req_ud2(5, true).encode(&mut buf[3..]).unwrap();
225        buf[..3].copy_from_slice(&[0x00, 0x68, 0x42]); // noise, a false long-frame start
226        let all = &buf[..3 + n];
227        assert_eq!(scan(all), Scan::Frame { frame: req_ud2(5, true), skip: 3, len: 5 });
228        // Incomplete: keep from the first plausible start (68 42 10 7B is no header).
229        assert_eq!(scan(&all[..3 + 3]), Scan::NeedMore { skip: 3 });
230        assert_eq!(scan(&[0x00, 0x68, 0x05]), Scan::NeedMore { skip: 1 });
231        assert_eq!(scan(&[0x00, 0x01, 0x02]), Scan::NeedMore { skip: 3 });
232        assert_eq!(scan(&[]), Scan::NeedMore { skip: 0 });
233        // An ACK after an echo of our own request.
234        let mut echo = [0u8; 6];
235        echo[..5].copy_from_slice(&all[3..]);
236        echo[5] = ACK;
237        assert_eq!(scan(&echo), Scan::Frame { frame: req_ud2(5, true), skip: 0, len: 5 });
238        // A long frame still arriving whose data holds an E5: wait, never an ACK (review
239        // 2026-11-27: the readout ended with no telegram).
240        let mut long = [0u8; 64];
241        let data =
242            [0x78, 0x56, 0x34, 0x12, 0x24, 0x40, 0x01, 0x07, 0x55, 0, 0, 0, 0x03, 0x13, 0xE5, 0x31, 0x00];
243        let n = Frame::Long { c: 0x08, a: 5, ci: 0x72, data: &data }.encode(&mut long).unwrap();
244        for cut in 1..n {
245            assert_eq!(scan(&long[..cut]), Scan::NeedMore { skip: 0 }, "cut {cut}");
246        }
247        assert!(matches!(scan(&long[..n]), Scan::Frame { skip: 0, .. }));
248    }
249
250    #[test]
251    fn bad_checksum_and_stop() {
252        assert!(matches!(Frame::parse(&[0x10, 0x5B, 0x01, 0x00, 0x16]), Err(Error::Checksum { .. })));
253        assert_eq!(Frame::parse(&[0x10, 0x5B, 0x01, 0x5C, 0x17]), Err(Error::MissingStop));
254        assert_eq!(Frame::parse(&[0x68, 0x05, 0x06, 0x68]), Err(Error::InvalidHeader));
255        assert_eq!(Frame::parse(&[0x42]), Err(Error::InvalidStart(0x42)));
256    }
257}