Skip to main content

mbus_kit/
master.rs

1//! A wired M-Bus master, sans-I/O (EN 13757-2/-3): the frames a master sends, a readout
2//! that handles the frame count bit and multi-telegram replies, and a secondary-address
3//! search.
4//!
5//! Nothing here opens a port or reads a clock. Each state machine says what to send and
6//! how long to wait for a reply ([`Request`]); you write the bytes, wait, and hand back
7//! what arrived ([`Readout::reply`], [`Search::reply`]) or that nothing did
8//! ([`Readout::timeout`], [`Search::timeout`]).
9//!
10//! ```
11//! use mbus_kit::master::{Event, Readout, Target};
12//!
13//! let mut readout = Readout::new(Target::Primary(5));
14//! # let replies: [&[u8]; 2] = [&[0xE5], &[0x68, 0x1F, 0x1F, 0x68, 0x08, 0x05, 0x72, 0x78, 0x56, 0x34, 0x12, 0x24, 0x40, 0x01, 0x07, 0x55, 0x00, 0x00, 0x00, 0x03, 0x13, 0x15, 0x31, 0x00, 0xDA, 0x02, 0x3B, 0x13, 0x01, 0x8B, 0x60, 0x04, 0x37, 0x18, 0x02, 0x1B, 0x16]];
15//! # let mut replies = replies.into_iter();
16//! while let Some(request) = readout.next_request() {
17//!     // port.write(request.bytes()); wait up to request.timeout_ms(Baud::B2400) for a frame …
18//!     let reply: &[u8] = replies.next().unwrap();
19//!     match readout.reply(reply) {
20//!         Event::Telegram(app) => {
21//!             for r in app.records().into_iter().flatten() {
22//!                 println!("{}", r.unwrap());
23//!             }
24//!         }
25//!         Event::NeedMore => { /* read more bytes and call reply() again */ }
26//!         _ => {}
27//!     }
28//! }
29//! assert!(readout.is_complete()); // or readout.outcome(): why it is not
30//! ```
31//!
32//! Hand `reply` exactly one frame ([`wired::scan`] finds it behind noise or an echo).
33//! A readout delivers only telegrams from the meter it addresses and says how it ended
34//! ([`Outcome`]): a telegram limit or a broken page is never "complete".
35
36use core::fmt;
37
38use crate::app::{Address, Application, Manufacturer, Medium};
39use crate::time::DateTime;
40use crate::wired::{self, BROADCAST, Frame, NETWORK_LAYER, control};
41use crate::{Error, Result};
42
43/// CI values a master sends (EN 13757-3, m-bus.com 6.1).
44pub mod ci {
45    /// Application reset.
46    pub const APPLICATION_RESET: u8 = 0x50;
47    /// Data send (records to the slave).
48    pub const DATA_SEND: u8 = 0x51;
49    /// Selection of a slave by secondary address.
50    pub const SELECT: u8 = 0x52;
51    /// Baud rate 300 … 38400: `B8` + index.
52    pub const BAUD_300: u8 = 0xB8;
53}
54
55/// A secondary address to select, each part optional (a wildcard).
56///
57/// The identification number is eight BCD digits; any digit may be a wildcard (`F` on
58/// the wire). Manufacturer, version and medium are wildcarded as a whole.
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
60pub struct SecondaryAddress {
61    /// The eight digits, most significant first; `None` is a wildcard.
62    pub digits: [Option<u8>; 8],
63    /// Manufacturer, or any.
64    pub manufacturer: Option<Manufacturer>,
65    /// Version, or any.
66    pub version: Option<u8>,
67    /// Medium, or any.
68    pub medium: Option<Medium>,
69}
70
71impl SecondaryAddress {
72    /// Every meter: all wildcards.
73    pub const ANY: Self = Self { digits: [None; 8], manufacturer: None, version: None, medium: None };
74
75    /// The meter with this identification number (up to 8 decimal digits), any
76    /// manufacturer, version and medium. `None` above 99 999 999.
77    pub fn id(number: u32) -> Option<Self> {
78        if number > 99_999_999 {
79            return None;
80        }
81        #[allow(clippy::cast_possible_truncation)] // each digit < 10
82        let d = |k: u32| Some((number / k % 10) as u8);
83        let digits = [d(10_000_000), d(1_000_000), d(100_000), d(10_000), d(1_000), d(100), d(10), d(1)];
84        Some(Self { digits, ..Self::ANY })
85    }
86
87    /// Exactly this meter: number, manufacturer, version and medium.
88    pub fn exact(address: &Address) -> Self {
89        let mut digits = [None; 8];
90        let [a, b, c, d] = address.id;
91        for (slot, byte) in digits.chunks_exact_mut(2).zip([d, c, b, a]) {
92            if let [high, low] = slot {
93                *high = Some(byte >> 4).filter(|&x| x <= 9);
94                *low = Some(byte & 0x0F).filter(|&x| x <= 9);
95            }
96        }
97        Self {
98            digits,
99            manufacturer: Some(address.manufacturer),
100            version: Some(address.version),
101            medium: Some(address.medium),
102        }
103    }
104
105    /// Parse a pattern of 8 characters, digits or `F`/`*`/`?` wildcards, e.g.
106    /// `"1234FFFF"`. Shorter patterns are padded with wildcards on the right.
107    pub fn pattern(text: &str) -> Option<Self> {
108        let mut out = Self::ANY;
109        for (n, c) in text.bytes().enumerate() {
110            let slot = out.digits.get_mut(n)?;
111            *slot = match c {
112                b'0'..=b'9' => Some(c - b'0'),
113                b'F' | b'f' | b'*' | b'?' => None,
114                _ => return None,
115            };
116        }
117        Some(out)
118    }
119
120    /// The identification number as transmitted (BCD, LSB first, `F` for wildcards).
121    pub fn id_bytes(&self) -> [u8; 4] {
122        let nibble = |d: Option<u8>| d.unwrap_or(0x0F);
123        let mut out = [0u8; 4];
124        for (i, pair) in self.digits.chunks_exact(2).enumerate() {
125            if let ([high, low], Some(slot)) = (pair, out.get_mut(3 - i)) {
126                *slot = (nibble(*high) << 4) | nibble(*low);
127            }
128        }
129        out
130    }
131
132    /// Whether `address` matches.
133    pub fn matches(&self, address: &Address) -> bool {
134        let exact = Self::exact(address);
135        self.digits.iter().zip(exact.digits).all(|(want, got)| want.is_none() || *want == got)
136            && self.manufacturer.is_none_or(|m| m == address.manufacturer)
137            && self.version.is_none_or(|v| v == address.version)
138            && self.medium.is_none_or(|m| m == address.medium)
139    }
140
141    /// The 8 data bytes of a selection: ID (BCD, LSB first), manufacturer (LE), version,
142    /// medium; wildcards as `F` nibbles, `FFFF` and `FF`.
143    pub fn to_bytes(&self) -> [u8; 8] {
144        let [i0, i1, i2, i3] = self.id_bytes();
145        let [m0, m1] = self.manufacturer.map_or(0xFFFF, |m| m.0).to_le_bytes();
146        [i0, i1, i2, i3, m0, m1, self.version.unwrap_or(0xFF), self.medium.map_or(0xFF, |m| m.0)]
147    }
148}
149
150impl fmt::Display for SecondaryAddress {
151    /// `12345678`, `1234FFFF KAM v27 water`, wildcards as `F`.
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        for d in self.digits {
154            match d {
155                Some(d) => write!(f, "{d}")?,
156                None => f.write_str("F")?,
157            }
158        }
159        if let Some(m) = self.manufacturer {
160            write!(f, " {m}")?;
161        }
162        if let Some(v) = self.version {
163            write!(f, " v{v}")?;
164        }
165        if let Some(m) = self.medium {
166            write!(f, " {m}")?;
167        }
168        Ok(())
169    }
170}
171
172/// Baud rates of wired M-Bus.
173#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
174pub enum Baud {
175    /// 300 Bd.
176    B300,
177    /// 600 Bd.
178    B600,
179    /// 1200 Bd.
180    B1200,
181    /// 2400 Bd (the default of most meters).
182    B2400,
183    /// 4800 Bd.
184    B4800,
185    /// 9600 Bd.
186    B9600,
187    /// 19200 Bd.
188    B19200,
189    /// 38400 Bd.
190    B38400,
191}
192
193impl Baud {
194    /// Bits per second.
195    pub const fn bits_per_second(self) -> u32 {
196        match self {
197            Self::B300 => 300,
198            Self::B600 => 600,
199            Self::B1200 => 1200,
200            Self::B2400 => 2400,
201            Self::B4800 => 4800,
202            Self::B9600 => 9600,
203            Self::B19200 => 19200,
204            Self::B38400 => 38400,
205        }
206    }
207
208    const ALL: [Self; 8] = [
209        Self::B300,
210        Self::B600,
211        Self::B1200,
212        Self::B2400,
213        Self::B4800,
214        Self::B9600,
215        Self::B19200,
216        Self::B38400,
217    ];
218
219    const fn ci(self) -> u8 {
220        ci::BAUD_300
221            + match self {
222                Self::B300 => 0,
223                Self::B600 => 1,
224                Self::B1200 => 2,
225                Self::B2400 => 3,
226                Self::B4800 => 4,
227                Self::B9600 => 5,
228                Self::B19200 => 6,
229                Self::B38400 => 7,
230            }
231    }
232}
233
234/// A baud rate from bits per second, e.g. from a configuration file:
235/// `Baud::try_from(2400)`. Anything but the eight M-Bus rates is [`Error::InvalidBaud`].
236impl TryFrom<u32> for Baud {
237    type Error = Error;
238
239    fn try_from(bits_per_second: u32) -> Result<Self> {
240        Self::ALL
241            .into_iter()
242            .find(|b| b.bits_per_second() == bits_per_second)
243            .ok_or(Error::InvalidBaud(bits_per_second))
244    }
245}
246
247/// A frame to send and how long to wait for its reply.
248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249pub struct Request {
250    bytes: [u8; 32],
251    len: u8,
252    reply: bool,
253}
254
255/// The response timeout at `baud`: 330 bit times plus 50 ms (EN 13757-2 via m-bus.com
256/// 5.4), in milliseconds rounded up: 188 ms at 2400 Bd, 85 ms at 9600 Bd.
257pub const fn response_timeout_ms(baud: Baud) -> u32 {
258    (330 * 1000u32).div_ceil(baud.bits_per_second()) + 50
259}
260
261/// The default number of repetitions of a request that got no valid reply.
262pub const RETRIES: u8 = 2;
263
264impl Request {
265    const EMPTY: Self = Self { bytes: [0; 32], len: 0, reply: false };
266
267    fn from_frame(frame: &Frame<'_>, reply: bool) -> Result<Self> {
268        let mut bytes = [0u8; 32];
269        let n = frame.encode(&mut bytes)?;
270        Ok(Self { bytes, len: u8::try_from(n).map_err(|_| Error::OutputTooSmall)?, reply })
271    }
272
273    /// The bytes to write to the bus.
274    pub fn bytes(&self) -> &[u8] {
275        self.bytes.get(..usize::from(self.len)).unwrap_or(&[])
276    }
277
278    /// How long to wait for the start of the reply at `baud`, in milliseconds
279    /// ([`response_timeout_ms`]); 0 when no reply is expected (broadcast).
280    pub const fn timeout_ms(&self, baud: Baud) -> u32 {
281        if self.reply { response_timeout_ms(baud) } else { 0 }
282    }
283
284    /// The same frame with the frame count bit set or cleared (checksum recomputed).
285    /// EN 13757-2: after `SND_NKE`, and to address `FD` after every selection, the next
286    /// `SND_UD` carries FCB = 1; it toggles after each acknowledged one.
287    #[must_use]
288    pub fn with_fcb(mut self, fcb: bool) -> Self {
289        let len = usize::from(self.len);
290        let (c_at, sum) = match self.bytes() {
291            [0x10, ..] => (1, 1..3),
292            [0x68, ..] if len >= 6 => (4, 4..len - 2),
293            _ => return self,
294        };
295        if let Some(c) = self.bytes.get_mut(c_at) {
296            *c = (*c & !control::FCB) | if fcb { control::FCB } else { 0 };
297        }
298        let cs = self.bytes.get(sum).map_or(0, |b| b.iter().fold(0u8, |s, &x| s.wrapping_add(x)));
299        if let Some(slot) = self.bytes.get_mut(len - 2) {
300            *slot = cs;
301        }
302        self
303    }
304
305    /// Whether a reply is expected at all.
306    pub const fn expects_reply(&self) -> bool {
307        self.reply
308    }
309}
310
311const fn timeout_for(address: u8) -> bool {
312    address != BROADCAST
313}
314
315/// `SND_NKE`: reset the link layer of a slave (and its FCB); to [`NETWORK_LAYER`], deselect.
316pub fn link_reset(address: u8) -> Request {
317    // A short frame always fits the 32-byte request.
318    Request::from_frame(&wired::snd_nke(address), timeout_for(address)).unwrap_or(Request::EMPTY)
319}
320
321fn snd_ud(address: u8, fcb: bool, ci: u8, data: &[u8]) -> Result<Request> {
322    let c = control::SND_UD | if fcb { control::FCB } else { 0 };
323    Request::from_frame(&Frame::Long { c, a: address, ci, data }, timeout_for(address))
324}
325
326/// Select a slave by secondary address (`SND_UD` to address `FD`, CI `52`, FCB = 1 as
327/// for every selection). A slave that matches answers `E5` and is then reached at
328/// [`NETWORK_LAYER`] until deselected; every other slave deselects itself.
329pub fn select(address: &SecondaryAddress) -> Request {
330    snd_ud(NETWORK_LAYER, true, ci::SELECT, &address.to_bytes()).unwrap_or(Request::EMPTY)
331}
332
333/// Enhanced selection: also match the fabrication number (record `0C 78`, 8 BCD digits;
334/// `None` wildcards it). For two meters that share an identification number. A slave that
335/// does not support it does not answer.
336pub fn select_enhanced(address: &SecondaryAddress, fabrication: Option<u32>) -> Request {
337    let fab = fabrication.and_then(SecondaryAddress::id).map_or([0xFF; 4], |f| f.id_bytes());
338    let [a, b, c, d, e, f, g, h] = address.to_bytes();
339    let [f0, f1, f2, f3] = fab;
340    snd_ud(NETWORK_LAYER, true, ci::SELECT, &[a, b, c, d, e, f, g, h, 0x0C, 0x78, f0, f1, f2, f3])
341        .unwrap_or(Request::EMPTY)
342}
343
344/// Deselect: `SND_NKE` to the network-layer address.
345pub fn deselect() -> Request {
346    link_reset(NETWORK_LAYER)
347}
348
349/// Set a slave's primary address (`SND_UD`, CI `51`, record `01 7A new`). `None` for the
350/// reserved addresses 251–255. Make sure first that nothing answers at `new`
351/// ([`link_reset`] to it times out): two slaves on one address cannot be read.
352pub fn set_primary_address(address: u8, new: u8) -> Option<Request> {
353    (new <= 250).then(|| snd_ud(address, false, ci::DATA_SEND, &[0x01, 0x7A, new]).unwrap_or(Request::EMPTY))
354}
355
356/// Reset a slave's application layer (CI `50`), optionally only one telegram type (the
357/// subcode: upper nibble the type, e.g. `1x` user data, lower nibble the subtelegram).
358/// Also drops a readout selection back to the standard telegram.
359pub fn application_reset(address: u8, subcode: Option<u8>) -> Request {
360    let data = subcode.map(|s| [s]);
361    snd_ud(address, false, ci::APPLICATION_RESET, data.as_ref().map_or(&[][..], |d| &d[..]))
362        .unwrap_or(Request::EMPTY)
363}
364
365/// Ask for all data in the next `REQ_UD2` (global readout request, DIF `7F`).
366pub fn request_all_data(address: u8) -> Request {
367    snd_ud(address, false, ci::DATA_SEND, &[0x7F]).unwrap_or(Request::EMPTY)
368}
369
370/// Switch a slave to another baud rate (CI `B8`–`BF`). The slave acknowledges at the old
371/// rate and listens at the new one.
372pub fn set_baud(address: u8, baud: Baud) -> Request {
373    snd_ud(address, false, baud.ci(), &[]).unwrap_or(Request::EMPTY)
374}
375
376/// Set a slave's clock (CI `51`, record `04 6D` date and time, type F).
377pub fn set_time(address: u8, time: &DateTime) -> Request {
378    let [a, b, c, d] = time.to_type_f();
379    snd_ud(address, false, ci::DATA_SEND, &[0x04, 0x6D, a, b, c, d]).unwrap_or(Request::EMPTY)
380}
381
382/// Whom a readout reads.
383#[derive(Clone, Copy, Debug, PartialEq, Eq)]
384pub enum Target {
385    /// A primary address: 0–250, or 254 (the test address every slave answers; for a
386    /// line with one slave).
387    Primary(u8),
388    /// A secondary address, selected first and deselected after.
389    Secondary(SecondaryAddress),
390}
391
392/// What happened when a reply (or its absence) was handed to a state machine.
393#[derive(Clone, Debug)]
394#[allow(clippy::large_enum_variant)] // returned by value once per reply; boxing needs alloc
395pub enum Event<'a> {
396    /// The bytes are the start of a frame: read more and call `reply` again with all of
397    /// them.
398    NeedMore,
399    /// A telegram with records (for a readout), from the addressed meter.
400    Telegram(Application<'a>),
401    /// A meter was found (for a search).
402    Found(Address),
403    /// Several meters share this full identification number; select them with
404    /// [`select_enhanced`] (fabrication number) or by manufacturer, version and medium.
405    Ambiguous(SecondaryAddress),
406    /// The slave acknowledged (`E5`).
407    Acknowledged,
408    /// No valid reply; the request will be repeated.
409    Retrying,
410    /// No valid reply after every retry: the slave does not answer.
411    NoReply,
412    /// A valid frame that cannot be decoded as a telegram.
413    Invalid(Error),
414    /// A meter acknowledged this selection (for a search), but its reply to the read
415    /// did not name a meter that matches it: no reply, no long header, or another
416    /// identification number.
417    Unreadable(SecondaryAddress),
418    /// A telegram from another meter than the readout expects (the identity that
419    /// answered; `None` when the telegram carries none). Not delivered; the readout ends.
420    WrongMeter(Option<Address>),
421}
422
423/// How a readout ended: see [`Readout::outcome`].
424#[derive(Clone, Copy, Debug, PartialEq, Eq)]
425pub enum Outcome {
426    /// The meter sent its last telegram (no "more records follow"), or answered `E5`
427    /// instead of data: every record was read.
428    Complete,
429    /// The meter still has records, but [`Readout::max_telegrams`] telegrams were read.
430    /// The telegrams delivered are only the first part of the meter's data.
431    LimitReached,
432    /// A reply was not a decodable telegram, or one of its records is broken (so
433    /// whether more follow is unknown); [`Error::InvalidAddress`] for 251–253 and 255.
434    Invalid(Error),
435    /// A telegram came from another meter than expected ([`Readout::expect_meter`], the
436    /// selection of a secondary target, or the first telegram of this readout). It was
437    /// not delivered. The identity is the one that answered (`None`: it sent none).
438    WrongMeter(Option<Address>),
439    /// No valid reply after every retry; `heard` says what came instead.
440    NoReply {
441        /// What the tries of the last request heard.
442        heard: Heard,
443    },
444}
445
446impl fmt::Display for Outcome {
447    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448        match self {
449            Self::Complete => f.write_str("complete"),
450            Self::LimitReached => f.write_str("telegram limit reached, the meter has more records"),
451            Self::Invalid(e @ Error::InvalidAddress(_)) => write!(f, "{e}"),
452            Self::Invalid(e) => write!(f, "invalid telegram: {e}"),
453            Self::WrongMeter(Some(a)) => write!(f, "another meter answered: {a}"),
454            Self::WrongMeter(None) => f.write_str("another meter answered (without an identity)"),
455            Self::NoReply { heard } => write!(f, "no reply, heard {heard}"),
456        }
457    }
458}
459
460/// What a request heard instead of a valid reply: the diagnosis in
461/// [`Outcome::NoReply`]. When the tries of one request heard different things, the most
462/// specific wins (the variants are ordered from least to most specific).
463///
464/// This describes the bytes on the line, not who sent them: wired M-Bus has no
465/// authentication, so any device can send a frame with any address.
466#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
467pub enum Heard {
468    /// Silence: check power, wiring, the converter and the baud rate.
469    #[default]
470    Nothing,
471    /// Bytes without a valid frame, or a frame with more bytes behind it: several meters
472    /// answering at once (a shared address) or noise on the line.
473    Garbled,
474    /// A valid frame that does not answer the request: `E5` where data was due, a
475    /// master's frame. Another master or a converter echo on the line.
476    Unexpected,
477    /// A meter's response from this other primary address: check the configured address.
478    OtherAddress(u8),
479}
480
481impl fmt::Display for Heard {
482    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
483        match self {
484            Self::Nothing => f.write_str("nothing"),
485            Self::Garbled => f.write_str("garbled bytes"),
486            Self::Unexpected => f.write_str("a frame that does not answer the request"),
487            Self::OtherAddress(a) => write!(f, "a response from primary address {a}"),
488        }
489    }
490}
491
492#[derive(Clone, Copy, Debug, PartialEq, Eq)]
493enum ReadState {
494    Reset,
495    Select,
496    Read,
497    Deselect,
498    Done,
499}
500
501/// Read every telegram of one meter: `SND_NKE` (primary) or selection (secondary), then
502/// `REQ_UD2` with the frame count bit toggled until no more records follow, then
503/// deselection (secondary). A request without a valid reply is repeated with the same
504/// FCB, [`RETRIES`] times. When it is over, [`Readout::outcome`] says whether every
505/// telegram was read, or why not.
506///
507/// # What counts as a reply
508///
509/// Hand [`Readout::reply`] the bytes of **exactly one frame**. On a line with noise or a
510/// converter that echoes, cut the frame out of the receive buffer with [`wired::scan`]
511/// (as [`serial::Bus`](crate::serial) does). Bytes after the frame make the reply garbled:
512/// two slaves answered at once.
513///
514/// During a read, only a slave's response (`RSP_UD`, [`control::is_response`]) from the
515/// requested primary address is a telegram (any address for 254, and for a secondary
516/// target, which answers via 253). Anything else is handled like a garbled
517/// reply: repeated, then [`Outcome::NoReply`]. Every telegram must also carry the expected
518/// identity: the one given to [`Readout::expect_meter`], the selection of a secondary
519/// target, and the identity of the first telegram; otherwise the readout ends with
520/// [`Outcome::WrongMeter`].
521///
522/// These checks attribute data to a meter; they do not authenticate it. Wired M-Bus has
523/// no authentication: any device on the line can send a frame with any address and
524/// identity.
525#[derive(Clone, Debug)]
526pub struct Readout {
527    target: Target,
528    state: ReadState,
529    fcb: bool,
530    tries: u8,
531    retries: u8,
532    telegrams: u8,
533    max_telegrams: u8,
534    expect: Option<SecondaryAddress>,
535    /// The identity of the first telegram (once `telegrams > 0`).
536    first: Option<Address>,
537    /// The most specific thing the current request's failed tries heard.
538    heard: Heard,
539    outcome: Option<Outcome>,
540}
541
542impl Readout {
543    /// A readout with the default retries and a limit of 16 telegrams.
544    pub const fn new(target: Target) -> Self {
545        // Secondary: deselect every slave first (SND_NKE to FD), so no stale selection
546        // answers along.
547        let (state, outcome) = match target {
548            // 253 reaches a selected slave: read it as `Target::Secondary`, which selects it
549            // (the link reset before the read would deselect it).
550            Target::Primary(a @ (251..=253 | BROADCAST)) => {
551                (ReadState::Done, Some(Outcome::Invalid(Error::InvalidAddress(a))))
552            }
553            _ => (ReadState::Reset, None),
554        };
555        Self {
556            target,
557            state,
558            fcb: true,
559            tries: 0,
560            retries: RETRIES,
561            telegrams: 0,
562            max_telegrams: 16,
563            expect: None,
564            first: None,
565            heard: Heard::Nothing,
566            outcome,
567        }
568    }
569
570    /// Repeat a request at most `retries` times.
571    #[must_use]
572    pub const fn retries(mut self, retries: u8) -> Self {
573        self.retries = retries;
574        self
575    }
576
577    /// Read at most `max` telegrams (at least 1). A meter that still has records after
578    /// them ends the readout with [`Outcome::LimitReached`], not [`Outcome::Complete`].
579    #[must_use]
580    pub const fn max_telegrams(mut self, max: u8) -> Self {
581        self.max_telegrams = max;
582        self
583    }
584
585    /// Accept only telegrams from this meter (the identity printed on it, wildcards
586    /// allowed): e.g. bind a primary address to `SecondaryAddress::exact(&address)`. A
587    /// telegram with another identity, or none, ends the readout with
588    /// [`Outcome::WrongMeter`].
589    #[must_use]
590    pub const fn expect_meter(mut self, meter: SecondaryAddress) -> Self {
591        self.expect = Some(meter);
592        self
593    }
594
595    const fn address(&self) -> u8 {
596        match self.target {
597            Target::Primary(a) => a,
598            Target::Secondary(_) => NETWORK_LAYER,
599        }
600    }
601
602    /// The next frame to send, or `None` when the readout is over.
603    pub fn next_request(&mut self) -> Option<Request> {
604        Some(match (self.state, self.target) {
605            // Primary: SND_NKE to the slave. Secondary: SND_NKE to FD, deselecting all.
606            (ReadState::Reset, _) => link_reset(self.address()),
607            (ReadState::Select, Target::Secondary(s)) => select(&s),
608            (ReadState::Read, _) => {
609                Request::from_frame(&wired::req_ud2(self.address(), self.fcb), timeout_for(0)).ok()?
610            }
611            (ReadState::Deselect, _) => deselect(),
612            _ => return None,
613        })
614    }
615
616    /// How the readout ended; `None` while it runs (including the deselection).
617    pub const fn outcome(&self) -> Option<Outcome> {
618        match self.state {
619            ReadState::Done => self.outcome,
620            _ => None,
621        }
622    }
623
624    /// Whether every telegram was read: [`Outcome::Complete`].
625    pub const fn is_complete(&self) -> bool {
626        matches!(self.outcome(), Some(Outcome::Complete))
627    }
628
629    /// How many telegrams were delivered.
630    pub const fn telegrams(&self) -> u8 {
631        self.telegrams
632    }
633
634    const fn advance(&mut self, next: ReadState) {
635        self.state = next;
636        self.tries = 0;
637        self.heard = Heard::Nothing;
638    }
639
640    /// End the readout; a secondary target that may be selected is deselected first.
641    const fn finish(&mut self, outcome: Outcome) {
642        self.outcome = Some(outcome);
643        let next = match (self.target, self.state) {
644            (Target::Secondary(_), ReadState::Select | ReadState::Read) => ReadState::Deselect,
645            _ => ReadState::Done,
646        };
647        self.advance(next);
648    }
649
650    /// The timeout passed without a valid reply. `received` is what arrived (empty for
651    /// silence): it does not change what happens next, but says what the readout heard
652    /// ([`Heard`]) if it ends with [`Outcome::NoReply`].
653    pub fn timeout(&mut self, received: &[u8]) -> Event<'static> {
654        let heard = match wired::scan_ended(received) {
655            _ if received.is_empty() => Heard::Nothing,
656            wired::Scan::Frame { frame, skip, len } if skip + len == received.len() => self.judge(&frame),
657            _ => Heard::Garbled,
658        };
659        self.fail(heard)
660    }
661
662    /// What a frame that is not a valid answer says about the line.
663    const fn judge(&self, frame: &Frame<'_>) -> Heard {
664        match (self.state, self.target, frame) {
665            (ReadState::Read, Target::Primary(p), Frame::Long { c, a, .. })
666                if p <= 250 && *a != p && control::is_response(*c) =>
667            {
668                Heard::OtherAddress(*a)
669            }
670            _ => Heard::Unexpected,
671        }
672    }
673
674    /// A try failed: repeat the request, or end with [`Outcome::NoReply`].
675    fn fail(&mut self, heard: Heard) -> Event<'static> {
676        match (self.state, self.target) {
677            // Unselected slaves need not answer the deselection: go on to the selection.
678            (ReadState::Reset, Target::Secondary(_)) => {
679                self.advance(ReadState::Select);
680                return Event::NoReply;
681            }
682            // Not every slave acknowledges a deselection; the outcome stands.
683            (ReadState::Deselect, _) => {
684                self.advance(ReadState::Done);
685                return Event::NoReply;
686            }
687            (ReadState::Done, _) => return Event::NoReply,
688            _ => {}
689        }
690        self.heard = self.heard.max(heard);
691        if self.tries < self.retries {
692            self.tries += 1;
693            Event::Retrying
694        } else {
695            self.finish(Outcome::NoReply { heard: self.heard });
696            Event::NoReply
697        }
698    }
699
700    /// Hand over what arrived: the bytes of one frame (see [the rules](Readout#what-counts-as-a-reply)).
701    pub fn reply<'a>(&mut self, frame: &'a [u8]) -> Event<'a> {
702        let (parsed, used) = match Frame::parse(frame) {
703            Ok(None) => return Event::NeedMore,
704            Ok(Some(parsed)) => parsed,
705            Err(_) => return self.fail(Heard::Garbled),
706        };
707        if self.state == ReadState::Deselect {
708            self.advance(ReadState::Done);
709            return Event::Acknowledged;
710        }
711        if used != frame.len() {
712            // Bytes after the frame: two answers overlapped.
713            return self.fail(Heard::Garbled);
714        }
715        match (self.state, parsed) {
716            (ReadState::Reset, Frame::Ack) => {
717                // EN 13757-2: after SND_NKE the next REQ_UD2 has FCB set.
718                self.fcb = true;
719                let next = match self.target {
720                    Target::Primary(_) => ReadState::Read,
721                    Target::Secondary(_) => ReadState::Select,
722                };
723                self.advance(next);
724                Event::Acknowledged
725            }
726            (ReadState::Select, Frame::Ack) => {
727                self.fcb = true;
728                self.advance(ReadState::Read);
729                Event::Acknowledged
730            }
731            // E5 instead of the next page: the slave has nothing more to send. Before the
732            // first page, an E5 is a late or doubled acknowledgement, not data.
733            (ReadState::Read, Frame::Ack) if self.telegrams > 0 => {
734                self.finish(Outcome::Complete);
735                Event::Acknowledged
736            }
737            (ReadState::Read, Frame::Long { c, a, ci, data }) if self.answers(c, a) => {
738                self.telegram(ci, data)
739            }
740            (_, parsed) => {
741                let heard = self.judge(&parsed);
742                self.fail(heard)
743            }
744        }
745    }
746
747    /// A slave's response from the address asked.
748    const fn answers(&self, c: u8, a: u8) -> bool {
749        control::is_response(c)
750            && match self.target {
751                Target::Primary(p) if p <= 250 => a == p,
752                _ => true,
753            }
754    }
755
756    fn telegram<'a>(&mut self, ci: u8, data: &'a [u8]) -> Event<'a> {
757        let app = match Application::parse(ci, data) {
758            Ok(app) => app,
759            Err(e) => {
760                self.finish(Outcome::Invalid(e));
761                return Event::Invalid(e);
762            }
763        };
764        let meter = app.meter();
765        let selection = match self.target {
766            Target::Secondary(s) => Some(s),
767            Target::Primary(_) => None,
768        };
769        let fits = |p: &SecondaryAddress| *p == SecondaryAddress::ANY || meter.is_some_and(|m| p.matches(&m));
770        let same = self.telegrams == 0 || self.first == meter;
771        if !(selection.iter().chain(&self.expect).all(fits) && same) {
772            self.finish(Outcome::WrongMeter(meter));
773            return Event::WrongMeter(meter);
774        }
775        self.first = meter;
776        self.telegrams = self.telegrams.saturating_add(1);
777        self.fcb = !self.fcb;
778        match app.records().map(more_follows) {
779            // A broken record hides whether `1F` follows: not complete.
780            Some(Err(e)) => self.finish(Outcome::Invalid(e)),
781            None | Some(Ok(false)) => self.finish(Outcome::Complete),
782            Some(Ok(true)) if self.telegrams >= self.max_telegrams.max(1) => {
783                self.finish(Outcome::LimitReached);
784            }
785            Some(Ok(true)) => self.advance(ReadState::Read),
786        }
787        Event::Telegram(app)
788    }
789}
790
791/// Whether a telegram's records end with `1F` (more records follow); the first broken
792/// record otherwise.
793#[allow(clippy::needless_pass_by_value)] // used as `.map(more_follows)`
794fn more_follows(mut records: crate::Records<'_>) -> Result<bool> {
795    for r in records.by_ref() {
796        r?;
797    }
798    Ok(records.more_follows())
799}
800
801/// A secondary-address search (wildcard scan): finds every meter on the bus.
802///
803/// Probes a selection with the first digit fixed and the rest wildcarded. No reply: no
804/// meter there. `E5`: exactly one meter, read with `REQ_UD2` to learn its address. A
805/// garbled reply: several meters collided, so the next digit is fixed too, 0 to 9, and
806/// so on. Depth-first, at most 8 digits deep; ends after at most `10 × 8 × (meters + 1)`
807/// selections, plus one read per meter.
808#[allow(clippy::struct_excessive_bools)] // independent flags of one state machine
809#[derive(Clone, Debug)]
810pub struct Search {
811    prefix: [u8; 8],
812    depth: u8,
813    reading: bool,
814    done: bool,
815    tries: u8,
816    retries: u8,
817    selections: u32,
818    max_selections: u32,
819    exhausted: bool,
820    deselected: bool,
821}
822
823impl Default for Search {
824    fn default() -> Self {
825        Self::new()
826    }
827}
828
829impl Search {
830    /// A search of the whole bus.
831    pub const fn new() -> Self {
832        Self {
833            prefix: [0; 8],
834            depth: 1,
835            reading: false,
836            done: false,
837            tries: 0,
838            retries: RETRIES,
839            selections: 0,
840            max_selections: 25_000,
841            exhausted: false,
842            deselected: false,
843        }
844    }
845
846    /// Give up after `max` selections (default 25 000: a bus of 250 meters needs at most
847    /// 10 × 8 × 251 = 20 080). A stuck line or a babbling device makes every probe look like a
848    /// collision, and the full tree has 10⁸ prefixes.
849    #[must_use]
850    pub const fn max_selections(mut self, max: u32) -> Self {
851        self.max_selections = max;
852        self
853    }
854
855    /// Whether the search covered the whole bus (`false` while running, or after it gave
856    /// up at [`Search::max_selections`]).
857    pub const fn is_complete(&self) -> bool {
858        self.done && !self.exhausted
859    }
860
861    /// The selection pattern being probed.
862    pub fn probe(&self) -> SecondaryAddress {
863        let mut s = SecondaryAddress::ANY;
864        for (slot, digit) in s.digits.iter_mut().zip(self.prefix).take(usize::from(self.depth)) {
865            *slot = Some(digit);
866        }
867        s
868    }
869
870    /// How many selections have been sent.
871    pub const fn selections(&self) -> u32 {
872        self.selections
873    }
874
875    /// The next frame to send, or `None` when the search is over. The last request
876    /// deselects every slave, so the last meter found does not stay selected.
877    pub fn next_request(&mut self) -> Option<Request> {
878        if !self.done && !self.reading && self.tries == 0 && self.selections >= self.max_selections {
879            self.done = true;
880            self.exhausted = true;
881        }
882        if self.done {
883            if self.deselected {
884                return None;
885            }
886            self.deselected = true;
887            return Some(deselect());
888        }
889        if self.reading {
890            return Request::from_frame(&wired::req_ud2(NETWORK_LAYER, true), timeout_for(0)).ok();
891        }
892        if self.tries == 0 {
893            self.selections = self.selections.saturating_add(1);
894        }
895        Some(select(&self.probe()))
896    }
897
898    /// Move to the next prefix at this depth, climbing up when a digit's 0–9 are done.
899    fn next_sibling(&mut self) {
900        self.tries = 0;
901        self.reading = false;
902        loop {
903            let Some(d) = self.prefix.get_mut(usize::from(self.depth) - 1) else {
904                self.done = true;
905                return;
906            };
907            if *d < 9 {
908                *d += 1;
909                return;
910            }
911            *d = 0;
912            if self.depth == 1 {
913                self.done = true;
914                return;
915            }
916            self.depth -= 1;
917        }
918    }
919
920    /// The timeout passed. `received` is whatever arrived in that time (empty if
921    /// nothing): bytes that are not a valid frame mean several meters answered at once.
922    pub fn timeout(&mut self, received: &[u8]) -> Event<'static> {
923        if self.done {
924            // The closing deselection: not every slave acknowledges it.
925            return Event::NoReply;
926        }
927        if !received.is_empty() {
928            return self.collision();
929        }
930        if self.tries < self.retries {
931            self.tries += 1;
932            return Event::Retrying;
933        }
934        if self.reading {
935            // The selection was acknowledged, the read never was: report, don't drop.
936            return self.unreadable();
937        }
938        // No meter under this prefix.
939        self.next_sibling();
940        Event::NoReply
941    }
942
943    fn unreadable(&mut self) -> Event<'static> {
944        let probe = self.probe();
945        self.next_sibling();
946        Event::Unreadable(probe)
947    }
948
949    /// Several meters answered: fix one more digit, starting at 0.
950    fn collision(&mut self) -> Event<'static> {
951        self.reading = false;
952        self.tries = 0;
953        if self.depth >= 8 {
954            // A full ID collides: two meters with one number. Report it and go on.
955            let probe = self.probe();
956            self.next_sibling();
957            return Event::Ambiguous(probe);
958        }
959        self.depth += 1;
960        if let Some(d) = self.prefix.get_mut(usize::from(self.depth) - 1) {
961            *d = 0;
962        }
963        Event::Retrying
964    }
965
966    /// Hand over what arrived. Incomplete but plausible bytes: [`Event::NeedMore`];
967    /// anything invalid: a collision.
968    pub fn reply(&mut self, bytes: &[u8]) -> Event<'static> {
969        if self.done {
970            return self.timeout(bytes);
971        }
972        match Frame::parse(bytes) {
973            Ok(None) => Event::NeedMore,
974            // Bytes after a frame: a second answer overlapping the first.
975            Ok(Some((_, used))) if used < bytes.len() => self.collision(),
976            Ok(Some((Frame::Ack, _))) if !self.reading => {
977                self.reading = true;
978                self.tries = 0;
979                Event::Acknowledged
980            }
981            // E5 to the read: the selected meter answered, but not with data.
982            Ok(Some((Frame::Ack, _))) => self.timeout(&[]),
983            Ok(Some((Frame::Long { c, ci, data, .. }, _))) if self.reading && control::is_response(c) => {
984                let probe = self.probe();
985                match Application::parse(ci, data).ok().and_then(|a| a.meter()) {
986                    Some(meter) if probe.matches(&meter) => {
987                        self.next_sibling();
988                        Event::Found(meter)
989                    }
990                    _ => self.unreadable(),
991                }
992            }
993            // Garbled: several meters answered.
994            _ => self.collision(),
995        }
996    }
997}