Skip to main content

control/
control.rs

1//! Bind a device, read its capabilities, drive the typed command channel. NO HARDWARE NEEDED:
2//! same setup as `stream.rs`, then `cargo run --example control [SERIAL]` (no serial = first
3//! device). Every command here is read-only or refused; never powers a rail or drives a pin.
4
5use kdi::{Cap, ChMode, Commands, ConnectOpts, Device, DeviceErr, Error, Filter};
6
7fn main() -> Result<(), Error> {
8    let filter = Filter {
9        serial: std::env::args().nth(1),
10        ..Filter::default()
11    };
12    let (found, errs) = kdi::find(&filter);
13    for e in &errs {
14        eprintln!("enumeration error: {e}");
15    }
16    let Some(info) = found.first() else {
17        eprintln!("no device found - connect an instrument and build with --features usb3");
18        return Ok(());
19    };
20
21    // Refuse the bind up front if the device cannot do what this program needs. A CAPABILITY, not
22    // a version comparison: a KDI minor is additive, so a version says nothing about what a build
23    // actually implements.
24    let mut dev = Device::open(
25        info,
26        &ConnectOpts {
27            need_caps: vec![Cap::CommandProtocol],
28            ..ConnectOpts::default()
29        },
30    )?;
31
32    let (major, minor) = dev.kdi();
33    println!(
34        "{}  contract {major}.{minor}  gateware {:08x}  lease {:?}",
35        info.serial,
36        dev.gateware_sha(),
37        dev.lease(),
38    );
39    let caps: Vec<&str> = dev.caps().iter().map(Cap::token).collect();
40    println!("caps: {}", caps.join(", "));
41
42    // ── typed commands: the reply is a struct, and a missing key is an error rather than a zero ──
43    let hello = dev.sys_hello()?;
44    println!(
45        "sys.hello: proto {} cmdset {} kdi {} board 0x{:x} fw {} gw {}",
46        hello.proto, hello.cmdset, hello.kdi, hello.board_id, hello.fw, hello.gw,
47    );
48
49    let power = dev.power_status()?;
50    println!(
51        "power.status: present 0x{:02x} reverify {}",
52        power.present, power.reverify,
53    );
54
55    // `valid` is a HARDWARE flag (bit 16 of the sample register), and `false` here is expected: a
56    // conversion only completes in `adc` mode, and this program will not set a mode on a populated
57    // slot. Measured on silicon, slot 0 seated: `codes [0, 0] valid [false, false]`.
58    if let Some(slot) = (0..8).find(|s| power.present >> s & 1 != 0) {
59        let adc = dev.adio_adc(slot, 0, Some(2))?;
60        println!(
61            "adio.adc slot {} ch {}: codes {:?} valid {:?}",
62            adc.slot, adc.ch, adc.codes, adc.valid,
63        );
64    }
65
66    // THE MODE MATTERS: the firmware gates on DRIVING modes, so `out`/`dac` on an empty slot is
67    // refused `not_present` while `Off` is allowed and proves nothing
68    // (sw/zephyr/app/console/src/kdi_ctl.c:264-264). Safe: gated on the present-mask above.
69    if let Some(empty) = (0..8).find(|s| power.present >> s & 1 == 0) {
70        match dev.adio_mode(empty, ChMode::Out, ChMode::Off) {
71            // Reaching here means the safety gate did NOT fire and a drive was configured on a
72            // slot the power tree calls empty. Say so; a success is the alarming outcome.
73            Ok(m) => println!(
74                "adio.mode slot {}: NOT REFUSED, ch_mode 0x{:04x} - the not_present gate did not \
75                 fire for a driving mode",
76                m.slot, m.ch_mode
77            ),
78            Err(Error::Device(r)) => {
79                let err = r.err;
80                println!(
81                    "adio.mode slot {empty} refused: {} (rc {}, retryable {})",
82                    err.map_or("?", DeviceErr::token),
83                    r.rc,
84                    err.is_some_and(DeviceErr::retryable),
85                );
86            }
87            Err(e) => return Err(e),
88        }
89    }
90
91    // A range the contract declares is checked HOST-SIDE: `n` is 1..=16, so this never reaches the
92    // wire and costs no round trip to learn.
93    match dev.adio_adc(0, 0, Some(99)) {
94        Err(Error::Host(h)) => println!("adio.adc n=99 refused before the wire: {}", h.token()),
95        other => println!("expected a host-side refusal, got {other:?}"),
96    }
97
98    dev.close()
99}