mbus-kit 0.4.0

M-Bus and wireless M-Bus (EN 13757-2/-3/-4) for Rust: heat, water and gas meter readout with a sans-I/O, no_std, allocation-free core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! `mbus`: decode, read, search and listen to M-Bus and wireless M-Bus meters.
//!
//! ```text
//! cargo install mbus-kit --features cli
//! mbus decode captures.hex --key 0102…0F11 --json
//! mbus read /dev/ttyUSB0 5
//! mbus search /dev/ttyUSB0
//! mbus listen /dev/ttyUSB0 --stick im871a --mode t1 --key 0102…0F11
//! ```

use std::io::{self, BufRead, ErrorKind, Read, Write};
use std::net::TcpStream;
use std::process::ExitCode;
use std::time::Duration;

use mbus_kit::app::Authenticity;
use mbus_kit::compact::{Format as Layout, FormatCache};
use mbus_kit::fragment::Reassembly;
use mbus_kit::json::{Json, JsonAddress, JsonString};
use mbus_kit::master::{Baud, Heard, Outcome, SecondaryAddress, Target};
use mbus_kit::oms::Key;
use mbus_kit::serial::{Bus, Error};
use mbus_kit::stick::{LinkMode, Message, Receiver, Stick};
use mbus_kit::wired::Frame;
use mbus_kit::wireless::{self, Format};
use mbus_kit::{Application, Body, Header};

/// `println!` that ends the process quietly when the reader has gone (`mbus … | head`),
/// and with exit code 1 when stdout fails otherwise.
macro_rules! out {
    ($($arg:tt)*) => {{
        let mut stdout = io::stdout().lock();
        if let Err(e) = writeln!(stdout, $($arg)*) {
            std::process::exit(i32::from(e.kind() != io::ErrorKind::BrokenPipe));
        }
    }};
}

const USAGE: &str = "\
mbus — M-Bus and wireless M-Bus meters

usage:
  mbus decode [FILE] [--key HEX]... [--format a|b|stripped] [--json]
      hex telegrams, one per line (stdin without FILE); wired or wireless, detected;
      rtl-wmbus lines; `key …` and `format …` lines; compact frames and fragments joined
  mbus read DEVICE ADDRESS [--baud 2400] [--key HEX]... [--json] [--no-stty]
      read a wired meter: ADDRESS is a primary address (0–250), an 8-digit ID, or
      an ID with wildcards (1234FFFF); DEVICE is a serial device or tcp:HOST:PORT
  mbus search DEVICE [--baud …] [--json] [--no-stty]
      find every meter on the bus by secondary address
  mbus listen DEVICE --stick im871a|iu891a|amb8465 [--mode t1|c1|c1t1|s1]
              [--key HEX]... [--json] [--setup] [--no-stty]
      receive radio telegrams through a stick (DEVICE `-`: a recorded stream on stdin);
      --setup prepares an Amber stick once (writes its flash)

The serial device is configured with stty (8E1 for M-Bus, 8N1 for sticks) unless
--no-stty is given.";

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match run(&args) {
        Ok(()) => ExitCode::SUCCESS,
        Err(Failure::Usage(msg)) => {
            eprintln!("mbus: {msg}\n\n{USAGE}");
            ExitCode::from(2)
        }
        Err(Failure::Run(msg)) => {
            eprintln!("mbus: {msg}");
            ExitCode::FAILURE
        }
    }
}

enum Failure {
    Usage(String),
    Run(String),
}

impl<E: std::fmt::Display> From<E> for Failure {
    fn from(e: E) -> Self {
        Self::Run(e.to_string())
    }
}

/// Command-line options shared by every command.
#[derive(Default)]
struct Options {
    positional: Vec<String>,
    keys: Vec<Key>,
    json: bool,
    stty: bool,
    setup: bool,
    baud: Option<Baud>,
    format: Option<Format>,
    stick: Option<Stick>,
    mode: Option<LinkMode>,
}

fn options(args: &[String]) -> Result<Options, Failure> {
    let usage = |m: String| Failure::Usage(m);
    let mut o = Options { stty: true, ..Options::default() };
    let mut it = args.iter();
    while let Some(a) = it.next() {
        let mut value = |name: &str| it.next().cloned().ok_or_else(|| usage(format!("{name} needs a value")));
        match a.as_str() {
            "--json" => o.json = true,
            "--no-stty" => o.stty = false,
            "--setup" => o.setup = true,
            "--key" => {
                let v = value("--key")?;
                o.keys.push(Key::from_hex(&v).ok_or_else(|| usage("a key is 32 hex digits".into()))?);
            }
            "--baud" => {
                let v = value("--baud")?;
                let n: u32 =
                    v.parse().map_err(|_| usage(format!("--baud takes bits per second, not {v}")))?;
                o.baud = Some(Baud::try_from(n).map_err(|e| usage(e.to_string()))?);
            }
            "--format" => {
                o.format = Some(
                    parse_format(&value("--format")?).ok_or_else(|| usage("--format a|b|stripped".into()))?,
                )
            }
            "--stick" => {
                o.stick = Some(match value("--stick")?.as_str() {
                    "im871a" | "im170a" => Stick::Im871a,
                    "iu891a" | "im891a" | "iu893a" => Stick::Iu891a,
                    "amb8465" | "amb8665" | "amber" => Stick::Amb8465,
                    other => return Err(usage(format!("unknown stick {other}"))),
                });
            }
            "--mode" => {
                o.mode = Some(match value("--mode")?.to_ascii_lowercase().as_str() {
                    "s1" => LinkMode::S1,
                    "t1" => LinkMode::T1,
                    "c1" => LinkMode::C1,
                    "c1t1" | "ct" | "c1+t1" => LinkMode::C1T1,
                    other => return Err(usage(format!("unknown mode {other}"))),
                });
            }
            flag if flag.starts_with("--") => return Err(usage(format!("unknown option {flag}"))),
            other => o.positional.push(other.to_owned()),
        }
    }
    Ok(o)
}

fn parse_format(f: &str) -> Option<Format> {
    match f {
        "a" | "A" => Some(Format::A),
        "b" | "B" => Some(Format::B),
        "stripped" => Some(Format::Stripped),
        _ => None,
    }
}

fn run(args: &[String]) -> Result<(), Failure> {
    let (cmd, rest) = args.split_first().ok_or_else(|| Failure::Usage("no command".into()))?;
    let o = options(rest)?;
    match cmd.as_str() {
        "decode" => decode(&o),
        "read" => read(&o),
        "search" => search(&o),
        "listen" => listen(&o),
        "help" | "-h" | "--help" => {
            out!("{USAGE}");
            Ok(())
        }
        "--version" | "version" => {
            out!("mbus {}", env!("CARGO_PKG_VERSION"));
            Ok(())
        }
        other => Err(Failure::Usage(format!("unknown command {other}"))),
    }
}

// ---- output

/// What a telegram passes through: keys, learnt layouts, the output style.
struct Ctx {
    keys: Vec<Key>,
    formats: FormatCache<32, 255>,
    json: bool,
    rssi: Option<i16>,
}

impl Ctx {
    fn new(o: &Options) -> Self {
        Self { keys: o.keys.clone(), formats: FormatCache::new(), json: o.json, rssi: None }
    }
}

/// Decrypt, join, expand and print one application.
fn handle(app: &Application<'_>, ctx: &mut Ctx, fragments: Option<&mut Reassembly<'_>>) {
    match &app.body {
        Body::Encrypted(e) => {
            for key in &ctx.keys.clone() {
                let mut plain = [0u8; 600];
                if let Ok(inner) = e.decrypt(key, &mut plain) {
                    return handle(&inner, ctx, fragments);
                }
            }
            if !ctx.keys.is_empty() && !ctx.json {
                out!("  no key opens it ({:?})", e.security);
            }
            show(app, ctx);
        }
        Body::Fragment(_) => match fragments {
            Some(f) => match f.push(app) {
                Ok(Some(message)) => handle(&message, ctx, None),
                Ok(None) => {
                    if !ctx.json {
                        out!("  fragment {} (waiting for more)", app.afl.map_or(0, |a| a.fragment_id()));
                    }
                }
                Err(e) => eprintln!("mbus: fragment: {e}"),
            },
            None => show(app, ctx),
        },
        Body::Compact(_) => {
            let mut out = [0u8; 600];
            match app.expand(&ctx.formats, &mut out) {
                Ok(full) => show(&full, ctx),
                Err(e) => {
                    if !ctx.json {
                        out!("  compact frame: {e} (a full frame of this meter teaches the layout)");
                    }
                    show(app, ctx);
                }
            }
        }
        Body::Format(layout) => {
            ctx.formats.insert(layout);
            show(app, ctx);
        }
        Body::Records(records) => {
            let mut layout = [0u8; 255];
            if let Some(l) = Layout::of(records, &mut layout) {
                ctx.formats.insert(&l);
            }
            show(app, ctx);
        }
        _ => show(app, ctx),
    }
}

fn show(app: &Application<'_>, ctx: &Ctx) {
    if ctx.json {
        out!("{}", Json::new(app).rssi(ctx.rssi));
        return;
    }
    let mut line = String::new();
    if let Some(m) = app.meter() {
        line.push_str(&m.to_string());
    }
    if let Some(dbm) = ctx.rssi {
        line.push_str(&format!(" · {dbm} dBm"));
    }
    match app.header {
        Header::Long(h) => line.push_str(&format!(" · access {}", h.short.access_number)),
        Header::Short(s) => line.push_str(&format!(" · access {}", s.access_number)),
        Header::None => {}
    }
    line.push_str(match app.authenticity {
        Authenticity::None => " · not authenticated",
        Authenticity::Encrypted => " · decrypted, not authenticated",
        Authenticity::Authenticated { .. } => " · authenticated",
    });
    if let Authenticity::Authenticated { counter } = app.authenticity {
        line.push_str(&format!(" (counter {counter})"));
    }
    out!("{}", line.trim_start_matches(" · "));
    match &app.body {
        Body::Records(records) => {
            let mut records = records.clone();
            for r in records.by_ref() {
                match r {
                    Ok(r)
                        if app.authenticity != Authenticity::None && r.authenticity == Authenticity::None =>
                    {
                        out!("  {r}  (unprotected)");
                    }
                    Ok(r) => out!("  {r}"),
                    Err(e) => out!("  record error: {e}"),
                }
            }
            if let Some(m) = records.manufacturer_data().filter(|m| !m.is_empty()) {
                let unprotected = app.authenticity != Authenticity::None
                    && records.manufacturer_authenticity() == Authenticity::None;
                out!("  manufacturer data: {m:02X?}{}", if unprotected { "  (unprotected)" } else { "" });
            }
        }
        Body::Encrypted(e) => {
            out!("  encrypted · {:?} · {} bytes (pass --key)", e.security, e.data.len())
        }
        Body::Compact(c) => out!("  compact frame · signature {:04X}", c.signature),
        Body::Format(f) => out!("  format frame · signature {:04X} (remembered)", f.signature),
        Body::Fragment(d) => out!("  fragment · {} bytes", d.len()),
        Body::ApplicationError(b) => out!("  application error {b:02X?}"),
        Body::Alarm(b) => out!("  alarm {b:02X?}"),
        Body::Empty => out!("  no application data"),
    }
}

// ---- decode

fn decode(o: &Options) -> Result<(), Failure> {
    let input: Box<dyn BufRead> = match o.positional.first() {
        Some(path) if path != "-" => Box::new(io::BufReader::new(std::fs::File::open(path)?)),
        _ => Box::new(io::BufReader::new(io::stdin())),
    };
    let mut ctx = Ctx::new(o);
    let mut format = o.format;
    let mut buf = vec![0u8; 16_384];
    let mut fragments = Reassembly::new(&mut buf);
    for line in input.lines() {
        let line = line?;
        let line = line.split('#').next().unwrap_or("").trim();
        if line.is_empty() || line.starts_with(['=', '!']) {
            continue;
        }
        if let Some(f) = line.strip_prefix("format ") {
            format = parse_format(f.trim());
            continue;
        }
        if let Some(k) = line.strip_prefix("key ") {
            ctx.keys.push(Key::from_hex(k.trim()).ok_or("a key line needs 32 hex digits")?);
            continue;
        }
        // rtl-wmbus: MODE;CRC_OK;3OUTOF6_OK;TIME;RSSI;RSSI;ID;0x<frame without CRCs>
        let (hex, this_format) = match line.rsplit_once(';') {
            Some((meta, frame)) if meta.split(';').nth(1) == Some("1") => {
                (frame.trim().trim_start_matches("0x").to_owned(), Some(Format::Stripped))
            }
            Some(_) => continue,
            None => (line.to_owned(), format),
        };
        let digits: String = hex.chars().filter(char::is_ascii_hexdigit).collect();
        if digits.len() % 2 != 0 {
            eprintln!("mbus: odd number of hex digits: {line}");
            continue;
        }
        let bytes: Vec<u8> = (0..digits.len() / 2)
            .filter_map(|i| u8::from_str_radix(&digits[2 * i..2 * i + 2], 16).ok())
            .collect();
        if let Err(e) = decode_one(&bytes, this_format, &mut ctx, &mut fragments) {
            if ctx.json {
                out!("{{\"error\":{}}}", JsonString(&e.to_string()));
            } else {
                out!("error: {e}");
            }
        }
        if !ctx.json {
            out!();
        }
    }
    Ok(())
}

fn decode_one(
    bytes: &[u8],
    format: Option<Format>,
    ctx: &mut Ctx,
    fragments: &mut Reassembly<'_>,
) -> mbus_kit::Result<()> {
    let wired = matches!(bytes, [0x68, _, _, 0x68, ..] | [0x10, ..] | [0xE5]);
    if wired && format.is_none() {
        let Some((frame, _)) = Frame::parse(bytes)? else { return Err(mbus_kit::Error::UnexpectedEnd) };
        let Frame::Long { ci, data, .. } = frame else {
            if !ctx.json {
                out!("{frame:?}");
            }
            return Ok(());
        };
        handle(&Application::parse(ci, data)?, ctx, Some(fragments));
        return Ok(());
    }
    let formats: &[Format] = match &format {
        Some(f) => std::slice::from_ref(f),
        None => &[Format::A, Format::Stripped, Format::B],
    };
    let mut last = mbus_kit::Error::UnexpectedEnd;
    for &f in formats {
        let mut buf = [0u8; 600];
        match wireless::decode(bytes, f, &mut buf) {
            Ok(Some((frame, _))) => {
                handle(&frame.application()?, ctx, Some(fragments));
                return Ok(());
            }
            Ok(None) => last = mbus_kit::Error::UnexpectedEnd,
            Err(e) => last = e,
        }
    }
    Err(last)
}

// ---- wired

/// A serial device or a TCP gateway.
enum Port {
    Device(std::fs::File),
    Tcp(TcpStream),
}

impl Read for Port {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            Self::Device(f) => f.read(buf),
            // A socket reads 0 bytes only when the gateway closed it.
            Self::Tcp(s) => match s.read(buf)? {
                0 if !buf.is_empty() => {
                    Err(io::Error::new(ErrorKind::UnexpectedEof, "the gateway closed the connection"))
                }
                n => Ok(n),
            },
        }
    }
}

impl Write for Port {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            Self::Device(f) => f.write(buf),
            Self::Tcp(s) => s.write(buf),
        }
    }
    fn flush(&mut self) -> io::Result<()> {
        match self {
            Self::Device(f) => f.flush(),
            Self::Tcp(s) => s.flush(),
        }
    }
}

/// `stty` for 8E1 (M-Bus) or 8N1 (sticks), raw. M-Bus reads return at once (the driver
/// polls and times every reply itself); stick reads wait up to 100 ms.
fn stty(device: &str, baud: u32, even_parity: bool) -> Result<(), Failure> {
    let flag = if cfg!(target_os = "macos") { "-f" } else { "-F" };
    let parity: &[&str] = if even_parity { &["parenb", "-parodd"] } else { &["-parenb"] };
    let status = std::process::Command::new("stty")
        .arg(flag)
        .arg(device)
        .arg(baud.to_string())
        .args(["cs8", "-cstopb"])
        .args(parity)
        .args(["raw", "-echo", "min", "0", "time", if even_parity { "0" } else { "1" }])
        .status()
        .map_err(|e| format!("stty: {e} (configure the port yourself and pass --no-stty)"))?;
    if !status.success() {
        return Err(Failure::Run(format!("stty could not configure {device} (pass --no-stty to skip)")));
    }
    Ok(())
}

fn open_bus(o: &Options) -> Result<Bus<Port>, Failure> {
    let device = o.positional.first().ok_or_else(|| Failure::Usage("which device?".into()))?;
    let baud = o.baud.unwrap_or(Baud::B2400);
    let (port, slack) = if let Some(addr) = device.strip_prefix("tcp:") {
        let stream = TcpStream::connect(addr)?;
        stream.set_read_timeout(Some(Duration::from_millis(10)))?;
        (Port::Tcp(stream), 200)
    } else {
        if o.stty && cfg!(unix) {
            stty(device, baud.bits_per_second(), true)?;
        }
        (Port::Device(std::fs::OpenOptions::new().read(true).write(true).open(device)?), 50)
    };
    Ok(Bus::new(port, baud).slack(Duration::from_millis(slack)))
}

fn read(o: &Options) -> Result<(), Failure> {
    let what = o
        .positional
        .get(1)
        .ok_or_else(|| Failure::Usage("which address? (0–250, an 8-digit ID or 1234FFFF)".into()))?;
    let target = if what.len() <= 3 {
        let a = what.parse().ok().filter(|a: &u8| *a <= 250);
        Target::Primary(a.ok_or_else(|| Failure::Usage(format!("{what} is not a primary address (0–250)")))?)
    } else {
        let id = SecondaryAddress::pattern(what).filter(|_| what.len() == 8);
        Target::Secondary(
            id.ok_or_else(|| Failure::Usage(format!("{what} is not an 8-digit ID or pattern")))?,
        )
    };
    let mut bus = open_bus(o)?;
    let mut ctx = Ctx::new(o);
    let mut buf = vec![0u8; 16_384];
    let mut fragments = Reassembly::new(&mut buf);
    let (telegrams, incomplete) = match bus.readout(target) {
        Ok(telegrams) => (telegrams, None),
        Err(Error::Incomplete { outcome, telegrams }) => (telegrams, Some(outcome)),
        Err(e) => return Err(e.into()),
    };
    for telegram in &telegrams {
        handle(&telegram.application()?, &mut ctx, Some(&mut fragments));
    }
    // What was read is printed, but an incomplete readout is never a success.
    let Some(outcome) = incomplete else { return Ok(()) };
    let msg = format!("incomplete readout after {} telegram(s): {outcome}", telegrams.len());
    let hint = hint(outcome);
    if o.json {
        match &hint {
            Some(h) => out!("{{\"error\":{},\"hint\":{}}}", JsonString(&msg), JsonString(h)),
            None => out!("{{\"error\":{}}}", JsonString(&msg)),
        }
    }
    Err(Failure::Run(match hint {
        Some(h) => format!("{msg}\nhint: {h}"),
        None => msg,
    }))
}

/// What an installer checks when a readout heard no valid reply.
fn hint(outcome: Outcome) -> Option<String> {
    let Outcome::NoReply { heard } = outcome else { return None };
    Some(match heard {
        Heard::OtherAddress(a) => {
            format!("a meter answers from primary address {a}: read that address, or fix the configured one")
        }
        Heard::Unexpected => "something other than a meter answered: a second master on the line, or a \
                              converter echoing the request"
            .into(),
        Heard::Garbled => "several meters answered at once (a shared primary address, or a pattern that \
                           matches more than one) or the line is noisy"
            .into(),
        Heard::Nothing => "nothing on the line: check power and wiring of meter and converter, the \
                           baud rate (--baud) and the address"
            .into(),
    })
}

fn search(o: &Options) -> Result<(), Failure> {
    let mut bus = open_bus(o)?;
    if !o.json {
        eprintln!("searching (every empty probe waits for the response timeout) …");
    }
    let found = bus.search()?;
    for meter in &found.meters {
        if o.json {
            out!("{{\"meter\":{}}}", JsonAddress(meter));
        } else {
            out!("{meter}");
        }
    }
    for id in &found.ambiguous {
        if o.json {
            out!("{{\"ambiguous\":{}}}", JsonString(&id.to_string()));
        } else {
            out!("{id}: several meters share this ID (use their fabrication numbers)");
        }
    }
    for id in &found.unreadable {
        if o.json {
            out!("{{\"unreadable\":{}}}", JsonString(&id.to_string()));
        } else {
            out!("{id}: a meter answers this selection but does not name itself");
        }
    }
    if !found.complete {
        eprintln!("mbus: the search gave up at its selection limit: is the line stuck?");
    }
    Ok(())
}

// ---- radio

fn listen(o: &Options) -> Result<(), Failure> {
    let stick = o.stick.ok_or_else(|| Failure::Usage("which stick? --stick im871a|iu891a|amb8465".into()))?;
    let mode = o.mode.unwrap_or(LinkMode::T1);
    let device = o.positional.first().map_or("-", String::as_str);
    let mut port: Box<dyn Read> = if device == "-" {
        Box::new(io::stdin())
    } else {
        if o.stty && cfg!(unix) {
            stty(device, stick.baud(), false)?;
        }
        let mut file = std::fs::OpenOptions::new().read(true).write(true).open(device)?;
        if o.setup {
            for command in stick.setup() {
                file.write_all(command.bytes())?;
                std::thread::sleep(Duration::from_millis(300));
            }
        }
        let listen =
            stick.listen(mode).ok_or_else(|| Failure::Run(format!("{stick:?} cannot receive {mode}")))?;
        file.write_all(listen.bytes())?;
        eprintln!("listening for {mode} on {device} ({stick:?}, {} Bd) …", stick.baud());
        Box::new(file)
    };
    let mut ctx = Ctx::new(o);
    let mut rx = Receiver::new(stick);
    let mut buf = vec![0u8; 16_384];
    let mut fragments = Reassembly::new(&mut buf);
    let mut chunk = [0u8; 512];
    loop {
        let n = match port.read(&mut chunk) {
            Ok(0) if device == "-" => return Ok(()),
            Ok(n) => n,
            Err(e) if matches!(e.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock) => 0,
            Err(e) => return Err(e.into()),
        };
        let mut rest = &chunk[..n];
        loop {
            let taken = rx.extend(rest);
            rest = &rest[taken..];
            while let Some(message) = rx.next_message() {
                match message {
                    Ok(Message::Telegram(t)) => {
                        let mut frame = [0u8; 600];
                        match wireless::decode(t.frame, Format::Stripped, &mut frame) {
                            Ok(Some((f, _))) => match f.application() {
                                Ok(app) => {
                                    ctx.rssi = t.rssi_dbm;
                                    handle(&app, &mut ctx, Some(&mut fragments));
                                }
                                Err(e) => eprintln!("mbus: {}: {e}", f.address),
                            },
                            Ok(None) => eprintln!("mbus: truncated telegram"),
                            Err(e) => eprintln!("mbus: telegram: {e}"),
                        }
                    }
                    Ok(Message::Response { group, id, payload }) => {
                        if !o.json {
                            eprintln!("stick: {group:02X}/{id:02X} {payload:02X?}");
                        }
                    }
                    Err(e) => eprintln!("stick: skipped ({e})"),
                }
            }
            if rest.is_empty() {
                break;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_heard_gets_its_own_hint() {
        let hints: Vec<String> = [Heard::Nothing, Heard::Garbled, Heard::Unexpected, Heard::OtherAddress(6)]
            .into_iter()
            .map(|heard| hint(Outcome::NoReply { heard }).unwrap())
            .collect();
        for (i, h) in hints.iter().enumerate() {
            assert!(hints.iter().skip(i + 1).all(|o| o != h));
        }
        assert!(hints[3].contains("primary address 6"));
        assert_eq!(hint(Outcome::Complete), None);
    }
}