viva_u3v/bootstrap.rs
1//! USB3 Vision bootstrap register maps.
2//!
3//! The device exposes a hierarchy of register maps that describe its
4//! capabilities and provide addresses for higher-level structures:
5//!
6//! ```text
7//! ABRM (addr 0x0000, GenCP standard)
8//! ├─ manufacturer / model / serial strings
9//! ├─ Manifest Table address → GenICam XML location
10//! └─ SBRM address → USB3 Vision registers
11//! ├─ max transfer sizes
12//! ├─ SIRM address → streaming config
13//! └─ EIRM address → event config
14//! ```
15//!
16//! Every bootstrap register is **little-endian**: GenCP requires the
17//! bootstrap registers to share the protocol's byte order (GenCP 1.2 §2.3),
18//! which for USB3 Vision is little-endian (see [`crate::control`]). Where the
19//! layouts come from, strongest evidence first:
20//!
21//! - **ABRM**: GenCP 1.2, Table 15, with the capability bits of Table 17 and
22//! the manifest of Tables 29-30.
23//! - **SBRM**: the USB3 Vision standard, which is not freely available. A
24//! Grasshopper3's own XML maps U3VCP capability (+0x04), max command and
25//! acknowledge transfer (+0x14, +0x18) and stream channel count (+0x1C),
26//! all `LittleEndian` (`PGR_GS3_U3_23S6M.xml`); aravis (`arvuvcpprivate.h`)
27//! and Wireshark (`packet-u3v.c`) agree on those and add the SIRM and EIRM
28//! addresses.
29//! - **SIRM**: aravis and Wireshark, which agree with each other.
30//! - **EIRM**: Wireshark (`packet-u3v.c` names its three registers); aravis
31//! reads only its address.
32//! - **Current speed** (SBRM +0x40): the Grasshopper3's XML maps it, and its
33//! formula reads the bits (8 SuperSpeed, 4 HighSpeed, 2 FullSpeed);
34//! Wireshark names the register.
35//!
36//! Until backlog TC-27 this module read every register big-endian at offsets
37//! of its own; no USB3 Vision camera had been reported against it.
38
39use crate::U3vError;
40use crate::control::ControlChannel;
41use crate::stream::StreamLayout;
42use crate::usb::UsbTransfer;
43
44// ---------------------------------------------------------------------------
45// ABRM — Technology Agnostic Bootstrap Register Map (GenCP standard, at 0)
46// ---------------------------------------------------------------------------
47
48/// ABRM register offsets (GenCP 1.2, Table 15).
49pub mod abrm {
50 /// `u32`: major version in the upper 16 bits, minor in the lower.
51 pub const GENCP_VERSION: u64 = 0x0000;
52 /// 64-byte string.
53 pub const MANUFACTURER_NAME: u64 = 0x0004;
54 /// 64-byte string.
55 pub const MODEL_NAME: u64 = 0x0044;
56 /// 64-byte string; present when [`capability::FAMILY_NAME`](super::capability::FAMILY_NAME) is set.
57 pub const FAMILY_NAME: u64 = 0x0084;
58 /// 64-byte string.
59 pub const DEVICE_VERSION: u64 = 0x00C4;
60 /// 64-byte string.
61 pub const MANUFACTURER_INFO: u64 = 0x0104;
62 /// 64-byte string.
63 pub const SERIAL_NUMBER: u64 = 0x0144;
64 /// 64-byte string; present when [`capability::USER_DEFINED_NAME`](super::capability::USER_DEFINED_NAME) is set.
65 pub const USER_DEFINED_NAME: u64 = 0x0184;
66 /// `u64` bit field, [`capability`](super::capability).
67 pub const DEVICE_CAPABILITY: u64 = 0x01C4;
68 /// `u32`, milliseconds.
69 pub const MAX_DEVICE_RESPONSE_TIME: u64 = 0x01CC;
70 /// `u64`.
71 pub const MANIFEST_TABLE_ADDRESS: u64 = 0x01D0;
72 /// `u64`; present when [`capability::SBRM`](super::capability::SBRM) is set.
73 pub const SBRM_ADDRESS: u64 = 0x01D8;
74 /// `u64` bit field.
75 pub const DEVICE_CONFIGURATION: u64 = 0x01E0;
76 /// `u32`, milliseconds.
77 pub const HEARTBEAT_TIMEOUT: u64 = 0x01E8;
78 /// `u32`: the id of the device's message channel (GenCP 1.2 Table 15).
79 pub const MESSAGE_CHANNEL_ID: u64 = 0x01EC;
80 /// `u64`, read-only: the device time, in ns, as last latched; present
81 /// when [`capability::TIMESTAMP`](super::capability::TIMESTAMP) is set
82 /// (GenCP 1.3.1 §5.4.16).
83 pub const TIMESTAMP: u64 = 0x01F0;
84 /// `u32`, write-only: writing bit 0 latches the device time into
85 /// [`TIMESTAMP`] (GenCP 1.3.1 §5.4.17).
86 pub const TIMESTAMP_LATCH: u64 = 0x01F8;
87 /// `u64`, read-only: nanoseconds per tick of the device clock (GenCP
88 /// 1.3.1 §5.4.18).
89 pub const TIMESTAMP_INCREMENT: u64 = 0x01FC;
90 /// `u32`.
91 pub const ACCESS_PRIVILEGE: u64 = 0x0204;
92 /// `u32`: 0 big-endian, `0xFFFF_FFFF` little-endian, for the device's own
93 /// registers; present when [`capability::ENDIANNESS_REGISTER`](super::capability::ENDIANNESS_REGISTER) is set.
94 pub const IMPLEMENTATION_ENDIANNESS: u64 = 0x020C;
95 /// Bytes from the start of the ABRM to the reserved space.
96 pub const LEN: u64 = 0x0210;
97 /// Length of every string register.
98 pub const STRING_LEN: usize = 64;
99}
100
101/// Device Capability bits (GenCP 1.2, Table 17).
102pub mod capability {
103 /// The User Defined Name register exists.
104 pub const USER_DEFINED_NAME: u64 = 1 << 0;
105 /// Heartbeat and Access Privilege are supported.
106 pub const ACCESS_PRIVILEGE: u64 = 1 << 1;
107 /// The device has a message channel.
108 pub const MESSAGE_CHANNEL: u64 = 1 << 2;
109 /// The device has a timestamp register.
110 pub const TIMESTAMP: u64 = 1 << 3;
111 /// Bits 4-7: the bootstrap strings' encoding, 0 ASCII, 1 UTF-8, 2 UTF-16.
112 pub const STRING_ENCODING_SHIFT: u32 = 4;
113 /// The Family Name register exists.
114 pub const FAMILY_NAME: u64 = 1 << 8;
115 /// The device has an SBRM.
116 pub const SBRM: u64 = 1 << 9;
117 /// The Implementation Endianness register exists.
118 pub const ENDIANNESS_REGISTER: u64 = 1 << 10;
119 /// A WRITEMEM_ACK says how many bytes were written.
120 pub const WRITTEN_LENGTH: u64 = 1 << 11;
121}
122
123/// Technology Agnostic Bootstrap Register Map — GenCP's registers at address 0.
124#[derive(Debug, Clone)]
125pub struct Abrm {
126 /// Major version in the upper 16 bits, minor in the lower.
127 pub gencp_version: u32,
128 /// Manufacturer name.
129 pub manufacturer_name: String,
130 /// Model name.
131 pub model_name: String,
132 /// Empty when the device has no Family Name register.
133 pub family_name: String,
134 /// Device version.
135 pub device_version: String,
136 /// Manufacturer-specific information.
137 pub manufacturer_info: String,
138 /// Serial number.
139 pub serial_number: String,
140 /// Empty when the device has no User Defined Name register.
141 pub user_defined_name: String,
142 /// [`capability`] bits.
143 pub device_capability: u64,
144 /// How long the device may take to execute a command, not counting the
145 /// transfers, in milliseconds.
146 pub max_device_response_time_ms: u32,
147 /// Where the manifest table is.
148 pub manifest_table_address: u64,
149 /// Where the SBRM is.
150 pub sbrm_address: u64,
151}
152
153impl Abrm {
154 /// Read the ABRM from the device.
155 ///
156 /// The GenCP version is read first, as GenCP recommends for the first
157 /// command of a session (§3.1); conditional registers are read only when
158 /// the Device Capability register says they exist, since a device answers
159 /// a missing one with `GENCP_INVALID_ADDRESS` (§5.3).
160 pub fn read_from<T: UsbTransfer>(control: &mut ControlChannel<T>) -> Result<Self, U3vError> {
161 let gencp_version = read_u32(control, abrm::GENCP_VERSION)?;
162 let device_capability = read_u64(control, abrm::DEVICE_CAPABILITY)?;
163 let encoding = StringEncoding::from_capability(device_capability);
164 let read_string =
165 |control: &mut ControlChannel<T>, addr: u64| -> Result<String, U3vError> {
166 let raw = control.read_mem(addr, abrm::STRING_LEN)?;
167 Ok(encoding.decode(&raw))
168 };
169 let read_optional_string =
170 |control: &mut ControlChannel<T>, bit: u64, addr: u64| -> Result<String, U3vError> {
171 if device_capability & bit == 0 {
172 return Ok(String::new());
173 }
174 read_string(control, addr)
175 };
176
177 Ok(Self {
178 gencp_version,
179 manufacturer_name: read_string(control, abrm::MANUFACTURER_NAME)?,
180 model_name: read_string(control, abrm::MODEL_NAME)?,
181 family_name: read_optional_string(control, capability::FAMILY_NAME, abrm::FAMILY_NAME)?,
182 device_version: read_string(control, abrm::DEVICE_VERSION)?,
183 manufacturer_info: read_string(control, abrm::MANUFACTURER_INFO)?,
184 serial_number: read_string(control, abrm::SERIAL_NUMBER)?,
185 user_defined_name: read_optional_string(
186 control,
187 capability::USER_DEFINED_NAME,
188 abrm::USER_DEFINED_NAME,
189 )?,
190 device_capability,
191 max_device_response_time_ms: read_u32(control, abrm::MAX_DEVICE_RESPONSE_TIME)?,
192 manifest_table_address: read_u64(control, abrm::MANIFEST_TABLE_ADDRESS)?,
193 // Conditional in GenCP, but a USB3 Vision device without one has
194 // no stream and no transfer limits; aravis reads it regardless.
195 sbrm_address: read_u64(control, abrm::SBRM_ADDRESS)?,
196 })
197 }
198}
199
200/// How the bootstrap strings are encoded (Device Capability bits 4-7).
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202enum StringEncoding {
203 Ascii,
204 Utf8,
205 Utf16,
206}
207
208impl StringEncoding {
209 fn from_capability(capability: u64) -> Self {
210 match (capability >> capability::STRING_ENCODING_SHIFT) & 0xF {
211 1 => Self::Utf8,
212 2 => Self::Utf16,
213 // 0 is ASCII; reserved values are read as the most common case.
214 _ => Self::Ascii,
215 }
216 }
217
218 /// Decode a string register: unused bytes are 0, and a full register may
219 /// omit the terminator (GenCP 1.2 §5.2). UTF-16 code units follow the
220 /// bootstrap byte order, little-endian.
221 fn decode(self, raw: &[u8]) -> String {
222 match self {
223 Self::Ascii | Self::Utf8 => parse_nul_string(raw),
224 Self::Utf16 => {
225 let units: Vec<u16> = raw
226 .as_chunks::<2>()
227 .0
228 .iter()
229 .map(|&pair| u16::from_le_bytes(pair))
230 .take_while(|&unit| unit != 0)
231 .collect();
232 String::from_utf16_lossy(&units)
233 }
234 }
235 }
236}
237
238// ---------------------------------------------------------------------------
239// SBRM — USB3 Vision (technology-specific) Bootstrap Register Map
240// ---------------------------------------------------------------------------
241
242/// SBRM register offsets from the SBRM base address.
243pub mod sbrm {
244 /// `u32`: major version in the upper 16 bits, minor in the lower.
245 pub const U3V_VERSION: u64 = 0x0000;
246 /// `u64` bit field, [`u3vcp_capability`](super::u3vcp_capability).
247 pub const U3VCP_CAPABILITY: u64 = 0x0004;
248 /// `u64` bit field.
249 pub const U3VCP_CONFIGURATION: u64 = 0x000C;
250 /// `u32`, bytes.
251 pub const MAX_CMD_TRANSFER: u64 = 0x0014;
252 /// `u32`, bytes.
253 pub const MAX_ACK_TRANSFER: u64 = 0x0018;
254 /// `u32`.
255 pub const NUM_STREAM_CHANNELS: u64 = 0x001C;
256 /// `u64`.
257 pub const SIRM_ADDRESS: u64 = 0x0020;
258 /// `u32`, bytes.
259 pub const SIRM_LENGTH: u64 = 0x0028;
260 /// `u64`.
261 pub const EIRM_ADDRESS: u64 = 0x002C;
262 /// `u32`, bytes.
263 pub const EIRM_LENGTH: u64 = 0x0034;
264 /// `u64`.
265 pub const IIDC2_ADDRESS: u64 = 0x0038;
266 /// `u32`: the bus speed the device runs at.
267 pub const CURRENT_SPEED: u64 = 0x0040;
268 /// Bytes from the SBRM base to its reserved space.
269 pub const LEN: u64 = 0x0044;
270}
271
272/// U3VCP Capability bits, as the Grasshopper3 XML maps them
273/// (`U3VCPSIRMAvailable` bit 0, `U3VCPEIRMAvailable` bit 1,
274/// `U3VCPIIDC2Available` bit 2).
275pub mod u3vcp_capability {
276 /// The device has a SIRM.
277 pub const SIRM_AVAILABLE: u64 = 1 << 0;
278 /// The device has an EIRM.
279 pub const EIRM_AVAILABLE: u64 = 1 << 1;
280 /// The device has an IIDC2 register map.
281 pub const IIDC2_AVAILABLE: u64 = 1 << 2;
282}
283
284/// The bus speed a device runs at: the SBRM's current speed register, as
285/// the Grasshopper3's XML decodes it, or the speed the host reports.
286#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
287#[non_exhaustive]
288pub enum UsbSpeed {
289 /// USB 1 low speed, 1.5 Mbit/s.
290 Low,
291 /// USB 1 full speed, 12 Mbit/s.
292 Full,
293 /// USB 2 high speed, 480 Mbit/s.
294 High,
295 /// USB 3 SuperSpeed, 5 Gbit/s.
296 Super,
297 /// USB 3 SuperSpeed+, 10 Gbit/s or more.
298 SuperPlus,
299}
300
301impl UsbSpeed {
302 /// The speed the SBRM's current speed register reports: one bit set,
303 /// bit 3 SuperSpeed, bit 2 high, bit 1 full, bit 0 low — the bits the
304 /// Grasshopper3's XML tests (`CurrentSpeed_Int`). Bit 4 is read as
305 /// SuperSpeed+, by analogy; no document in the corpus shows it. `None`
306 /// for 0, a device that does not say.
307 pub fn from_register(bits: u32) -> Option<Self> {
308 match bits {
309 0 => None,
310 b if b & (1 << 4) != 0 => Some(Self::SuperPlus),
311 b if b & (1 << 3) != 0 => Some(Self::Super),
312 b if b & (1 << 2) != 0 => Some(Self::High),
313 b if b & (1 << 1) != 0 => Some(Self::Full),
314 _ => Some(Self::Low),
315 }
316 }
317
318 /// Whether this is a USB 2 speed or slower: a USB3 Vision camera on such
319 /// a link runs at a fraction of its bandwidth, if at all — a USB 2 port
320 /// or cable, or a hub between.
321 pub fn is_below_superspeed(self) -> bool {
322 self < Self::Super
323 }
324}
325
326impl std::fmt::Display for UsbSpeed {
327 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328 f.write_str(match self {
329 Self::Low => "low speed (1.5 Mbit/s)",
330 Self::Full => "full speed (12 Mbit/s)",
331 Self::High => "high speed (480 Mbit/s, USB 2)",
332 Self::Super => "SuperSpeed (5 Gbit/s)",
333 Self::SuperPlus => "SuperSpeed+ (10 Gbit/s)",
334 })
335 }
336}
337
338/// USB3 Vision's technology-specific Bootstrap Register Map.
339#[derive(Debug, Clone)]
340pub struct Sbrm {
341 /// Where the SBRM is.
342 pub base: u64,
343 /// Major version in the upper 16 bits, minor in the lower.
344 pub u3v_version: u32,
345 /// [`u3vcp_capability`] bits.
346 pub u3vcp_capability: u64,
347 /// Largest command transfer the device accepts, in bytes.
348 pub max_cmd_transfer: u32,
349 /// Largest acknowledge transfer it sends, in bytes.
350 pub max_ack_transfer: u32,
351 /// Number of stream channels.
352 pub num_stream_channels: u32,
353 /// 0 when the device has no SIRM.
354 pub sirm_address: u64,
355 /// Length of the SIRM in bytes.
356 pub sirm_length: u32,
357 /// 0 when the device has no EIRM.
358 pub eirm_address: u64,
359 /// Length of the EIRM in bytes.
360 pub eirm_length: u32,
361 /// The bus speed the device says it runs at; `None` when it does not
362 /// say, or refuses the register.
363 pub current_speed: Option<UsbSpeed>,
364}
365
366impl Sbrm {
367 /// Read the SBRM from the device at the given base address (from ABRM).
368 ///
369 /// The SIRM and EIRM registers are read whatever the capability bits
370 /// say, as aravis does, and a refusal reads as "absent": a device whose
371 /// bit and register disagree still streams.
372 pub fn read_from<T: UsbTransfer>(
373 control: &mut ControlChannel<T>,
374 base: u64,
375 ) -> Result<Self, U3vError> {
376 let u3vcp_capability = read_u64(control, base + sbrm::U3VCP_CAPABILITY)?;
377 let optional_u64 = |control: &mut ControlChannel<T>, offset: u64| {
378 or_absent(read_u64(control, base + offset))
379 };
380 let optional_u32 = |control: &mut ControlChannel<T>, offset: u64| {
381 or_absent(read_u32(control, base + offset))
382 };
383 Ok(Self {
384 base,
385 u3v_version: read_u32(control, base + sbrm::U3V_VERSION)?,
386 u3vcp_capability,
387 max_cmd_transfer: read_u32(control, base + sbrm::MAX_CMD_TRANSFER)?,
388 max_ack_transfer: read_u32(control, base + sbrm::MAX_ACK_TRANSFER)?,
389 num_stream_channels: read_u32(control, base + sbrm::NUM_STREAM_CHANNELS)?,
390 sirm_address: optional_u64(control, sbrm::SIRM_ADDRESS)?,
391 sirm_length: optional_u32(control, sbrm::SIRM_LENGTH)?,
392 eirm_address: optional_u64(control, sbrm::EIRM_ADDRESS)?,
393 eirm_length: optional_u32(control, sbrm::EIRM_LENGTH)?,
394 current_speed: UsbSpeed::from_register(optional_u32(control, sbrm::CURRENT_SPEED)?),
395 })
396 }
397}
398
399/// A register the device refuses to read is absent, read as 0; a transport
400/// failure is still a failure.
401fn or_absent<V: Default>(read: Result<V, U3vError>) -> Result<V, U3vError> {
402 match read {
403 Err(U3vError::Status(status)) => {
404 tracing::debug!(
405 %status,
406 "optional bootstrap register refused; reading as absent"
407 );
408 Ok(V::default())
409 }
410 other => other,
411 }
412}
413
414// ---------------------------------------------------------------------------
415// SIRM — Streaming Interface Register Map
416// ---------------------------------------------------------------------------
417
418/// SIRM register offsets from the SIRM base address.
419///
420/// The device fills in Info and the three *required* sizes; the host writes
421/// the transfer layout and Control.
422pub mod sirm {
423 /// `u32`: bits 24-31 are the log2 of the transfer alignment.
424 pub const INFO: u64 = 0x0000;
425 /// `u32`: bit 0 is StreamEnable.
426 pub const CONTROL: u64 = 0x0004;
427 /// `u64`, read-only: bytes of payload in one block.
428 pub const REQUIRED_PAYLOAD_SIZE: u64 = 0x0008;
429 /// `u32`, read-only: bytes the leader needs.
430 pub const REQUIRED_LEADER_SIZE: u64 = 0x0010;
431 /// `u32`, read-only: bytes the trailer needs.
432 pub const REQUIRED_TRAILER_SIZE: u64 = 0x0014;
433 /// `u32`, written by the host: the leader transfer's size.
434 pub const MAX_LEADER_SIZE: u64 = 0x0018;
435 /// `u32`, written by the host: each payload transfer's size.
436 pub const PAYLOAD_TRANSFER_SIZE: u64 = 0x001C;
437 /// `u32`, written by the host: how many payload transfers of that size.
438 pub const PAYLOAD_TRANSFER_COUNT: u64 = 0x0020;
439 /// `u32`, written by the host: the first final transfer's size.
440 pub const FINAL_TRANSFER1_SIZE: u64 = 0x0024;
441 /// `u32`, written by the host: the second final transfer's size.
442 pub const FINAL_TRANSFER2_SIZE: u64 = 0x0028;
443 /// `u32`, written by the host: the trailer transfer's size.
444 pub const MAX_TRAILER_SIZE: u64 = 0x002C;
445 /// Bytes in the SIRM.
446 pub const LEN: u64 = 0x0030;
447 /// Control's StreamEnable bit.
448 pub const STREAM_ENABLE: u32 = 1 << 0;
449}
450
451/// What the device says about one stream channel.
452#[derive(Debug, Clone)]
453pub struct Sirm {
454 /// Where the SIRM is.
455 pub base: u64,
456 /// `SI Info`: the transfer alignment, as a power of two in bits 24-31.
457 pub info: u32,
458 /// `SI Control`: bit 0 enables streaming.
459 pub control: u32,
460 /// `Required Payload Size`: bytes a block's payload takes.
461 pub required_payload_size: u64,
462 /// `Required Leader Size`.
463 pub required_leader_size: u32,
464 /// `Required Trailer Size`.
465 pub required_trailer_size: u32,
466}
467
468impl Sirm {
469 /// Read the device's half of the SIRM at the given base address (from
470 /// SBRM).
471 pub fn read_from<T: UsbTransfer>(
472 control: &mut ControlChannel<T>,
473 base: u64,
474 ) -> Result<Self, U3vError> {
475 Ok(Self {
476 base,
477 info: read_u32(control, base + sirm::INFO)?,
478 control: read_u32(control, base + sirm::CONTROL)?,
479 required_payload_size: read_u64(control, base + sirm::REQUIRED_PAYLOAD_SIZE)?,
480 required_leader_size: read_u32(control, base + sirm::REQUIRED_LEADER_SIZE)?,
481 required_trailer_size: read_u32(control, base + sirm::REQUIRED_TRAILER_SIZE)?,
482 })
483 }
484
485 /// The alignment every transfer size must keep, from Info bits 24-31.
486 pub fn alignment(&self) -> Result<u32, U3vError> {
487 let exponent = self.info >> 24;
488 1u32.checked_shl(exponent)
489 .ok_or_else(|| U3vError::Device("asks for a transfer alignment beyond 2^31 bytes"))
490 }
491
492 /// Write the transfer layout the host will read with. The required sizes
493 /// are the device's and are never written: they are read-only, and a
494 /// device refuses the write (Codex review of #181).
495 pub fn configure<T: UsbTransfer>(
496 &self,
497 control: &mut ControlChannel<T>,
498 layout: &StreamLayout,
499 ) -> Result<(), U3vError> {
500 for (offset, value) in [
501 (sirm::MAX_LEADER_SIZE, layout.leader_size),
502 (sirm::MAX_TRAILER_SIZE, layout.trailer_size),
503 (sirm::PAYLOAD_TRANSFER_SIZE, layout.payload_transfer_size),
504 (sirm::PAYLOAD_TRANSFER_COUNT, layout.payload_transfer_count),
505 (sirm::FINAL_TRANSFER1_SIZE, layout.final_transfer1_size),
506 (sirm::FINAL_TRANSFER2_SIZE, layout.final_transfer2_size),
507 ] {
508 control.write_mem(self.base + offset, &value.to_le_bytes())?;
509 }
510 Ok(())
511 }
512
513 /// Set StreamEnable.
514 pub fn enable<T: UsbTransfer>(&self, control: &mut ControlChannel<T>) -> Result<(), U3vError> {
515 control.write_mem(
516 self.base + sirm::CONTROL,
517 &sirm::STREAM_ENABLE.to_le_bytes(),
518 )
519 }
520
521 /// Clear StreamEnable.
522 pub fn disable<T: UsbTransfer>(&self, control: &mut ControlChannel<T>) -> Result<(), U3vError> {
523 control.write_mem(self.base + sirm::CONTROL, &0u32.to_le_bytes())
524 }
525}
526
527// ---------------------------------------------------------------------------
528// EIRM — Event Interface Register Map
529// ---------------------------------------------------------------------------
530
531/// EIRM register offsets from the EIRM base address, as Wireshark names them
532/// (`packet-u3v.c`: `EI_Control`, `Maximum_Event_Transfer_Length`,
533/// `Event_Test_Control`); the USB3 Vision standard is not freely available.
534pub mod eirm {
535 /// `u32`: bit 0 is EventEnable.
536 pub const CONTROL: u64 = 0x0000;
537 /// `u32`, read-only: the longest event transfer the device sends.
538 pub const MAXIMUM_EVENT_TRANSFER_LENGTH: u64 = 0x0004;
539 /// `u32`: event test control.
540 pub const EVENT_TEST_CONTROL: u64 = 0x0008;
541 /// Control's EventEnable bit.
542 pub const EVENT_ENABLE: u32 = 1 << 0;
543}
544
545/// What the device says about its event interface.
546#[derive(Debug, Clone)]
547pub struct Eirm {
548 /// Where the EIRM is.
549 pub base: u64,
550 /// The longest event transfer the device sends, in bytes.
551 pub maximum_event_transfer_length: u32,
552}
553
554impl Eirm {
555 /// Read the EIRM at the given base address (from SBRM).
556 pub fn read_from<T: UsbTransfer>(
557 control: &mut ControlChannel<T>,
558 base: u64,
559 ) -> Result<Self, U3vError> {
560 Ok(Self {
561 base,
562 maximum_event_transfer_length: read_u32(
563 control,
564 base + eirm::MAXIMUM_EVENT_TRANSFER_LENGTH,
565 )?,
566 })
567 }
568
569 /// Set or clear EventEnable: whether the device sends events on its
570 /// event endpoint.
571 pub fn set_enabled<T: UsbTransfer>(
572 &self,
573 control: &mut ControlChannel<T>,
574 enabled: bool,
575 ) -> Result<(), U3vError> {
576 let value = if enabled { eirm::EVENT_ENABLE } else { 0 };
577 control.write_mem(self.base + eirm::CONTROL, &value.to_le_bytes())
578 }
579}
580
581// ---------------------------------------------------------------------------
582// Manifest (for locating GenICam XML)
583// ---------------------------------------------------------------------------
584
585/// Manifest layout (GenCP 1.2, Tables 29-30).
586mod manifest {
587 /// The table starts with a `u64` entry count.
588 pub(super) const ENTRIES: u64 = 8;
589 /// Each entry is 64 bytes.
590 pub(super) const ENTRY_LEN: u64 = 64;
591 /// Entries looked at before giving up on finding a device XML.
592 pub(super) const MAX_ENTRIES: u64 = 16;
593}
594
595/// How a manifest file is stored (Schema / Filetype / Fileformat bits 10-15).
596#[derive(Debug, Clone, Copy, PartialEq, Eq)]
597#[non_exhaustive]
598pub enum FileFormat {
599 /// An uncompressed GenICam XML file.
600 Uncompressed,
601 /// A ZIP archive holding a single GenICam XML file.
602 Zip,
603 /// A value GenCP 1.2 reserves.
604 Reserved(u8),
605}
606
607/// One entry of the device's Manifest Table: a GenICam file in its memory.
608#[derive(Debug, Clone)]
609pub struct ManifestEntry {
610 /// Where the file is.
611 pub file_address: u64,
612 /// Its size in bytes.
613 pub file_size: u64,
614 /// How it is stored.
615 pub format: FileFormat,
616}
617
618impl ManifestEntry {
619 /// The first entry describing a device XML (file type 0) in the
620 /// Manifest Table at `table_address` (from ABRM). A buffer XML (file
621 /// type 1) describes chunk data only and is skipped.
622 pub fn read_device_xml<T: UsbTransfer>(
623 control: &mut ControlChannel<T>,
624 table_address: u64,
625 ) -> Result<Self, U3vError> {
626 let count = read_u64(control, table_address)?;
627 if count == 0 {
628 return Err(U3vError::Device("has an empty manifest table"));
629 }
630 for index in 0..count.min(manifest::MAX_ENTRIES) {
631 let entry_address = table_address + manifest::ENTRIES + index * manifest::ENTRY_LEN;
632 let entry = control.read_mem(entry_address, 24)?;
633 let schema = u32::from_le_bytes(entry[4..8].try_into().unwrap());
634 let file_type = schema & 0x7;
635 if file_type != 0 {
636 continue;
637 }
638 let format = match ((schema >> 10) & 0x3F) as u8 {
639 0 => FileFormat::Uncompressed,
640 1 => FileFormat::Zip,
641 other => FileFormat::Reserved(other),
642 };
643 return Ok(Self {
644 file_address: u64::from_le_bytes(entry[8..16].try_into().unwrap()),
645 file_size: u64::from_le_bytes(entry[16..24].try_into().unwrap()),
646 format,
647 });
648 }
649 Err(U3vError::Device("lists no device XML in its manifest"))
650 }
651}
652
653// ---------------------------------------------------------------------------
654// Helpers
655// ---------------------------------------------------------------------------
656
657fn read_u32<T: UsbTransfer>(control: &mut ControlChannel<T>, addr: u64) -> Result<u32, U3vError> {
658 let bytes = control.read_mem(addr, 4)?;
659 Ok(u32::from_le_bytes(bytes[..4].try_into().unwrap()))
660}
661
662fn read_u64<T: UsbTransfer>(control: &mut ControlChannel<T>, addr: u64) -> Result<u64, U3vError> {
663 let bytes = control.read_mem(addr, 8)?;
664 Ok(u64::from_le_bytes(bytes[..8].try_into().unwrap()))
665}
666
667fn parse_nul_string(data: &[u8]) -> String {
668 let end = data.iter().position(|&b| b == 0).unwrap_or(data.len());
669 String::from_utf8_lossy(&data[..end]).into_owned()
670}
671
672// ---------------------------------------------------------------------------
673// Tests
674// ---------------------------------------------------------------------------
675
676#[cfg(test)]
677mod tests {
678 use super::*;
679
680 #[test]
681 fn parse_nul_terminated_string() {
682 let mut data = vec![0u8; 64];
683 let s = b"TestCamera";
684 data[..s.len()].copy_from_slice(s);
685 assert_eq!(parse_nul_string(&data), "TestCamera");
686 }
687
688 #[test]
689 fn parse_string_no_nul() {
690 let data = b"FullBuffer64Chars";
691 assert_eq!(parse_nul_string(data), "FullBuffer64Chars");
692 }
693
694 /// Device Capability bits 4-7 name the strings' encoding; UTF-16 code
695 /// units are little-endian, as every bootstrap field is.
696 #[test]
697 fn strings_follow_the_capability_encoding() {
698 let utf16 = StringEncoding::from_capability(2 << capability::STRING_ENCODING_SHIFT);
699 assert_eq!(utf16, StringEncoding::Utf16);
700 let mut raw = [0u8; 64];
701 for (i, unit) in "Ünï".encode_utf16().enumerate() {
702 raw[2 * i..2 * i + 2].copy_from_slice(&unit.to_le_bytes());
703 }
704 assert_eq!(utf16.decode(&raw), "Ünï");
705
706 let utf8 = StringEncoding::from_capability(1 << capability::STRING_ENCODING_SHIFT);
707 assert_eq!(utf8.decode("Ünï\0".as_bytes()), "Ünï");
708 assert_eq!(StringEncoding::from_capability(0), StringEncoding::Ascii);
709 }
710
711 #[test]
712 fn alignment_comes_from_info_bits_24_to_31() {
713 let sirm = |info| Sirm {
714 base: 0,
715 info,
716 control: 0,
717 required_payload_size: 0,
718 required_leader_size: 0,
719 required_trailer_size: 0,
720 };
721 assert_eq!(sirm(0).alignment().unwrap(), 1);
722 assert_eq!(sirm(10 << 24).alignment().unwrap(), 1024);
723 assert!(sirm(40 << 24).alignment().is_err());
724 }
725}