kdi 0.7.0

Keyvast Device Interface (KDI): find a device by identity, control it with typed commands, read its data streams.
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
// GENERATED FROM kdi/contract.yaml BY kdi/gen.py — DO NOT EDIT.
//
// Regenerate with `make kdi-gen`. A hand edit is caught by
// kdi/tests/test_end_to_end.py::test_generated_rust_is_current, which re-renders this file and
// compares it byte-for-byte; there is no merge path for a local change.
//
// This file is COMMITTED even though the repo otherwise never tracks generated artifacts, because
// a crates.io tarball carries no Python: a consumer who cannot run the generator has to find the
// contract already compiled in.

// A TRAIT, not an inherent impl: this file is generated, so it may reach the device only through
// the one PUBLIC entry point (`Device::raw_cmd`) — no private field of `Device` and no endpoint
// number may leak into a file no human is allowed to edit, which is the same binding quarantine
// lib.rs opens with. A generated method knows a command NAME and an argument ORDER, nothing else.
//
// Why type them at all: `Device::raw_cmd` is stringly-typed, so `raw_cmd("adio.adc", &["1", "0"])`
// transposes slot and channel with no complaint (the failure kdi/frontpanel.py:61 documents),
// an out-of-range slot is learned a round trip later, and a misspelled name is learned on the
// wire. Every range below comes from contract.yaml and is checked BEFORE a byte is sent; the
// refusal is `HostErr::HostUnsafeArg`, which is the contract's own token for "refused by the host
// before it reached the wire" — `host_errors` is a CLOSED set and a conforming library mints none
// of its own (kdi/contract.yaml:93).

#![allow(dead_code)]

use std::io::ErrorKind;

use serde_json::Value;

use crate::{io_err, Device, Error, HostErr, Reply};

/// Every published command with its declared argument order. THE ORDER IS THE WIRE
/// (`request.arg_order: declared`, kdi/contract.yaml:874), so a host serialising a
/// positional `Device::raw_cmd` call reads it from here instead of keeping a second copy of
/// the registry — the copy that goes stale is the one that transposes two arguments.
/// The `scope: session` commands are listed too: they have no typed method, but they are
/// still callable through `Device::raw_cmd`.
pub const COMMANDS: &[(&str, &[&str])] = &[
    ("sys.claim", &[]),
    ("sys.release", &[]),
    ("sys.challenge", &[]),
    ("sys.unlock", &["tier", "nonce", "dna", "sig"]),
    ("sys.hello", &[]),
    ("id.boards", &["seg"]),
    ("power.status", &[]),
    ("power.up", &[]),
    ("adio.mode", &["slot", "ch1", "ch2"]),
    ("adio.fb", &["slot", "on"]),
    ("adio.dout", &["slot", "mask"]),
    ("adio.adc", &["slot", "ch", "n"]),
];

/// A mode token, 1:1 with the contract's `of:` list. One enum for every argument that
/// takes this value set — `adio.mode` declares it twice and two identical types would be
/// two things to keep in step.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum SegBoards {
    /// The contract token `main`.
    Main,

    /// The contract token `slot0`.
    Slot0,

    /// The contract token `slot1`.
    Slot1,

    /// The contract token `slot2`.
    Slot2,

    /// The contract token `slot3`.
    Slot3,

    /// The contract token `slot4`.
    Slot4,

    /// The contract token `slot5`.
    Slot5,

    /// The contract token `slot6`.
    Slot6,

    /// The contract token `slot7`.
    Slot7,
}

impl SegBoards {
    /// The contract token, 1:1 with contract.yaml.
    pub const fn token(self) -> &'static str {
        match self {
            SegBoards::Main => "main",
            SegBoards::Slot0 => "slot0",
            SegBoards::Slot1 => "slot1",
            SegBoards::Slot2 => "slot2",
            SegBoards::Slot3 => "slot3",
            SegBoards::Slot4 => "slot4",
            SegBoards::Slot5 => "slot5",
            SegBoards::Slot6 => "slot6",
            SegBoards::Slot7 => "slot7",
        }
    }

    /// Parse a token. `None` is a token this build does not know — from a device on
    /// a newer minor, which is legal and must never be a parse failure.
    pub fn from_token(s: &str) -> Option<Self> {
        Some(match s {
            "main" => SegBoards::Main,
            "slot0" => SegBoards::Slot0,
            "slot1" => SegBoards::Slot1,
            "slot2" => SegBoards::Slot2,
            "slot3" => SegBoards::Slot3,
            "slot4" => SegBoards::Slot4,
            "slot5" => SegBoards::Slot5,
            "slot6" => SegBoards::Slot6,
            "slot7" => SegBoards::Slot7,
            _ => return None,
        })
    }
}

/// A mode token, 1:1 with the contract's `of:` list. One enum for every argument that
/// takes this value set — `adio.mode` declares it twice and two identical types would be
/// two things to keep in step.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum ChMode {
    /// The contract token `off`.
    Off,

    /// The contract token `in`.
    In,

    /// The contract token `out`.
    Out,

    /// The contract token `adc`.
    Adc,

    /// The contract token `dac`.
    Dac,
}

impl ChMode {
    /// The contract token, 1:1 with contract.yaml.
    pub const fn token(self) -> &'static str {
        match self {
            ChMode::Off => "off",
            ChMode::In => "in",
            ChMode::Out => "out",
            ChMode::Adc => "adc",
            ChMode::Dac => "dac",
        }
    }

    /// Parse a token. `None` is a token this build does not know — from a device on
    /// a newer minor, which is legal and must never be a parse failure.
    pub fn from_token(s: &str) -> Option<Self> {
        Some(match s {
            "off" => ChMode::Off,
            "in" => ChMode::In,
            "out" => ChMode::Out,
            "adc" => ChMode::Adc,
            "dac" => ChMode::Dac,
            _ => return None,
        })
    }
}

/// The reply to `sys.hello`.
///
/// Handshake. fw/gw are the firmware and gateware git shas (8 hex) — equal when both came from one
/// build. The identity REGISTERS carry the same gateware sha pre-boot; the device DNA is not on
/// this command (it is AXI-side, reachable via the human `kv id`, and on `sys.challenge`). `tiers`
/// lists the tiers a session of THIS BUILD can reach, comma-joined in rank order: `public` alone
/// means the build has no unlock and no factory command; `public,service,factory` means every tier
/// is behind `sys.unlock`. A station tool refuses a build whose `tiers` lacks `factory` rather than
/// failing midway.
#[derive(Clone, Debug)]
pub struct SysHello {
    /// The reply's `proto` value — declared `u8`.
    pub proto: u8,

    /// The reply's `cmdset` value — declared `str`.
    pub cmdset: String,

    /// The reply's `kdi` value — declared `str`.
    pub kdi: String,

    /// The reply's `board_id` value — declared `u32`.
    pub board_id: u32,

    /// The reply's `fw` value — declared `str`.
    pub fw: String,

    /// The reply's `gw` value — declared `str`.
    pub gw: String,

    /// The reply's `tiers` value — declared `str`.
    pub tiers: String,
}

impl SysHello {
    fn parse(r: &Reply) -> Result<Self, Error> {
        Ok(Self {
            proto: uint(r, "proto")?,
            cmdset: text(r, "cmdset")?,
            kdi: text(r, "kdi")?,
            board_id: uint(r, "board_id")?,
            fw: text(r, "fw")?,
            gw: text(r, "gw")?,
            tiers: text(r, "tiers")?,
        })
    }
}

/// One entry of the `id.boards` reply's `boards` list — declared `[{addr: u8, serial: str}]`.
#[derive(Clone, Debug)]
pub struct IdBoardsEntry {
    /// The entry's `addr` value — declared `u8`.
    pub addr: u8,

    /// The entry's `serial` value — declared `str`.
    pub serial: String,
}

impl IdBoardsEntry {
    fn parse(v: &Value) -> Result<Self, Error> {
        Ok(Self {
            addr: uint(v, "addr")?,
            serial: text(v, "serial")?,
        })
    }
}

/// The reply to `id.boards`.
///
/// The Serial of every Board the device can see on one I2C segment: `main` is the main bus, `slotN`
/// is module mux channel N. Board-ignorant by design — the device scans 7-bit addresses 0x50..0x57,
/// reads 64 bytes at register 0 with a 16-bit register address, keeps the blocks that carry a valid
/// identity record (the internal `board_record` layout), and returns the Serial string with the
/// address it was found at. A NAK from an EEPROM address is "no Board there", never an error; a
/// blank EEPROM (all 0xFF or all 0x00) is "no record" and is omitted; only a stuck bus is reported
/// — and `i2c_nak` can only mean the mux itself (`addr` 0x77) refused the channel select. One
/// segment per call so at most 8 entries, and the reply always fits `max_body_bytes`. On a `slot`
/// segment the device holds the mux on that channel for the transaction and restores what the power
/// sequencer expects. Every other record field is unreachable below the factory tier.
#[derive(Clone, Debug)]
pub struct IdBoards {
    /// The reply's `boards` value — declared `[{addr: u8, serial: str}]`.
    pub boards: Vec<IdBoardsEntry>,
}

impl IdBoards {
    fn parse(r: &Reply) -> Result<Self, Error> {
        Ok(Self {
            boards: objects(r, "boards", IdBoardsEntry::parse)?,
        })
    }
}

/// The reply to `power.status`.
///
/// Read the power tree, writing nothing. present = module-present bitmask from the most recent
/// sequence pass (a raw detect read is NOT equivalent — after a pass those bits are outputs driving
/// the DCDC enables). reverify = the periodic re-verify thread is enabled.
#[derive(Clone, Debug)]
pub struct PowerStatus {
    /// The reply's `present` value — declared `u8`.
    pub present: u8,

    /// The reply's `reverify` value — declared `bool`.
    pub reverify: bool,
}

impl PowerStatus {
    fn parse(r: &Reply) -> Result<Self, Error> {
        Ok(Self {
            present: uint(r, "present")?,
            reverify: flag(r, "reverify")?,
        })
    }
}

/// The reply to `power.up`.
///
/// Run the rail sequence. Stim stays off. Level-set: safe to retry.
#[derive(Clone, Debug)]
pub struct PowerUp {
    /// The reply's `ok` value — declared `bool`.
    pub ok: bool,

    /// The reply's `present` value — declared `u8`.
    pub present: u8,
}

impl PowerUp {
    fn parse(r: &Reply) -> Result<Self, Error> {
        Ok(Self {
            ok: flag(r, "ok")?,
            present: uint(r, "present")?,
        })
    }
}

/// The reply to `adio.mode`.
///
/// Set a slot's two channel modes (I2C mux + CH_MODE, kept coherent).
#[derive(Clone, Debug)]
pub struct AdioMode {
    /// The reply's `slot` value — declared `u8`.
    pub slot: u8,

    /// The reply's `ch_mode` value — declared `u16`.
    pub ch_mode: u16,
}

impl AdioMode {
    fn parse(r: &Reply) -> Result<Self, Error> {
        Ok(Self {
            slot: uint(r, "slot")?,
            ch_mode: uint(r, "ch_mode")?,
        })
    }
}

/// The reply to `adio.fb`.
///
/// Cross-channel loopback tie. Independent of either channel's DIRECTION and of CH_MODE, and re-
/// asserted with the expander, so setting a mode never silently drops a tie. The muxes make it a
/// SELECT, not a strap: with the tie on, a channel routes to the other channel instead of to its
/// jack.
#[derive(Clone, Debug)]
pub struct AdioFb {
    /// The reply's `slot` value — declared `u8`.
    pub slot: u8,

    /// The reply's `fb` value — declared `u8`.
    pub fb: u8,
}

impl AdioFb {
    fn parse(r: &Reply) -> Result<Self, Error> {
        Ok(Self {
            slot: uint(r, "slot")?,
            fb: uint(r, "fb")?,
        })
    }
}

/// The reply to `adio.dout`.
///
/// Drive the digital outputs (bit0 CH1, bit1 CH2) and echo the RAW pad readback, so one call is
/// both a stimulus and its measurement. A non-zero mask is refused on an absent slot: driving a pin
/// high there back-powers the module rail. Note the pin only moves if that channel's CH_MODE is
/// out, and a driven channel reads 0 on its own TTL lane by design -- read the OTHER channel,
/// through the tie.
#[derive(Clone, Debug)]
pub struct AdioDout {
    /// The reply's `slot` value — declared `u8`.
    pub slot: u8,

    /// The reply's `dout` value — declared `u8`.
    pub dout: u8,

    /// The reply's `din` value — declared `u8`.
    pub din: u8,
}

impl AdioDout {
    fn parse(r: &Reply) -> Result<Self, Error> {
        Ok(Self {
            slot: uint(r, "slot")?,
            dout: uint(r, "dout")?,
            din: uint(r, "din")?,
        })
    }
}

/// The reply to `adio.adc`.
///
/// n is range-checked, never silently clamped (the human `kv adio adc` clamps). valid\[i\] mirrors
/// each sample's valid bit — a code with valid=false is meaningless.
#[derive(Clone, Debug)]
pub struct AdioAdc {
    /// The reply's `slot` value — declared `u8`.
    pub slot: u8,

    /// The reply's `ch` value — declared `u8`.
    pub ch: u8,

    /// The reply's `codes` value — declared `u16[]`.
    pub codes: Vec<u16>,

    /// The reply's `valid` value — declared `bool[]`.
    pub valid: Vec<bool>,
}

impl AdioAdc {
    fn parse(r: &Reply) -> Result<Self, Error> {
        Ok(Self {
            slot: uint(r, "slot")?,
            ch: uint(r, "ch")?,
            codes: uints(r, "codes")?,
            valid: flags(r, "valid")?,
        })
    }
}

/// Every published command, typed. Implemented for `Device` below.
pub trait Commands {
    /// Handshake. fw/gw are the firmware and gateware git shas (8 hex) — equal when both came from
    /// one build. The identity REGISTERS carry the same gateware sha pre-boot; the device DNA is
    /// not on this command (it is AXI-side, reachable via the human `kv id`, and on
    /// `sys.challenge`). `tiers` lists the tiers a session of THIS BUILD can reach, comma-joined in
    /// rank order: `public` alone means the build has no unlock and no factory command;
    /// `public,service,factory` means every tier is behind `sys.unlock`. A station tool refuses a
    /// build whose `tiers` lacks `factory` rather than failing midway.
    fn sys_hello(&mut self) -> Result<SysHello, Error>;

    /// The Serial of every Board the device can see on one I2C segment: `main` is the main bus,
    /// `slotN` is module mux channel N. Board-ignorant by design — the device scans 7-bit addresses
    /// 0x50..0x57, reads 64 bytes at register 0 with a 16-bit register address, keeps the blocks
    /// that carry a valid identity record (the internal `board_record` layout), and returns the
    /// Serial string with the address it was found at. A NAK from an EEPROM address is "no Board
    /// there", never an error; a blank EEPROM (all 0xFF or all 0x00) is "no record" and is omitted;
    /// only a stuck bus is reported — and `i2c_nak` can only mean the mux itself (`addr` 0x77)
    /// refused the channel select. One segment per call so at most 8 entries, and the reply always
    /// fits `max_body_bytes`. On a `slot` segment the device holds the mux on that channel for the
    /// transaction and restores what the power sequencer expects. Every other record field is
    /// unreachable below the factory tier.
    fn id_boards(&mut self, seg: SegBoards) -> Result<IdBoards, Error>;

    /// Read the power tree, writing nothing. present = module-present bitmask from the most recent
    /// sequence pass (a raw detect read is NOT equivalent — after a pass those bits are outputs
    /// driving the DCDC enables). reverify = the periodic re-verify thread is enabled.
    fn power_status(&mut self) -> Result<PowerStatus, Error>;

    /// Run the rail sequence. Stim stays off. Level-set: safe to retry.
    fn power_up(&mut self) -> Result<PowerUp, Error>;

    /// Set a slot's two channel modes (I2C mux + CH_MODE, kept coherent).
    fn adio_mode(&mut self, slot: u8, ch1: ChMode, ch2: ChMode) -> Result<AdioMode, Error>;

    /// Cross-channel loopback tie. Independent of either channel's DIRECTION and of CH_MODE, and
    /// re-asserted with the expander, so setting a mode never silently drops a tie. The muxes make
    /// it a SELECT, not a strap: with the tie on, a channel routes to the other channel instead of
    /// to its jack.
    fn adio_fb(&mut self, slot: u8, on: u8) -> Result<AdioFb, Error>;

    /// Drive the digital outputs (bit0 CH1, bit1 CH2) and echo the RAW pad readback, so one call is
    /// both a stimulus and its measurement. A non-zero mask is refused on an absent slot: driving a
    /// pin high there back-powers the module rail. Note the pin only moves if that channel's
    /// CH_MODE is out, and a driven channel reads 0 on its own TTL lane by design -- read the OTHER
    /// channel, through the tie.
    fn adio_dout(&mut self, slot: u8, mask: u8) -> Result<AdioDout, Error>;

    /// n is range-checked, never silently clamped (the human `kv adio adc` clamps). valid\[i\]
    /// mirrors each sample's valid bit — a code with valid=false is meaningless.
    fn adio_adc(&mut self, slot: u8, ch: u8, n: Option<u8>) -> Result<AdioAdc, Error>;
}

impl Commands for Device {
    fn sys_hello(&mut self) -> Result<SysHello, Error> {
        let reply = checked(self.raw_cmd("sys.hello", &[])?)?;
        SysHello::parse(&reply)
    }

    fn id_boards(&mut self, seg: SegBoards) -> Result<IdBoards, Error> {
        let args: Vec<String> = vec![seg.token().to_string()];
        let args: Vec<&str> = args.iter().map(String::as_str).collect();
        let reply = checked(self.raw_cmd("id.boards", &args)?)?;
        IdBoards::parse(&reply)
    }

    fn power_status(&mut self) -> Result<PowerStatus, Error> {
        let reply = checked(self.raw_cmd("power.status", &[])?)?;
        PowerStatus::parse(&reply)
    }

    fn power_up(&mut self) -> Result<PowerUp, Error> {
        let reply = checked(self.raw_cmd("power.up", &[])?)?;
        PowerUp::parse(&reply)
    }

    fn adio_mode(&mut self, slot: u8, ch1: ChMode, ch2: ChMode) -> Result<AdioMode, Error> {
        if slot > 7 {
            return Err(Error::Host(HostErr::HostUnsafeArg));
        }
        let args: Vec<String> = vec![
            slot.to_string(),
            ch1.token().to_string(),
            ch2.token().to_string(),
        ];
        let args: Vec<&str> = args.iter().map(String::as_str).collect();
        let reply = checked(self.raw_cmd("adio.mode", &args)?)?;
        AdioMode::parse(&reply)
    }

    fn adio_fb(&mut self, slot: u8, on: u8) -> Result<AdioFb, Error> {
        if slot > 7 {
            return Err(Error::Host(HostErr::HostUnsafeArg));
        }
        if on > 1 {
            return Err(Error::Host(HostErr::HostUnsafeArg));
        }
        let args: Vec<String> = vec![slot.to_string(), on.to_string()];
        let args: Vec<&str> = args.iter().map(String::as_str).collect();
        let reply = checked(self.raw_cmd("adio.fb", &args)?)?;
        AdioFb::parse(&reply)
    }

    fn adio_dout(&mut self, slot: u8, mask: u8) -> Result<AdioDout, Error> {
        if slot > 7 {
            return Err(Error::Host(HostErr::HostUnsafeArg));
        }
        if mask > 3 {
            return Err(Error::Host(HostErr::HostUnsafeArg));
        }
        let args: Vec<String> = vec![slot.to_string(), mask.to_string()];
        let args: Vec<&str> = args.iter().map(String::as_str).collect();
        let reply = checked(self.raw_cmd("adio.dout", &args)?)?;
        AdioDout::parse(&reply)
    }

    fn adio_adc(&mut self, slot: u8, ch: u8, n: Option<u8>) -> Result<AdioAdc, Error> {
        if slot > 7 {
            return Err(Error::Host(HostErr::HostUnsafeArg));
        }
        if ch > 1 {
            return Err(Error::Host(HostErr::HostUnsafeArg));
        }
        if let Some(n) = n {
            if !(1..=16).contains(&n) {
                return Err(Error::Host(HostErr::HostUnsafeArg));
            }
        }
        let mut args: Vec<String> = vec![slot.to_string(), ch.to_string()];
        if let Some(n) = n {
            args.push(n.to_string());
        }
        let args: Vec<&str> = args.iter().map(String::as_str).collect();
        let reply = checked(self.raw_cmd("adio.adc", &args)?)?;
        AdioAdc::parse(&reply)
    }
}

// Deliberately without typed methods: `sys.claim`, `sys.release`, `sys.challenge`, `sys.unlock`.
// Every one is `scope: session` — OPTIONAL, so a build may legally answer `unknown_cmd` to any of
// them and a host proceeds (kdi/contract.yaml:476-478). A typed method would read as a promise
// every build keeps. Their argument shapes ARE published (the unlock's grant is `tier nonce dna
// sig`, see the contract), and they stay in `COMMANDS` above, so `Device::raw_cmd` drives one
// positionally in the declared order.

// ───────────────────────────────────────────────────────────────────── reply decoding
//
// A missing or ill-typed key is an ERROR, never a default. A device on a NEWER minor may ADD keys
// — that is what makes a minor additive, and nothing here rejects an unknown one — but a reply
// missing a key this contract declares is not from the device this build thinks it is, and
// `unwrap_or_default` would hand the bench a present-mask of 0: "no modules fitted",
// indistinguishable from the truth.

fn bad(key: &str, want: &str) -> Error {
    io_err(
        ErrorKind::InvalidData,
        format!("reply key `{key}` is not {want}"),
    )
}

/// A whole reply and one object inside it (an entry of a list-valued key) are read alike.
trait Fields {
    fn field(&self, key: &str) -> Option<&Value>;
}

impl Fields for Reply {
    fn field(&self, key: &str) -> Option<&Value> {
        self.get(key)
    }
}

impl Fields for Value {
    fn field(&self, key: &str) -> Option<&Value> {
        self.get(key)
    }
}

fn at<'a>(r: &'a impl Fields, key: &str) -> Result<&'a Value, Error> {
    r.field(key).ok_or_else(|| bad(key, "present in the reply"))
}

/// Width-checked, never truncating: the device declares `present` as a u8 and a `v as u8` on a
/// wider value would silently report a different power tree than the one that answered.
fn uint<T: TryFrom<u64>>(r: &impl Fields, key: &str) -> Result<T, Error> {
    let v = at(r, key)?
        .as_u64()
        .ok_or_else(|| bad(key, "an unsigned integer"))?;
    T::try_from(v).map_err(|_| bad(key, "in range for its declared width"))
}

fn flag(r: &impl Fields, key: &str) -> Result<bool, Error> {
    at(r, key)?.as_bool().ok_or_else(|| bad(key, "a bool"))
}

fn text(r: &impl Fields, key: &str) -> Result<String, Error> {
    Ok(at(r, key)?
        .as_str()
        .ok_or_else(|| bad(key, "a string"))?
        .to_string())
}

fn uints<T: TryFrom<u64>>(r: &impl Fields, key: &str) -> Result<Vec<T>, Error> {
    at(r, key)?
        .as_array()
        .ok_or_else(|| bad(key, "an array"))?
        .iter()
        .map(|v| {
            let n = v
                .as_u64()
                .ok_or_else(|| bad(key, "an array of unsigned integers"))?;
            T::try_from(n).map_err(|_| bad(key, "in range for its declared width"))
        })
        .collect()
}

fn flags(r: &impl Fields, key: &str) -> Result<Vec<bool>, Error> {
    at(r, key)?
        .as_array()
        .ok_or_else(|| bad(key, "an array"))?
        .iter()
        .map(|v| v.as_bool().ok_or_else(|| bad(key, "an array of bools")))
        .collect()
}

fn object(r: &impl Fields, key: &str) -> Result<Value, Error> {
    Ok(at(r, key)?.clone())
}

/// A list of records, each parsed by the generated entry type. An element that is not an
/// object is an error for the same reason a missing key is: it is not the declared reply.
fn objects<T>(
    r: &impl Fields,
    key: &str,
    parse: fn(&Value) -> Result<T, Error>,
) -> Result<Vec<T>, Error> {
    at(r, key)?
        .as_array()
        .ok_or_else(|| bad(key, "an array"))?
        .iter()
        .map(|v| {
            if !v.is_object() {
                return Err(bad(key, "an array of objects"));
            }
            parse(v)
        })
        .collect()
}

/// A refusal reaches a TYPED caller as `Err`, while `Device::raw_cmd` still returns it as data
/// (lib.rs:12-15). The difference is what was asked for: `raw_cmd` hands back a `Reply` whose `rc`
/// the caller is obliged to read, but a reply that says `not_present` contains no `AdioAdc`, and
/// parsing one out of the absent keys would invent codes that were never sampled.
fn checked(r: Reply) -> Result<Reply, Error> {
    if r.ok() {
        Ok(r)
    } else {
        Err(Error::Device(r))
    }
}