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