Skip to main content

mbus_kit/
stick.rs

1//! Wireless M-Bus receiver sticks, sans-I/O: their serial protocols in, radio telegrams
2//! out.
3//!
4//! | Stick | Serial | Framing | Telegram | RSSI |
5//! |---|---|---|---|---|
6//! | IMST iM871A, iM170A | 57600 8N1 | `A5`, control/endpoint, message, length, payload, (timestamp), (RSSI), CRC-16/X-25 | L field = HCI length, then C … | raw, approximate dBm |
7//! | IMST iU891A, iM891A | 115200 8N1 | SLIP; SAP, message, payload, CRC-16/X-25 | L field first | dBm (signed) |
8//! | Amber/Würth AMB8465, AMB8665 (command mode) | 9600 8N1 | `FF`, command, length, payload, (RSSI), XOR | L field = length − 1 (with RSSI), then C … | dBm |
9//!
10//! Every stick checks and removes the link-layer CRCs: a [`Received`] frame starts at the
11//! L field and goes to [`wireless::decode`](crate::wireless::decode) or
12//! [`wireless::open`](crate::wireless::open) with
13//! [`Format::Stripped`](crate::wireless::Format::Stripped).
14//!
15//! ```
16//! use mbus_kit::stick::{LinkMode, Message, Receiver, Stick};
17//!
18//! let stick = Stick::Im871a;
19//! let listen = stick.listen(LinkMode::T1).unwrap(); // write listen.bytes() to the port once
20//! let mut rx = Receiver::new(stick);
21//! # let from_port = [0xA5u8, 0xC2, 0x03, 0x19, 0x44, 0x24, 0x23, 0x85, 0x07, 0x60, 0x14, 0x40, 0x18, 0xA1, 0x51, 0x49, 0x00, 0x13, 0x53, 0x55, 0xB8, 0x53, 0x18, 0x92, 0xDF, 0x2B, 0x27, 0x37, 0x34, 0x56, 0x60, 0xEB];
22//! rx.extend(&from_port); // whatever the port delivered, in any chunks
23//! while let Some(message) = rx.next_message() {
24//!     match message {
25//!         Ok(Message::Telegram(t)) => println!("{:02X?} at {:?} dBm", t.frame, t.rssi_dbm),
26//!         Ok(Message::Response { .. }) => { /* a confirmation of a command */ }
27//!         Err(e) => eprintln!("skipped: {e}"), // noise or a corrupted stick frame
28//!     }
29//! }
30//! ```
31//!
32//! The Amber sticks deliver telegrams framed only in command mode with RSSI: run
33//! [`Stick::setup`] once (it writes the stick's non-volatile settings), then
34//! [`Stick::listen`] after every power-up.
35
36use core::fmt;
37
38use crate::crc::crc16_x25;
39use crate::{Error, Result};
40
41/// A supported receiver stick.
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub enum Stick {
44    /// IMST iM871A (868 MHz) and iM170A (169 MHz): WM-Bus HCI 1.x.
45    Im871a,
46    /// IMST iU891A, iM891A, iU893A: the WM-Bus gateway HCI 2.x over SLIP.
47    Iu891a,
48    /// Amber/Würth AMB8465 (Metis-I) and AMB8665 (Metis-II), in command mode with RSSI.
49    Amb8465,
50}
51
52/// A link mode to receive.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54#[non_exhaustive]
55pub enum LinkMode {
56    /// S1 (stationary, 32.768 kcps).
57    S1,
58    /// T1 (frequent transmit, the most common for water and heat meters).
59    T1,
60    /// C1 (compact, formats A and B).
61    C1,
62    /// C1 and T1 at once.
63    C1T1,
64}
65
66impl fmt::Display for LinkMode {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.write_str(match self {
69            Self::S1 => "S1",
70            Self::T1 => "T1",
71            Self::C1 => "C1",
72            Self::C1T1 => "C1+T1",
73        })
74    }
75}
76
77/// Bytes to write to a stick.
78#[derive(Clone, Copy, PartialEq, Eq)]
79pub struct Command {
80    bytes: [u8; 32],
81    len: u8,
82}
83
84impl Command {
85    /// The bytes to write.
86    pub fn bytes(&self) -> &[u8] {
87        self.bytes.get(..usize::from(self.len)).unwrap_or(&[])
88    }
89
90    fn new() -> Self {
91        Self { bytes: [0; 32], len: 0 }
92    }
93
94    fn push(&mut self, b: u8) {
95        if let Some(slot) = self.bytes.get_mut(usize::from(self.len)) {
96            *slot = b;
97            self.len += 1;
98        }
99    }
100
101    /// An IMST HCI 1.x frame with CRC: `A5`, control 8 | endpoint, message, length.
102    fn imst(endpoint: u8, msg: u8, payload: &[u8]) -> Self {
103        let mut c = Self::new();
104        c.push(0xA5);
105        c.push(0x80 | endpoint);
106        c.push(msg);
107        c.push(u8::try_from(payload.len()).unwrap_or(0));
108        for &b in payload {
109            c.push(b);
110        }
111        let [lo, hi] = crc16_x25(c.bytes().get(1..).unwrap_or(&[])).to_le_bytes();
112        c.push(lo);
113        c.push(hi);
114        c
115    }
116
117    /// An IMST gateway HCI 2.x message, SLIP-framed: `C0`, SAP, message, payload, CRC, `C0`.
118    fn slip(sap: u8, msg: u8, payload: &[u8]) -> Self {
119        let mut body = [0u8; 16];
120        let mut n = 0usize;
121        for &b in [sap, msg].iter().chain(payload) {
122            if let Some(slot) = body.get_mut(n) {
123                *slot = b;
124                n += 1;
125            }
126        }
127        let [lo, hi] = crc16_x25(body.get(..n).unwrap_or(&[])).to_le_bytes();
128        let mut c = Self::new();
129        c.push(SLIP_END);
130        for &b in body.get(..n).unwrap_or(&[]).iter().chain(&[lo, hi]) {
131            match b {
132                SLIP_END => [SLIP_ESC, 0xDC].iter().for_each(|&e| c.push(e)),
133                SLIP_ESC => [SLIP_ESC, 0xDD].iter().for_each(|&e| c.push(e)),
134                b => c.push(b),
135            }
136        }
137        c.push(SLIP_END);
138        c
139    }
140
141    /// An Amber command: `FF`, command, length, payload, XOR of everything before.
142    fn amber(cmd: u8, payload: &[u8]) -> Self {
143        let mut c = Self::new();
144        c.push(0xFF);
145        c.push(cmd);
146        c.push(u8::try_from(payload.len()).unwrap_or(0));
147        for &b in payload {
148            c.push(b);
149        }
150        let cs = c.bytes().iter().fold(0u8, |x, &b| x ^ b);
151        c.push(cs);
152        c
153    }
154}
155
156impl fmt::Debug for Command {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        write!(f, "Command({:02X?})", self.bytes())
159    }
160}
161
162const SLIP_END: u8 = 0xC0;
163const SLIP_ESC: u8 = 0xDB;
164
165impl Stick {
166    /// The serial speed the stick uses out of the box (8N1).
167    pub const fn baud(self) -> u32 {
168        match self {
169            Self::Im871a => 57_600,
170            Self::Iu891a => 115_200,
171            Self::Amb8465 => 9_600,
172        }
173    }
174
175    /// The command that starts reception of `mode`, until the stick is powered off.
176    /// `None` where the stick cannot receive that mode (S1 on the Amber sticks).
177    ///
178    /// | Stick | Command | Modes |
179    /// |---|---|---|
180    /// | iM871A | `SET_CONFIG_REQ`, RAM only, link mode and RSSI on | S1 `00`, T1 `03`, C1 `07` (C1 format B also receives A), C1+T1 `0A` (firmware ≥ 1.4) |
181    /// | iU891A | Set Active Configuration (RAM): mode, receive notification, recalibration | S `01`, T `02`, C `05`, C/T `03` |
182    /// | AMB8465 | `CMD_SET_MODE_REQ` (RAM) | T2_other `08`, C2_other `0E`, C2_T2_other `09` |
183    pub fn listen(self, mode: LinkMode) -> Option<Command> {
184        Some(match self {
185            Self::Im871a => {
186                let code = match mode {
187                    LinkMode::S1 => 0x00,
188                    LinkMode::T1 => 0x03,
189                    LinkMode::C1 => 0x07,
190                    LinkMode::C1T1 => 0x0A,
191                };
192                // NVM no; IIFlag1: link mode; IIFlag2: AutoRSSI on.
193                Command::imst(0x01, 0x03, &[0x00, 0x02, code, 0x10, 0x01])
194            }
195            Self::Iu891a => {
196                let code = match mode {
197                    LinkMode::S1 => 0x01,
198                    LinkMode::T1 => 0x02,
199                    LinkMode::C1 => 0x05,
200                    LinkMode::C1T1 => 0x03,
201                };
202                // Link mode; options: receive notification + radio recalibration; UI
203                // options: none; LED flash 50 ms (the default); recalibration every 60 s.
204                let [l0, l1] = 50u16.to_le_bytes();
205                let [r0, r1, r2, r3] = 60_000u32.to_le_bytes();
206                Command::slip(0x09, 0x03, &[code, 0x0A, 0x00, 0x00, 0x00, l0, l1, r0, r1, r2, r3])
207            }
208            Self::Amb8465 => {
209                let code = match mode {
210                    LinkMode::S1 => return None,
211                    LinkMode::T1 => 0x08,
212                    LinkMode::C1 => 0x0E,
213                    LinkMode::C1T1 => 0x09,
214                };
215                Command::amber(0x04, &[code])
216            }
217        })
218    }
219
220    /// A harmless request whose response shows the stick is there: `PING_REQ` (iM871A,
221    /// iU891A) or `CMD_FWV_REQ` (Amber).
222    pub fn ping(self) -> Command {
223        match self {
224            Self::Im871a => Command::imst(0x01, 0x01, &[]),
225            Self::Iu891a => Command::slip(0x01, 0x01, &[]),
226            Self::Amb8465 => Command::amber(0x0C, &[]),
227        }
228    }
229
230    /// One-time preparation, written to the stick's non-volatile memory: for the Amber
231    /// sticks, frame received telegrams as `CMD_DATA_IND` (`UART_CMD_Out_Enable` = 1),
232    /// append the RSSI (`RSSI_Enable` = 1), then reset. Empty for the IMST sticks.
233    /// Flash memory wears: run it once per stick, not on every start.
234    pub fn setup(self) -> impl Iterator<Item = Command> {
235        let amber = matches!(self, Self::Amb8465);
236        [
237            Command::amber(0x09, &[0x05, 0x01, 0x01]),
238            Command::amber(0x09, &[0x45, 0x01, 0x01]),
239            Command::amber(0x05, &[]),
240        ]
241        .into_iter()
242        .filter(move |_| amber)
243    }
244}
245
246/// A radio telegram the stick received.
247#[derive(Clone, Copy, Debug, PartialEq, Eq)]
248pub struct Received<'a> {
249    /// The telegram from the L field, link-layer CRCs removed (`Format::Stripped`).
250    pub frame: &'a [u8],
251    /// The signal strength in dBm: as reported (iU891A), by the vendor's formula
252    /// (Amber), or approximated from the raw value (iM871A, whose vendor gives none).
253    pub rssi_dbm: Option<i16>,
254    /// The stick's raw RSSI byte, if it sent one.
255    pub rssi_raw: Option<u8>,
256    /// The stick's reception timestamp: its own clock (iM871A), or UTC seconds (iU891A).
257    pub timestamp: Option<u32>,
258    /// The link mode and frame format it arrived in, if the stick says (iU891A).
259    pub mode: Option<(LinkMode, bool)>,
260    /// The stick decrypted the payload itself with a key stored in it (iU891A).
261    pub decrypted_by_stick: bool,
262}
263
264/// What a stick sent.
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub enum Message<'a> {
267    /// A received radio telegram.
268    Telegram(Received<'a>),
269    /// A response or indication other than a telegram: `group` is the IMST endpoint or
270    /// SAP (0 for Amber), `id` the message or command (Amber confirmations are
271    /// `command | 0x80`), `payload` its bytes (a status byte first on the iU891A).
272    Response {
273        /// Endpoint (iM871A), SAP (iU891A) or 0 (Amber).
274        group: u8,
275        /// Message id or command.
276        id: u8,
277        /// The payload.
278        payload: &'a [u8],
279    },
280}
281
282const CAPACITY: usize = 640;
283
284/// Turns a stick's byte stream into [`Message`]s, without allocating.
285///
286/// Push bytes with [`Receiver::extend`] in whatever chunks the port delivers, then call
287/// [`Receiver::next_message`] until it returns `None`. Noise and corrupted stick frames
288/// come out as errors and are skipped; the next valid frame always decodes.
289#[derive(Clone)]
290pub struct Receiver {
291    stick: Stick,
292    buf: [u8; CAPACITY],
293    len: usize,
294    /// Bytes at the front that the last message used; dropped on the next call.
295    used: usize,
296}
297
298#[allow(clippy::missing_fields_in_debug)] // the buffer is noise in a log
299impl fmt::Debug for Receiver {
300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301        f.debug_struct("Receiver")
302            .field("stick", &self.stick)
303            .field("buffered", &(self.len - self.used))
304            .finish()
305    }
306}
307
308impl Receiver {
309    /// A receiver for `stick`.
310    pub const fn new(stick: Stick) -> Self {
311        Self { stick, buf: [0; CAPACITY], len: 0, used: 0 }
312    }
313
314    /// Add bytes from the port. Returns how many were taken: fewer than given only when
315    /// the buffer is full of an unfinished frame; call [`Receiver::next_message`] and
316    /// extend with the rest.
317    pub fn extend(&mut self, bytes: &[u8]) -> usize {
318        self.compact();
319        let free = CAPACITY - self.len;
320        let n = bytes.len().min(free);
321        if let (Some(dst), Some(src)) = (self.buf.get_mut(self.len..self.len + n), bytes.get(..n)) {
322            dst.copy_from_slice(src);
323            self.len += n;
324        }
325        n
326    }
327
328    /// The bytes received and not yet used.
329    fn data(&self) -> &[u8] {
330        self.buf.get(..self.len).unwrap_or(&[])
331    }
332
333    fn compact(&mut self) {
334        if self.used > 0 {
335            self.buf.copy_within(self.used..self.len, 0);
336            self.len -= self.used;
337            self.used = 0;
338        }
339    }
340
341    /// The next message, an error for bytes that were skipped, or `None` until more
342    /// bytes arrive.
343    pub fn next_message(&mut self) -> Option<Result<Message<'_>>> {
344        self.compact();
345        // A full buffer that holds no complete frame: drop it rather than stall.
346        let r = match self.stick {
347            Stick::Im871a => self.imst(),
348            Stick::Iu891a => self.gateway(),
349            Stick::Amb8465 => self.amber(),
350        };
351        match r {
352            Step::Wait if self.len == CAPACITY => {
353                self.used = self.len;
354                Some(Err(Error::InvalidLength))
355            }
356            Step::Wait => None,
357            Step::Skip(n, e) => {
358                self.used = n.max(1).min(self.len);
359                Some(Err(e))
360            }
361            Step::Done(n, kind) => {
362                self.used = n;
363                Some(Ok(self.message(kind)))
364            }
365        }
366    }
367
368    /// Skip to the first `start` byte; `true` if one is at the front.
369    fn seek(&mut self, start: u8) -> bool {
370        let skip = self.data().get(..).and_then(|b| b.iter().position(|&x| x == start)).unwrap_or(self.len);
371        if skip > 0 {
372            self.used = skip;
373            self.compact();
374        }
375        self.len > 0
376    }
377
378    fn imst(&mut self) -> Step {
379        if !self.seek(0xA5) {
380            return Step::Wait;
381        }
382        let Some(&[_, ctrl, msg, len]) = self.data().get(..4).and_then(|b| <&[u8; 4]>::try_from(b).ok())
383        else {
384            return Step::Wait;
385        };
386        if ctrl & 0x10 != 0 || ctrl.trailing_zeros() >= 4 {
387            return Step::Skip(1, Error::InvalidHeader);
388        }
389        let (ts, rssi, crc) = (ctrl & 0x20 != 0, ctrl & 0x40 != 0, ctrl & 0x80 != 0);
390        let body = 4 + usize::from(len);
391        let total = body + if ts { 4 } else { 0 } + usize::from(rssi) + if crc { 2 } else { 0 };
392        let Some(frame) = self.data().get(..total) else { return Step::Wait };
393        if crc {
394            let (data, fcs) = frame.split_at(total - 2);
395            let computed = crc16_x25(data.get(1..).unwrap_or(&[]));
396            let found = fcs.first().zip(fcs.get(1)).map_or(0, |(&lo, &hi)| u16::from_le_bytes([lo, hi]));
397            if computed != found {
398                return Step::Skip(1, Error::Crc { block: 0, computed, found });
399            }
400        }
401        let timestamp = ts.then(|| self.u32_le(body)).flatten();
402        let raw = rssi.then(|| self.data().get(body + if ts { 4 } else { 0 }).copied()).flatten();
403        if ctrl & 0x0F == 0x02 && msg == 0x03 {
404            // RADIOLINK WMBUSMSG_IND: the HCI length byte is the telegram's L field.
405            let rssi_dbm = raw.map(|r| i16::try_from((8 * i32::from(r) - 1900) / 15).unwrap_or(i16::MIN));
406            let t = Kind::Telegram {
407                at: 3,
408                len: 1 + usize::from(len),
409                rssi_dbm,
410                raw,
411                timestamp,
412                mode: None,
413                decrypted: false,
414            };
415            return Step::Done(total, t);
416        }
417        Step::Done(total, Kind::Response { group: ctrl & 0x0F, id: msg, at: 4, len: usize::from(len) })
418    }
419
420    fn gateway(&mut self) -> Step {
421        // SLIP: drop delimiters in front, then wait for the end delimiter.
422        while self.data().get(..).and_then(<[u8]>::first) == Some(&SLIP_END) {
423            self.used = 1;
424            self.compact();
425        }
426        let Some(end) = self.data().get(..).and_then(|b| b.iter().position(|&x| x == SLIP_END)) else {
427            return Step::Wait;
428        };
429        // Unescape in place: the result is never longer than the input.
430        let mut w = 0usize;
431        let mut r = 0usize;
432        while r < end {
433            let b = self.data().get(r).copied().unwrap_or(0);
434            let out = if b == SLIP_ESC {
435                r += 1;
436                match self.data().get(r) {
437                    Some(0xDC) => SLIP_END,
438                    Some(0xDD) => SLIP_ESC,
439                    _ => return Step::Skip(end, Error::InvalidHeader),
440                }
441            } else {
442                b
443            };
444            if let Some(slot) = self.buf.get_mut(w) {
445                *slot = out;
446            }
447            w += 1;
448            r += 1;
449        }
450        if w < 4 {
451            return Step::Skip(end, Error::UnexpectedEnd);
452        }
453        let Some(body) = self.data().get(..w) else { return Step::Skip(end, Error::UnexpectedEnd) };
454        let (data, fcs) = body.split_at(w - 2);
455        let computed = crc16_x25(data);
456        let found = fcs.first().zip(fcs.get(1)).map_or(0, |(&lo, &hi)| u16::from_le_bytes([lo, hi]));
457        if computed != found {
458            return Step::Skip(end, Error::Crc { block: 0, computed, found });
459        }
460        let (sap, msg) = (data.first().copied().unwrap_or(0), data.get(1).copied().unwrap_or(0));
461        let payload = w - 4;
462        if sap == 0x09 && msg == 0x20 && payload > 8 {
463            // Rx Message Ind: time (4, LSB first), decryption status, encryption mode,
464            // packet info, RSSI (dBm, signed), packet from the L field.
465            let timestamp = self.u32_le(2);
466            let decrypted = self.data().get(6) == Some(&1);
467            let info = self.data().get(8).copied().unwrap_or(0);
468            let raw = self.data().get(9).copied();
469            let mode = match info {
470                1 => Some((LinkMode::S1, false)),
471                2 | 6 | 7 => Some((LinkMode::T1, false)),
472                4 | 5 | 8 => Some((LinkMode::C1, false)),
473                20 | 21 | 24 => Some((LinkMode::C1, true)),
474                _ => None,
475            };
476            let rssi_dbm = raw.map(|r| i16::from(i8::from_le_bytes([r])));
477            let t = Kind::Telegram { at: 10, len: payload - 8, rssi_dbm, raw, timestamp, mode, decrypted };
478            return Step::Done(end, t);
479        }
480        Step::Done(end, Kind::Response { group: sap, id: msg, at: 2, len: payload })
481    }
482
483    fn amber(&mut self) -> Step {
484        if !self.seek(0xFF) {
485            return Step::Wait;
486        }
487        let Some(&[_, cmd, len]) = self.data().get(..3).and_then(|b| <&[u8; 3]>::try_from(b).ok()) else {
488            return Step::Wait;
489        };
490        // Only a data indication or a confirmation (command | 80) comes from the stick.
491        if cmd != 0x03 && cmd & 0x80 == 0 {
492            return Step::Skip(1, Error::InvalidHeader);
493        }
494        let total = 4 + usize::from(len);
495        let Some(frame) = self.data().get(..total) else { return Step::Wait };
496        let (data, cs) = frame.split_at(total - 1);
497        let computed = data.iter().fold(0u8, |x, &b| x ^ b);
498        let found = cs.first().copied().unwrap_or(0);
499        if computed != found {
500            return Step::Skip(1, Error::Checksum { computed, found });
501        }
502        if cmd == 0x03 && len >= 2 {
503            // CMD_DATA_IND: length = L + 1 with the RSSI byte last. Restore the L field.
504            let raw = self.data().get(total - 2).copied();
505            if let Some(l) = self.buf.get_mut(2) {
506                *l = len - 1;
507            }
508            let rssi_dbm = raw.map(|r| i16::from(i8::from_le_bytes([r])) / 2 - 74);
509            let t = Kind::Telegram {
510                at: 2,
511                len: usize::from(len),
512                rssi_dbm,
513                raw,
514                timestamp: None,
515                mode: None,
516                decrypted: false,
517            };
518            return Step::Done(total, t);
519        }
520        Step::Done(total, Kind::Response { group: 0, id: cmd, at: 3, len: usize::from(len) })
521    }
522
523    fn u32_le(&self, at: usize) -> Option<u32> {
524        let b = self.data().get(at..at + 4)?;
525        Some(u32::from_le_bytes(b.try_into().ok()?))
526    }
527
528    fn message(&self, kind: Kind) -> Message<'_> {
529        match kind {
530            Kind::Telegram { at, len, rssi_dbm, raw, timestamp, mode, decrypted } => {
531                Message::Telegram(Received {
532                    frame: self.data().get(at..at + len).unwrap_or(&[]),
533                    rssi_dbm,
534                    rssi_raw: raw,
535                    timestamp,
536                    mode,
537                    decrypted_by_stick: decrypted,
538                })
539            }
540            Kind::Response { group, id, at, len } => {
541                Message::Response { group, id, payload: self.data().get(at..at + len).unwrap_or(&[]) }
542            }
543        }
544    }
545}
546
547enum Step {
548    Wait,
549    Skip(usize, Error),
550    Done(usize, Kind),
551}
552
553#[derive(Clone, Copy)]
554enum Kind {
555    Telegram {
556        at: usize,
557        len: usize,
558        rssi_dbm: Option<i16>,
559        raw: Option<u8>,
560        timestamp: Option<u32>,
561        mode: Option<(LinkMode, bool)>,
562        decrypted: bool,
563    },
564    Response {
565        group: u8,
566        id: u8,
567        at: usize,
568        len: usize,
569    },
570}