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