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());
30//! ```
31
32use core::fmt;
33
34use crate::app::{Address, Application, Manufacturer, Medium};
35use crate::time::DateTime;
36use crate::wired::{self, BROADCAST, Frame, NETWORK_LAYER, control};
37use crate::{Error, Result};
38
39/// CI values a master sends (EN 13757-3, m-bus.com 6.1).
40pub mod ci {
41    /// Application reset.
42    pub const APPLICATION_RESET: u8 = 0x50;
43    /// Data send (records to the slave).
44    pub const DATA_SEND: u8 = 0x51;
45    /// Selection of a slave by secondary address.
46    pub const SELECT: u8 = 0x52;
47    /// Baud rate 300 … 38400: `B8` + index.
48    pub const BAUD_300: u8 = 0xB8;
49}
50
51/// A secondary address to select, each part optional (a wildcard).
52///
53/// The identification number is eight BCD digits; any digit may be a wildcard (`F` on
54/// the wire). Manufacturer, version and medium are wildcarded as a whole.
55#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
56pub struct SecondaryAddress {
57    /// The eight digits, most significant first; `None` is a wildcard.
58    pub digits: [Option<u8>; 8],
59    /// Manufacturer, or any.
60    pub manufacturer: Option<Manufacturer>,
61    /// Version, or any.
62    pub version: Option<u8>,
63    /// Medium, or any.
64    pub medium: Option<Medium>,
65}
66
67impl SecondaryAddress {
68    /// Every meter: all wildcards.
69    pub const ANY: Self = Self { digits: [None; 8], manufacturer: None, version: None, medium: None };
70
71    /// The meter with this identification number (up to 8 decimal digits), any
72    /// manufacturer, version and medium. `None` above 99 999 999.
73    pub fn id(number: u32) -> Option<Self> {
74        if number > 99_999_999 {
75            return None;
76        }
77        // const fn: unrolled, no indexing.
78        #[allow(clippy::cast_possible_truncation)] // each digit < 10
79        let d = |k: u32| Some((number / k % 10) as u8);
80        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)];
81        Some(Self { digits, ..Self::ANY })
82    }
83
84    /// Exactly this meter: number, manufacturer, version and medium.
85    pub fn exact(address: &Address) -> Self {
86        let mut digits = [None; 8];
87        let [a, b, c, d] = address.id;
88        for (slot, byte) in digits.chunks_exact_mut(2).zip([d, c, b, a]) {
89            if let [high, low] = slot {
90                *high = Some(byte >> 4).filter(|&x| x <= 9);
91                *low = Some(byte & 0x0F).filter(|&x| x <= 9);
92            }
93        }
94        Self {
95            digits,
96            manufacturer: Some(address.manufacturer),
97            version: Some(address.version),
98            medium: Some(address.medium),
99        }
100    }
101
102    /// Parse a pattern of 8 characters, digits or `F`/`*`/`?` wildcards, e.g.
103    /// `"1234FFFF"`. Shorter patterns are padded with wildcards on the right.
104    pub fn pattern(text: &str) -> Option<Self> {
105        let mut out = Self::ANY;
106        for (n, c) in text.bytes().enumerate() {
107            let slot = out.digits.get_mut(n)?;
108            *slot = match c {
109                b'0'..=b'9' => Some(c - b'0'),
110                b'F' | b'f' | b'*' | b'?' => None,
111                _ => return None,
112            };
113        }
114        Some(out)
115    }
116
117    /// The identification number as transmitted (BCD, LSB first, `F` for wildcards).
118    pub fn id_bytes(&self) -> [u8; 4] {
119        let nibble = |d: Option<u8>| d.unwrap_or(0x0F);
120        let mut out = [0u8; 4];
121        for (i, pair) in self.digits.chunks_exact(2).enumerate() {
122            if let ([high, low], Some(slot)) = (pair, out.get_mut(3 - i)) {
123                *slot = (nibble(*high) << 4) | nibble(*low);
124            }
125        }
126        out
127    }
128
129    /// Whether `address` matches.
130    pub fn matches(&self, address: &Address) -> bool {
131        let exact = Self::exact(address);
132        self.digits.iter().zip(exact.digits).all(|(want, got)| want.is_none() || *want == got)
133            && self.manufacturer.is_none_or(|m| m == address.manufacturer)
134            && self.version.is_none_or(|v| v == address.version)
135            && self.medium.is_none_or(|m| m == address.medium)
136    }
137
138    /// The 8 data bytes of a selection: ID (BCD, LSB first), manufacturer (LE), version,
139    /// medium; wildcards as `F` nibbles, `FFFF` and `FF`.
140    pub fn to_bytes(&self) -> [u8; 8] {
141        let [i0, i1, i2, i3] = self.id_bytes();
142        let [m0, m1] = self.manufacturer.map_or(0xFFFF, |m| m.0).to_le_bytes();
143        [i0, i1, i2, i3, m0, m1, self.version.unwrap_or(0xFF), self.medium.map_or(0xFF, |m| m.0)]
144    }
145}
146
147impl fmt::Display for SecondaryAddress {
148    /// `12345678`, `1234FFFF KAM v27 water`, wildcards as `F`.
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        for d in self.digits {
151            match d {
152                Some(d) => write!(f, "{d}")?,
153                None => f.write_str("F")?,
154            }
155        }
156        if let Some(m) = self.manufacturer {
157            write!(f, " {m}")?;
158        }
159        if let Some(v) = self.version {
160            write!(f, " v{v}")?;
161        }
162        if let Some(m) = self.medium {
163            write!(f, " {m}")?;
164        }
165        Ok(())
166    }
167}
168
169/// Baud rates of wired M-Bus.
170#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
171pub enum Baud {
172    /// 300 Bd.
173    B300,
174    /// 600 Bd.
175    B600,
176    /// 1200 Bd.
177    B1200,
178    /// 2400 Bd (the default of most meters).
179    B2400,
180    /// 4800 Bd.
181    B4800,
182    /// 9600 Bd.
183    B9600,
184    /// 19200 Bd.
185    B19200,
186    /// 38400 Bd.
187    B38400,
188}
189
190impl Baud {
191    /// Bits per second.
192    pub const fn bits_per_second(self) -> u32 {
193        match self {
194            Self::B300 => 300,
195            Self::B600 => 600,
196            Self::B1200 => 1200,
197            Self::B2400 => 2400,
198            Self::B4800 => 4800,
199            Self::B9600 => 9600,
200            Self::B19200 => 19200,
201            Self::B38400 => 38400,
202        }
203    }
204
205    const fn ci(self) -> u8 {
206        ci::BAUD_300
207            + match self {
208                Self::B300 => 0,
209                Self::B600 => 1,
210                Self::B1200 => 2,
211                Self::B2400 => 3,
212                Self::B4800 => 4,
213                Self::B9600 => 5,
214                Self::B19200 => 6,
215                Self::B38400 => 7,
216            }
217    }
218}
219
220/// A frame to send and how long to wait for its reply.
221#[derive(Clone, Copy, Debug, PartialEq, Eq)]
222pub struct Request {
223    bytes: [u8; 32],
224    len: u8,
225    reply: bool,
226}
227
228/// The response timeout at `baud`: 330 bit times plus 50 ms (EN 13757-2 via m-bus.com
229/// 5.4), in milliseconds rounded up: 188 ms at 2400 Bd, 85 ms at 9600 Bd.
230pub const fn response_timeout_ms(baud: Baud) -> u32 {
231    (330 * 1000u32).div_ceil(baud.bits_per_second()) + 50
232}
233
234/// The default number of repetitions of a request that got no valid reply.
235pub const RETRIES: u8 = 2;
236
237impl Request {
238    const EMPTY: Self = Self { bytes: [0; 32], len: 0, reply: false };
239
240    fn from_frame(frame: &Frame<'_>, reply: bool) -> Result<Self> {
241        let mut bytes = [0u8; 32];
242        let n = frame.encode(&mut bytes)?;
243        Ok(Self { bytes, len: u8::try_from(n).map_err(|_| Error::OutputTooSmall)?, reply })
244    }
245
246    /// The bytes to write to the bus.
247    pub fn bytes(&self) -> &[u8] {
248        self.bytes.get(..usize::from(self.len)).unwrap_or(&[])
249    }
250
251    /// How long to wait for the start of the reply at `baud`, in milliseconds
252    /// ([`response_timeout_ms`]); 0 when no reply is expected (broadcast).
253    pub const fn timeout_ms(&self, baud: Baud) -> u32 {
254        if self.reply { response_timeout_ms(baud) } else { 0 }
255    }
256
257    /// The same frame with the frame count bit set or cleared (checksum recomputed).
258    /// EN 13757-2: after `SND_NKE`, and to address `FD` after every selection, the next
259    /// `SND_UD` carries FCB = 1; it toggles after each acknowledged one.
260    #[must_use]
261    pub fn with_fcb(mut self, fcb: bool) -> Self {
262        let len = usize::from(self.len);
263        let (c_at, sum) = match self.bytes() {
264            [0x10, ..] => (1, 1..3),
265            [0x68, ..] if len >= 6 => (4, 4..len - 2),
266            _ => return self,
267        };
268        if let Some(c) = self.bytes.get_mut(c_at) {
269            *c = (*c & !control::FCB) | if fcb { control::FCB } else { 0 };
270        }
271        let cs = self.bytes.get(sum).map_or(0, |b| b.iter().fold(0u8, |s, &x| s.wrapping_add(x)));
272        if let Some(slot) = self.bytes.get_mut(len - 2) {
273            *slot = cs;
274        }
275        self
276    }
277
278    /// Whether a reply is expected at all.
279    pub const fn expects_reply(&self) -> bool {
280        self.reply
281    }
282}
283
284const fn timeout_for(address: u8) -> bool {
285    address != BROADCAST
286}
287
288/// `SND_NKE`: reset the link layer of a slave (and its FCB); to [`NETWORK_LAYER`], deselect.
289pub fn link_reset(address: u8) -> Request {
290    // A short frame always fits the 32-byte request.
291    Request::from_frame(&wired::snd_nke(address), timeout_for(address)).unwrap_or(Request::EMPTY)
292}
293
294fn snd_ud(address: u8, fcb: bool, ci: u8, data: &[u8]) -> Result<Request> {
295    let c = control::SND_UD | if fcb { control::FCB } else { 0 };
296    Request::from_frame(&Frame::Long { c, a: address, ci, data }, timeout_for(address))
297}
298
299/// Select a slave by secondary address (`SND_UD` to address `FD`, CI `52`, FCB = 1 as
300/// for every selection). A slave that matches answers `E5` and is then reached at
301/// [`NETWORK_LAYER`] until deselected; every other slave deselects itself.
302pub fn select(address: &SecondaryAddress) -> Request {
303    snd_ud(NETWORK_LAYER, true, ci::SELECT, &address.to_bytes()).unwrap_or(Request::EMPTY)
304}
305
306/// Enhanced selection: also match the fabrication number (record `0C 78`, 8 BCD digits;
307/// `None` wildcards it). For two meters that share an identification number. A slave that
308/// does not support it does not answer.
309pub fn select_enhanced(address: &SecondaryAddress, fabrication: Option<u32>) -> Request {
310    let fab = fabrication.and_then(SecondaryAddress::id).map_or([0xFF; 4], |f| f.id_bytes());
311    let [a, b, c, d, e, f, g, h] = address.to_bytes();
312    let [f0, f1, f2, f3] = fab;
313    snd_ud(NETWORK_LAYER, true, ci::SELECT, &[a, b, c, d, e, f, g, h, 0x0C, 0x78, f0, f1, f2, f3])
314        .unwrap_or(Request::EMPTY)
315}
316
317/// Deselect: `SND_NKE` to the network-layer address.
318pub fn deselect() -> Request {
319    link_reset(NETWORK_LAYER)
320}
321
322/// Set a slave's primary address (`SND_UD`, CI `51`, record `01 7A new`). `None` for the
323/// reserved addresses 251–255. Make sure first that nothing answers at `new`
324/// ([`link_reset`] to it times out): two slaves on one address cannot be read.
325pub fn set_primary_address(address: u8, new: u8) -> Option<Request> {
326    (new <= 250).then(|| snd_ud(address, false, ci::DATA_SEND, &[0x01, 0x7A, new]).unwrap_or(Request::EMPTY))
327}
328
329/// Reset a slave's application layer (CI `50`), optionally only one telegram type (the
330/// subcode: upper nibble the type, e.g. `1x` user data, lower nibble the subtelegram).
331/// Also drops a readout selection back to the standard telegram.
332pub fn application_reset(address: u8, subcode: Option<u8>) -> Request {
333    let data = subcode.map(|s| [s]);
334    snd_ud(address, false, ci::APPLICATION_RESET, data.as_ref().map_or(&[][..], |d| &d[..]))
335        .unwrap_or(Request::EMPTY)
336}
337
338/// Ask for all data in the next `REQ_UD2` (global readout request, DIF `7F`).
339pub fn request_all_data(address: u8) -> Request {
340    snd_ud(address, false, ci::DATA_SEND, &[0x7F]).unwrap_or(Request::EMPTY)
341}
342
343/// Switch a slave to another baud rate (CI `B8`–`BF`). The slave acknowledges at the old
344/// rate and listens at the new one.
345pub fn set_baud(address: u8, baud: Baud) -> Request {
346    snd_ud(address, false, baud.ci(), &[]).unwrap_or(Request::EMPTY)
347}
348
349/// Set a slave's clock (CI `51`, record `04 6D` date and time, type F).
350pub fn set_time(address: u8, time: &DateTime) -> Request {
351    let [a, b, c, d] = time.to_type_f();
352    snd_ud(address, false, ci::DATA_SEND, &[0x04, 0x6D, a, b, c, d]).unwrap_or(Request::EMPTY)
353}
354
355/// Whom a readout reads.
356#[derive(Clone, Copy, Debug, PartialEq, Eq)]
357pub enum Target {
358    /// A primary address (0–250).
359    Primary(u8),
360    /// A secondary address, selected first and deselected after.
361    Secondary(SecondaryAddress),
362}
363
364/// What happened when a reply (or its absence) was handed to a state machine.
365#[derive(Clone, Debug)]
366#[allow(clippy::large_enum_variant)] // returned by value once per reply; boxing needs alloc
367pub enum Event<'a> {
368    /// The bytes are the start of a frame: read more and call `reply` again with all of
369    /// them.
370    NeedMore,
371    /// A telegram with records (for a readout).
372    Telegram(Application<'a>),
373    /// A meter was found (for a search).
374    Found(Address),
375    /// Several meters share this full identification number; select them with
376    /// [`select_enhanced`] (fabrication number) or by manufacturer, version and medium.
377    Ambiguous(SecondaryAddress),
378    /// The slave acknowledged (`E5`).
379    Acknowledged,
380    /// No valid reply; the request will be repeated.
381    Retrying,
382    /// No valid reply after every retry: the slave does not answer.
383    NoReply,
384    /// A valid frame that cannot be decoded as a telegram.
385    Invalid(Error),
386}
387
388#[derive(Clone, Copy, Debug, PartialEq, Eq)]
389enum ReadState {
390    Reset,
391    Select,
392    Read,
393    Deselect,
394    Done,
395    Failed,
396}
397
398/// Read every telegram of one meter: `SND_NKE` (primary) or selection (secondary), then
399/// `REQ_UD2` with the frame count bit toggled until no more records follow, then
400/// deselection (secondary). A request without a valid reply is repeated with the same
401/// FCB, [`RETRIES`] times.
402#[derive(Clone, Debug)]
403pub struct Readout {
404    target: Target,
405    state: ReadState,
406    fcb: bool,
407    tries: u8,
408    retries: u8,
409    telegrams: u8,
410    max_telegrams: u8,
411}
412
413impl Readout {
414    /// A readout with the default retries and a limit of 16 telegrams.
415    pub const fn new(target: Target) -> Self {
416        // Secondary: deselect every slave first (SND_NKE to FD), so no stale selection
417        // answers along.
418        let state = ReadState::Reset;
419        let _ = target;
420        Self { target, state, fcb: true, tries: 0, retries: RETRIES, telegrams: 0, max_telegrams: 16 }
421    }
422
423    /// Repeat a request at most `retries` times.
424    #[must_use]
425    pub const fn retries(mut self, retries: u8) -> Self {
426        self.retries = retries;
427        self
428    }
429
430    /// Stop after `max` telegrams even if the meter says more follow.
431    #[must_use]
432    pub const fn max_telegrams(mut self, max: u8) -> Self {
433        self.max_telegrams = max;
434        self
435    }
436
437    const fn address(&self) -> u8 {
438        match self.target {
439            Target::Primary(a) => a,
440            Target::Secondary(_) => NETWORK_LAYER,
441        }
442    }
443
444    /// The next frame to send, or `None` when the readout is over.
445    pub fn next_request(&mut self) -> Option<Request> {
446        Some(match (self.state, self.target) {
447            // Primary: SND_NKE to the slave. Secondary: SND_NKE to FD, deselecting all.
448            (ReadState::Reset, _) => link_reset(self.address()),
449            (ReadState::Select, Target::Secondary(s)) => select(&s),
450            (ReadState::Read, _) => {
451                Request::from_frame(&wired::req_ud2(self.address(), self.fcb), timeout_for(0)).ok()?
452            }
453            (ReadState::Deselect, _) => deselect(),
454            _ => return None,
455        })
456    }
457
458    /// Whether every telegram was read.
459    pub const fn is_complete(&self) -> bool {
460        matches!(self.state, ReadState::Done)
461    }
462
463    /// How many telegrams were read.
464    pub const fn telegrams(&self) -> u8 {
465        self.telegrams
466    }
467
468    fn advance(&mut self, next: ReadState) {
469        self.state = next;
470        self.tries = 0;
471    }
472
473    fn after_read(&self) -> ReadState {
474        match self.target {
475            Target::Primary(_) => ReadState::Done,
476            Target::Secondary(_) => ReadState::Deselect,
477        }
478    }
479
480    /// The timeout passed without a valid reply (`received` is ignored: a readout
481    /// repeats the request either way).
482    pub fn timeout(&mut self, received: &[u8]) -> Event<'static> {
483        let _ = received;
484        if let (ReadState::Reset, Target::Secondary(_)) = (self.state, self.target) {
485            // Unselected slaves need not answer the deselection: go on to the selection.
486            self.advance(ReadState::Select);
487            return Event::NoReply;
488        }
489        if self.state == ReadState::Deselect {
490            // A deselection is not acknowledged by every slave; the data is complete.
491            self.advance(ReadState::Done);
492            return Event::NoReply;
493        }
494        if self.tries < self.retries {
495            self.tries += 1;
496            Event::Retrying
497        } else {
498            self.state = ReadState::Failed;
499            Event::NoReply
500        }
501    }
502
503    /// Hand over what arrived: the bytes from the start of the reply.
504    pub fn reply<'a>(&mut self, bytes: &'a [u8]) -> Event<'a> {
505        let frame = match Frame::parse(bytes) {
506            Ok(None) => return Event::NeedMore,
507            Ok(Some((frame, _))) => frame,
508            Err(_) => return self.timeout(bytes),
509        };
510        match (self.state, frame) {
511            (ReadState::Reset, Frame::Ack) => {
512                // EN 13757-2: after SND_NKE the next REQ_UD2 has FCB set.
513                self.fcb = true;
514                let next = match self.target {
515                    Target::Primary(_) => ReadState::Read,
516                    Target::Secondary(_) => ReadState::Select,
517                };
518                self.advance(next);
519                Event::Acknowledged
520            }
521            (ReadState::Select, Frame::Ack) => {
522                self.fcb = true;
523                self.advance(ReadState::Read);
524                Event::Acknowledged
525            }
526            (ReadState::Deselect, _) => {
527                self.advance(ReadState::Done);
528                Event::Acknowledged
529            }
530            // E5 instead of data: the slave has nothing (more) to send.
531            (ReadState::Read, Frame::Ack) => {
532                self.advance(self.after_read());
533                Event::Acknowledged
534            }
535            (ReadState::Read, Frame::Long { ci, data, .. }) => match Application::parse(ci, data) {
536                Ok(app) => {
537                    self.telegrams = self.telegrams.saturating_add(1);
538                    let more =
539                        app.records().is_some_and(|r| more_follows(r)) && self.telegrams < self.max_telegrams;
540                    self.fcb = !self.fcb;
541                    let next = if more { ReadState::Read } else { self.after_read() };
542                    self.advance(next);
543                    Event::Telegram(app)
544                }
545                Err(e) => {
546                    self.advance(self.after_read());
547                    Event::Invalid(e)
548                }
549            },
550            _ => self.timeout(bytes),
551        }
552    }
553}
554
555/// Whether a telegram's records end with `1F` (more records follow).
556fn more_follows(mut records: crate::Records<'_>) -> bool {
557    for _ in records.by_ref() {}
558    records.more_follows()
559}
560
561/// A secondary-address search (wildcard scan): finds every meter on the bus.
562///
563/// Probes a selection with the first digit fixed and the rest wildcarded. No reply: no
564/// meter there. `E5`: exactly one meter, read with `REQ_UD2` to learn its address. A
565/// garbled reply: several meters collided, so the next digit is fixed too, 0 to 9, and
566/// so on. Depth-first, at most 8 digits deep; ends after at most `10 × 8 × (meters + 1)`
567/// selections, plus one read per meter.
568#[derive(Clone, Debug)]
569pub struct Search {
570    prefix: [u8; 8],
571    depth: u8,
572    reading: bool,
573    done: bool,
574    tries: u8,
575    retries: u8,
576    selections: u32,
577    max_selections: u32,
578    exhausted: bool,
579}
580
581impl Default for Search {
582    fn default() -> Self {
583        Self::new()
584    }
585}
586
587impl Search {
588    /// A search of the whole bus.
589    pub const fn new() -> Self {
590        Self {
591            prefix: [0; 8],
592            depth: 1,
593            reading: false,
594            done: false,
595            tries: 0,
596            retries: RETRIES,
597            selections: 0,
598            max_selections: 20_000,
599            exhausted: false,
600        }
601    }
602
603    /// Give up after `max` selections (default 20 000: a bus of 250 meters needs at most
604    /// 10 × 8 × 251). A stuck line or a babbling device makes every probe look like a
605    /// collision, and the full tree has 10⁸ prefixes.
606    #[must_use]
607    pub const fn max_selections(mut self, max: u32) -> Self {
608        self.max_selections = max;
609        self
610    }
611
612    /// Whether the search covered the whole bus (`false` while running, or after it gave
613    /// up at [`Search::max_selections`]).
614    pub const fn is_complete(&self) -> bool {
615        self.done && !self.exhausted
616    }
617
618    /// The selection pattern being probed.
619    pub fn probe(&self) -> SecondaryAddress {
620        let mut s = SecondaryAddress::ANY;
621        for (slot, digit) in s.digits.iter_mut().zip(self.prefix).take(usize::from(self.depth)) {
622            *slot = Some(digit);
623        }
624        s
625    }
626
627    /// How many selections have been sent.
628    pub const fn selections(&self) -> u32 {
629        self.selections
630    }
631
632    /// The next frame to send, or `None` when the search is over.
633    pub fn next_request(&mut self) -> Option<Request> {
634        if self.done {
635            return None;
636        }
637        if self.reading {
638            return Request::from_frame(&wired::req_ud2(NETWORK_LAYER, true), timeout_for(0)).ok();
639        }
640        if self.tries == 0 {
641            if self.selections >= self.max_selections {
642                self.done = true;
643                self.exhausted = true;
644                return None;
645            }
646            self.selections = self.selections.saturating_add(1);
647        }
648        Some(select(&self.probe()))
649    }
650
651    /// Move to the next prefix at this depth, climbing up when a digit's 0–9 are done.
652    fn next_sibling(&mut self) {
653        self.tries = 0;
654        self.reading = false;
655        loop {
656            let Some(d) = self.prefix.get_mut(usize::from(self.depth) - 1) else {
657                self.done = true;
658                return;
659            };
660            if *d < 9 {
661                *d += 1;
662                return;
663            }
664            *d = 0;
665            if self.depth == 1 {
666                self.done = true;
667                return;
668            }
669            self.depth -= 1;
670        }
671    }
672
673    /// The timeout passed. `received` is whatever arrived in that time (empty if
674    /// nothing): bytes that are not a valid frame mean several meters answered at once.
675    pub fn timeout(&mut self, received: &[u8]) -> Event<'static> {
676        if !received.is_empty() {
677            return self.collision();
678        }
679        if self.tries < self.retries {
680            self.tries += 1;
681            return Event::Retrying;
682        }
683        // No meter under this prefix (or the selected one did not answer the read).
684        self.next_sibling();
685        Event::NoReply
686    }
687
688    /// Several meters answered: fix one more digit, starting at 0.
689    fn collision(&mut self) -> Event<'static> {
690        self.reading = false;
691        self.tries = 0;
692        if self.depth >= 8 {
693            // A full ID collides: two meters with one number. Report it and go on.
694            let probe = self.probe();
695            self.next_sibling();
696            return Event::Ambiguous(probe);
697        }
698        self.depth += 1;
699        if let Some(d) = self.prefix.get_mut(usize::from(self.depth) - 1) {
700            *d = 0;
701        }
702        Event::Retrying
703    }
704
705    /// Hand over what arrived. Incomplete but plausible bytes: [`Event::NeedMore`];
706    /// anything invalid: a collision.
707    pub fn reply(&mut self, bytes: &[u8]) -> Event<'static> {
708        match Frame::parse(bytes) {
709            Ok(None) => Event::NeedMore,
710            // Bytes after a frame: a second answer overlapping the first.
711            Ok(Some((_, used))) if used < bytes.len() => self.collision(),
712            Ok(Some((Frame::Ack, _))) if !self.reading => {
713                self.reading = true;
714                self.tries = 0;
715                Event::Acknowledged
716            }
717            Ok(Some((Frame::Long { ci, data, .. }, _))) if self.reading => {
718                let found = Application::parse(ci, data).ok().and_then(|a| a.meter());
719                self.next_sibling();
720                found.map_or(Event::NoReply, Event::Found)
721            }
722            // Garbled, or an E5 that was two overlapping E5s: several meters answered.
723            _ => self.collision(),
724        }
725    }
726}