pub struct Caps(pub u32);Expand description
The device’s capability bitmap, read once at bind. The raw word is public so it can be logged
or compared verbatim; Caps::has and Caps::iter are how it is read.
Tuple Fields§
§0: u32Implementations§
Source§impl Caps
impl Caps
Sourcepub fn has(self, c: Cap) -> bool
pub fn has(self, c: Cap) -> bool
Does this build have that capability? THE ONLY correct feature test — a version comparison is not one, because a minor is additive and says nothing about what a build implements.
Examples found in repository?
examples/usb3_configure.rs (line 41)
10fn main() -> ExitCode {
11 let mut args = std::env::args().skip(1);
12 let Some(bit) = args.next() else {
13 eprintln!("usage: usb3_configure <bit> [serial]");
14 return ExitCode::FAILURE;
15 };
16 let serial = args.next().unwrap_or_default();
17
18 let image = match fs::read(&bit) {
19 Ok(b) => b,
20 Err(e) => {
21 eprintln!("{bit}: {e}");
22 return ExitCode::FAILURE;
23 }
24 };
25
26 let mut dev = match kdi::Device::open_usb3_configured(&serial, &image) {
27 Ok(d) => d,
28 Err(e) => {
29 eprintln!("configure + open failed: {e}");
30 return ExitCode::FAILURE;
31 }
32 };
33
34 let (major, minor) = dev.kdi();
35 let sha = dev.gateware_sha();
36 let caps = dev.caps();
37 println!("serial {}", dev.info().serial);
38 println!("contract {major}.{minor}");
39 println!("gateware_sha {sha:08x}");
40 println!("caps 0x{:08x}", caps.0);
41 if caps.has(kdi::Cap::CommandProtocol) {
42 match dev.sys_hello() {
43 Ok(h) => println!("fw_sha {}", h.fw),
44 Err(e) => {
45 eprintln!("sys.hello failed: {e}");
46 return ExitCode::FAILURE;
47 }
48 }
49 } else {
50 println!("fw_sha -");
51 }
52
53 if let Err(e) = dev.close() {
54 eprintln!("close: {e}");
55 return ExitCode::FAILURE;
56 }
57 println!("configure OK");
58 ExitCode::SUCCESS
59}More examples
examples/usb3_handshake.rs (line 35)
7fn main() -> std::process::ExitCode {
8 let mut args = std::env::args().skip(1);
9 let serial = args.next().unwrap_or_default();
10 let driver_dir = args.next();
11
12 let opened = kdi::Device::open_usb3(&serial, driver_dir.as_deref().map(std::path::Path::new));
13
14 let mut dev = match opened {
15 Ok(d) => d,
16 Err(e) => {
17 // Naming the failure matters more than the exit code: "no board" and "the driver is
18 // present but a symbol did not resolve" are the two outcomes worth telling apart, and
19 // every entry point resolves by name at dlopen so the second one says which symbol.
20 eprintln!("could not open the board: {e}");
21 return std::process::ExitCode::FAILURE;
22 }
23 };
24
25 let (major, minor) = dev.kdi();
26 let caps = dev.caps();
27 println!("serial {}", dev.info().serial);
28 println!("transport {:?}", dev.info().transport);
29 println!("contract {major}.{minor}");
30 println!("caps 0x{:08x}", caps.0);
31 for c in caps.iter() {
32 println!(" {}", c.token());
33 }
34 println!("gateware_sha {:08x}", dev.gateware_sha());
35 if caps.has(kdi::Cap::CommandProtocol) {
36 match dev.sys_hello() {
37 Ok(h) => println!("fw_sha {}", h.fw),
38 Err(e) => {
39 eprintln!("sys.hello failed: {e}");
40 return std::process::ExitCode::FAILURE;
41 }
42 }
43 } else {
44 println!("fw_sha -");
45 }
46
47 match dev.wait_ready(std::time::Duration::from_millis(kdi::READY_TIMEOUT_MS)) {
48 Ok(()) => println!("contract_ready yes"),
49 Err(e) => {
50 // Not fatal for a handshake read: a board still calibrating is a normal transient, and
51 // the point of this program is to report what the device says.
52 println!("contract_ready NO ({e})");
53 }
54 }
55
56 if let Err(e) = dev.close() {
57 eprintln!("close: {e}");
58 return std::process::ExitCode::FAILURE;
59 }
60 std::process::ExitCode::SUCCESS
61}examples/rate_acceptance.rs (line 76)
63fn main() -> ExitCode {
64 let serial = std::env::args().nth(1).unwrap_or_default();
65 let mut dev = match Device::open_usb3(&serial, None) {
66 Ok(d) => d,
67 Err(e) => {
68 eprintln!("open failed: {e}");
69 return ExitCode::FAILURE;
70 }
71 };
72
73 println!("gateware_sha 0x{:08x}", dev.gateware_sha());
74 let (maj, min) = dev.kdi();
75 println!("contract {maj}.{min}");
76 if !dev.caps().has(Cap::RateControl) {
77 eprintln!(
78 "FAIL: this build does not advertise rate_control -- wrong bitstream for this check"
79 );
80 return ExitCode::FAILURE;
81 }
82
83 let mut fails = 0;
84 let mut check = |name: &str, ok: bool, detail: String| {
85 println!(
86 " {:<26} {} {detail}",
87 name,
88 if ok { "ok " } else { "FAIL" }
89 );
90 if !ok {
91 fails += 1;
92 }
93 };
94
95 // 1. UNCONFIGURED EMITS NOTHING. Not "slow frames" -- none.
96 let ready0 = dev.rate_ready().unwrap_or(true);
97 let silent = drain(&mut dev, Stream::Samples, 4, Duration::from_secs(3));
98 match silent {
99 // start() is expected to refuse before it ever reaches the pipe; that IS the check.
100 Err(e) if e.contains("rate is not configured") => check(
101 "unconfigured is silent",
102 !ready0,
103 format!("rate_ready={ready0}, start refused: named set_rate"),
104 ),
105 Ok((v, _)) => check(
106 "unconfigured is silent",
107 !ready0 && v.is_empty(),
108 format!("rate_ready={ready0}, {} frames", v.len()),
109 ),
110 Err(e) => check("unconfigured is silent", false, e),
111 }
112
113 // 2. CONFIGURED IS CORRECT, and the frame's OWN declared cadence is the reference -- never a
114 // host-side constant, which is what let #131 stand for so long.
115 if let Err(e) = dev.set_rate(M, D) {
116 check("set_rate", false, format!("{e}"));
117 } else {
118 let ready1 = dev.rate_ready().unwrap_or(false);
119 match drain(&mut dev, Stream::Samples, 24, Duration::from_secs(10)) {
120 Ok((v, lost)) if v.len() >= 8 => {
121 let declared = f64::from(v[0].1) / f64::from(v[0].2.max(1));
122 let mut gaps: Vec<f64> = v.windows(2).map(|w| (w[1].0 - w[0].0) as f64).collect();
123 gaps.sort_by(|a, b| a.partial_cmp(b).unwrap());
124 let med = gaps[gaps.len() / 2];
125 let ratio = med / declared;
126 check("configured is correct", ready1 && lost == 0 && (ratio - 1.0).abs() < 0.02,
127 format!("rate_ready={ready1}, declared {declared:.1}, observed {med:.1}, ratio {ratio:.3}, lost {lost}"));
128 }
129 Ok((v, _)) => check(
130 "configured is correct",
131 false,
132 format!("only {} frames", v.len()),
133 ),
134 Err(e) => check("configured is correct", false, e),
135 }
136 }
137
138 // 3. THE PUBLISHED CADENCE IS THE MEASURED ONE, ACROSS THE TABLE. Judged against the cadence
139 // THAT FRAME DECLARES, never a host-side constant: a constant is what let #131 stand, with
140 // device and host agreeing and both wrong. This check would have caught it on day one.
141 for (m, d, label) in [
142 (7u8, 125u8, "1 kS/s"),
143 (14, 25, "10 kS/s"),
144 (42, 25, "30 kS/s"),
145 ] {
146 if let Err(e) = dev.set_rate(m, d) {
147 check("sweep", false, format!("{label}: set_rate: {e}"));
148 continue;
149 }
150 match drain(&mut dev, Stream::Samples, 16, Duration::from_secs(20)) {
151 Ok((v, lost)) if v.len() >= 8 => {
152 let declared = f64::from(v[0].1) / f64::from(v[0].2.max(1));
153 let mut gaps: Vec<f64> = v.windows(2).map(|w| (w[1].0 - w[0].0) as f64).collect();
154 gaps.sort_by(|a, b| a.partial_cmp(b).unwrap());
155 let med = gaps[gaps.len() / 2];
156 let ratio = med / declared;
157 check(
158 &format!("sweep {label}"),
159 lost == 0 && (ratio - 1.0).abs() < 0.02,
160 format!(
161 "declared {declared:.1}, observed {med:.1}, ratio {ratio:.3}, lost {lost}"
162 ),
163 );
164 }
165 Ok((v, _)) => check(
166 &format!("sweep {label}"),
167 false,
168 format!("only {} frames", v.len()),
169 ),
170 Err(e) => check(&format!("sweep {label}"), false, e),
171 }
172 }
173
174 // 4. QUIESCE RETURNS TO UNCONFIGURED, and check 1 must hold again.
175 if let Err(e) = dev.quiesce() {
176 check("quiesce unconfigures", false, format!("{e}"));
177 } else {
178 let ready2 = dev.rate_ready().unwrap_or(true);
179 check(
180 "quiesce unconfigures",
181 !ready2,
182 format!("rate_ready={ready2}"),
183 );
184 }
185
186 // 5. THE DIGITAL STREAM IS UNTOUCHED by any of it -- it is self-clocked and was correct
187 // throughout #131, so a change that disturbs it is a regression in the fix.
188 match drain(&mut dev, Stream::Digital, 8, Duration::from_secs(5)) {
189 Ok((v, _)) if v.len() >= 4 => {
190 let declared = f64::from(v[0].1) / f64::from(v[0].2.max(1));
191 let mut gaps: Vec<f64> = v.windows(2).map(|w| (w[1].0 - w[0].0) as f64).collect();
192 gaps.sort_by(|a, b| a.partial_cmp(b).unwrap());
193 let med = gaps[gaps.len() / 2];
194 check(
195 "digital unaffected",
196 (med / declared - 1.0).abs() < 0.05,
197 format!(
198 "{} frames, declared {declared:.1}, observed {med:.1}",
199 v.len()
200 ),
201 );
202 }
203 Ok((v, _)) => check(
204 "digital unaffected",
205 false,
206 format!("only {} frames", v.len()),
207 ),
208 Err(e) => check("digital unaffected", false, e),
209 }
210
211 let _ = dev.quiesce();
212 println!("\nRESULT: {}", if fails == 0 { "PASS" } else { "FAIL" });
213 if fails == 0 {
214 ExitCode::SUCCESS
215 } else {
216 ExitCode::FAILURE
217 }
218}Sourcepub fn iter(self) -> impl Iterator<Item = Cap>
pub fn iter(self) -> impl Iterator<Item = Cap>
Every capability the device reported, in bit order. For logging what a board can do; a
decision about ONE feature is Caps::has.
Examples found in repository?
examples/usb3_handshake.rs (line 31)
7fn main() -> std::process::ExitCode {
8 let mut args = std::env::args().skip(1);
9 let serial = args.next().unwrap_or_default();
10 let driver_dir = args.next();
11
12 let opened = kdi::Device::open_usb3(&serial, driver_dir.as_deref().map(std::path::Path::new));
13
14 let mut dev = match opened {
15 Ok(d) => d,
16 Err(e) => {
17 // Naming the failure matters more than the exit code: "no board" and "the driver is
18 // present but a symbol did not resolve" are the two outcomes worth telling apart, and
19 // every entry point resolves by name at dlopen so the second one says which symbol.
20 eprintln!("could not open the board: {e}");
21 return std::process::ExitCode::FAILURE;
22 }
23 };
24
25 let (major, minor) = dev.kdi();
26 let caps = dev.caps();
27 println!("serial {}", dev.info().serial);
28 println!("transport {:?}", dev.info().transport);
29 println!("contract {major}.{minor}");
30 println!("caps 0x{:08x}", caps.0);
31 for c in caps.iter() {
32 println!(" {}", c.token());
33 }
34 println!("gateware_sha {:08x}", dev.gateware_sha());
35 if caps.has(kdi::Cap::CommandProtocol) {
36 match dev.sys_hello() {
37 Ok(h) => println!("fw_sha {}", h.fw),
38 Err(e) => {
39 eprintln!("sys.hello failed: {e}");
40 return std::process::ExitCode::FAILURE;
41 }
42 }
43 } else {
44 println!("fw_sha -");
45 }
46
47 match dev.wait_ready(std::time::Duration::from_millis(kdi::READY_TIMEOUT_MS)) {
48 Ok(()) => println!("contract_ready yes"),
49 Err(e) => {
50 // Not fatal for a handshake read: a board still calibrating is a normal transient, and
51 // the point of this program is to report what the device says.
52 println!("contract_ready NO ({e})");
53 }
54 }
55
56 if let Err(e) = dev.close() {
57 eprintln!("close: {e}");
58 return std::process::ExitCode::FAILURE;
59 }
60 std::process::ExitCode::SUCCESS
61}More examples
examples/control.rs (line 39)
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}Trait Implementations§
impl Copy for Caps
impl Eq for Caps
impl StructuralPartialEq for Caps
Auto Trait Implementations§
impl Freeze for Caps
impl RefUnwindSafe for Caps
impl Send for Caps
impl Sync for Caps
impl Unpin for Caps
impl UnsafeUnpin for Caps
impl UnwindSafe for Caps
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more