Skip to main content

viva_u3v/
device.rs

1//! High-level USB3 Vision device handle.
2//!
3//! [`U3vDevice`] combines a control channel with parsed bootstrap registers
4//! to provide register I/O, XML fetching, and stream configuration.
5
6use std::fmt::Write as _;
7use std::io::Read;
8use std::sync::Arc;
9use std::time::Duration;
10
11use crate::U3vError;
12use crate::bootstrap::{
13    Abrm, Eirm, FileFormat, ManifestEntry, Sbrm, Sirm, UsbSpeed, abrm, capability, sbrm, sirm,
14    u3vcp_capability,
15};
16use crate::control::{ControlChannel, DEFAULT_TIMEOUT};
17use crate::event::U3vEventStream;
18use crate::stream::{
19    DEFAULT_MAX_TRANSFER_SIZE, DEFAULT_TRANSFERS_IN_FLIGHT, StreamLayout, U3vStream,
20};
21use crate::usb::{GONE_GRACE, UsbTransfer, unless_gone};
22
23/// How a stream reads: the payload size to use when the device does not say,
24/// and the transfers it keeps queued.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub struct U3vStreamOptions {
27    /// Bytes of payload in one block — from the `PayloadSize` feature, say —
28    /// used only when the SIRM's Required Payload Size is 0; 0 for none.
29    pub payload_size_hint: u64,
30    /// The largest payload transfer to ask for
31    /// ([`DEFAULT_MAX_TRANSFER_SIZE`]).
32    pub max_transfer_size: u32,
33    /// Transfers to keep queued ([`DEFAULT_TRANSFERS_IN_FLIGHT`]).
34    pub transfers_in_flight: usize,
35}
36
37impl Default for U3vStreamOptions {
38    fn default() -> Self {
39        Self {
40            payload_size_hint: 0,
41            max_transfer_size: DEFAULT_MAX_TRANSFER_SIZE,
42            transfers_in_flight: DEFAULT_TRANSFERS_IN_FLIGHT,
43        }
44    }
45}
46
47/// ZIP local file header magic: `PK\x03\x04`.
48const ZIP_MAGIC: &[u8; 4] = b"PK\x03\x04";
49
50/// Extract the first file of a ZIP archive.
51fn unzip_first(data: &[u8]) -> Result<Vec<u8>, U3vError> {
52    let cursor = std::io::Cursor::new(data);
53    let mut archive = zip::ZipArchive::new(cursor).map_err(|e| U3vError::Xml(Box::new(e)))?;
54    if archive.is_empty() {
55        return Err(U3vError::Device("serves an empty XML ZIP archive"));
56    }
57    let mut file = archive
58        .by_index(0)
59        .map_err(|e| U3vError::Xml(Box::new(e)))?;
60    let mut xml = Vec::with_capacity(file.size() as usize);
61    file.read_to_end(&mut xml)
62        .map_err(|e| U3vError::Xml(Box::new(e)))?;
63    Ok(xml)
64}
65
66/// Transfer limit used for the bootstrap reads, before the SBRM gives the
67/// device's own: small enough for any device.
68const INITIAL_MAX_TRANSFER: u32 = 1024;
69
70/// Added to the device's Maximum Device Response Time, which counts only
71/// the command's execution, for the two transfers around it (GenCP 1.2
72/// §3.1.2).
73const TRANSFER_MARGIN: Duration = Duration::from_millis(100);
74
75/// High-level handle for a USB3 Vision device.
76///
77/// Wraps a [`ControlChannel`] and parsed bootstrap registers. The generic
78/// `T` parameter allows production use with `NusbTransfer` (the `usb`
79/// feature) and testing with [`MockUsbTransfer`](crate::usb::MockUsbTransfer).
80pub struct U3vDevice<T: UsbTransfer> {
81    control: ControlChannel<T>,
82    abrm: Abrm,
83    sbrm: Sbrm,
84    stream_ep: Option<u8>,
85    event_ep: Option<u8>,
86    speed: Option<UsbSpeed>,
87}
88
89impl<T: UsbTransfer> U3vDevice<T> {
90    /// Open a U3V device given a shared USB transport and endpoint addresses.
91    ///
92    /// Reads the ABRM and SBRM bootstrap registers, then uses the device's
93    /// response time and transfer limits on the same control channel.
94    pub fn open(
95        transport: Arc<T>,
96        ep_in: u8,
97        ep_out: u8,
98        stream_ep: Option<u8>,
99        event_ep: Option<u8>,
100    ) -> Result<Self, U3vError> {
101        let mut control = ControlChannel::new(
102            transport,
103            ep_in,
104            ep_out,
105            INITIAL_MAX_TRANSFER,
106            INITIAL_MAX_TRANSFER,
107        );
108
109        let abrm = Abrm::read_from(&mut control)?;
110        let response_time =
111            Duration::from_millis(u64::from(abrm.max_device_response_time_ms)) + TRANSFER_MARGIN;
112        control.set_timeout(response_time.max(DEFAULT_TIMEOUT));
113
114        let sbrm = Sbrm::read_from(&mut control, abrm.sbrm_address)?;
115        control.set_max_transfer(sbrm.max_cmd_transfer, sbrm.max_ack_transfer);
116        // The host's word for the link, else the device's own register.
117        let speed = control.transport().link_speed().or(sbrm.current_speed);
118        if let Some(speed) = speed.filter(|s| s.is_below_superspeed()) {
119            // Backlog UV-03: a USB 2 port, cable or hub; streaming at a
120            // fraction of the camera's bandwidth, if at all.
121            tracing::warn!(
122                %speed,
123                model = %abrm.model_name,
124                "the USB3 Vision camera runs below SuperSpeed: plug it into a USB 3 port, \
125                 directly or through a USB 3 hub and cable"
126            );
127        }
128
129        Ok(Self {
130            control,
131            abrm,
132            sbrm,
133            stream_ep,
134            event_ep,
135            speed,
136        })
137    }
138
139    /// Access the shared transport handle (e.g. to create additional streams).
140    pub fn transport(&self) -> Arc<T> {
141        self.control.transport().clone()
142    }
143
144    /// Reference to the parsed ABRM.
145    pub fn abrm(&self) -> &Abrm {
146        &self.abrm
147    }
148
149    /// Reference to the parsed SBRM.
150    pub fn sbrm(&self) -> &Sbrm {
151        &self.sbrm
152    }
153
154    /// The bus speed the device runs at: as the host's USB stack reports
155    /// it, or else as the SBRM's current speed register says.
156    pub fn current_speed(&self) -> Option<UsbSpeed> {
157        self.speed
158    }
159
160    /// The device time, in ns: latched, then read from the GenCP timestamp
161    /// registers (GenCP 1.3.1 §5.4.16-17); `None` when the device has none
162    /// (Device Capability bit 3). The clock a stream's leaders and events
163    /// are stamped with.
164    pub fn timestamp(&mut self) -> Result<Option<u64>, U3vError> {
165        if self.abrm.device_capability & capability::TIMESTAMP == 0 {
166            return Ok(None);
167        }
168        self.control
169            .write_mem(abrm::TIMESTAMP_LATCH, &1u32.to_le_bytes())?;
170        let bytes = self.control.read_mem(abrm::TIMESTAMP, 8)?;
171        Ok(Some(u64::from_le_bytes(bytes[..8].try_into().unwrap())))
172    }
173
174    /// Read `len` bytes from device memory at `addr`.
175    pub fn read_mem(&mut self, addr: u64, len: usize) -> Result<Vec<u8>, U3vError> {
176        self.control.read_mem(addr, len)
177    }
178
179    /// Write `data` to device memory at `addr`.
180    pub fn write_mem(&mut self, addr: u64, data: &[u8]) -> Result<(), U3vError> {
181        self.control.write_mem(addr, data)
182    }
183
184    /// Read the device's half of the SIRM (Streaming Interface Register Map).
185    pub fn read_sirm(&mut self) -> Result<Sirm, U3vError> {
186        if self.sbrm.sirm_address == 0 {
187            return Err(U3vError::Device(
188                "has no streaming interface (SIRM address 0)",
189            ));
190        }
191        Sirm::read_from(&mut self.control, self.sbrm.sirm_address)
192    }
193
194    /// Fetch the GenICam XML descriptor from the device's manifest table.
195    ///
196    /// A ZIP-compressed file — by the manifest's file format, or by its
197    /// `PK\x03\x04` signature — is decompressed. Returns the XML as a UTF-8
198    /// string.
199    pub fn fetch_xml(&mut self) -> Result<String, U3vError> {
200        let entry =
201            ManifestEntry::read_device_xml(&mut self.control, self.abrm.manifest_table_address)?;
202        let raw = self
203            .control
204            .read_mem(entry.file_address, entry.file_size as usize)?;
205        let zipped = entry.format == FileFormat::Zip || raw.starts_with(ZIP_MAGIC);
206        let xml_bytes = if zipped { unzip_first(&raw)? } else { raw };
207        String::from_utf8(xml_bytes).map_err(|e| U3vError::Xml(Box::new(e)))
208    }
209
210    /// The bulk IN endpoint for streaming data, if the device has one.
211    pub fn stream_ep(&self) -> Option<u8> {
212        self.stream_ep
213    }
214
215    /// The bulk IN endpoint for events, if the device has one.
216    pub fn event_ep(&self) -> Option<u8> {
217        self.event_ep
218    }
219
220    /// [`open_stream_with`](Self::open_stream_with) the default transfer
221    /// settings and `payload_hint`.
222    pub fn open_stream(&mut self, payload_hint: u64) -> Result<U3vStream, U3vError>
223    where
224        T: 'static,
225    {
226        self.open_stream_with(&U3vStreamOptions {
227            payload_size_hint: payload_hint,
228            ..U3vStreamOptions::default()
229        })
230    }
231
232    /// Configure the SIRM, reset the stream endpoint and enable streaming,
233    /// returning a [`U3vStream`] that reads with the configured transfer
234    /// layout.
235    ///
236    /// The payload size is the SIRM's Required Payload Size: the device's
237    /// own figure for this stream channel. The options' hint — from the
238    /// `PayloadSize` feature, say — is used only when the device leaves that
239    /// register at 0. Every transfer is a multiple of the SIRM's alignment
240    /// and of the endpoint's packet size, whichever is larger.
241    ///
242    /// The endpoint is reset — halted and cleared, so the device drops
243    /// whatever an earlier stream left on it — after the layout is written
244    /// and before StreamEnable is set, as aravis does
245    /// (`arv_uv_device_reset_stream_endpoint`; backlog TC-27 (3)).
246    pub fn open_stream_with(&mut self, options: &U3vStreamOptions) -> Result<U3vStream, U3vError>
247    where
248        T: 'static,
249    {
250        let ep = self
251            .stream_ep
252            .ok_or(U3vError::Device("has no streaming endpoint"))?;
253
254        let sirm = self.read_sirm()?;
255        let payload_hint = options.payload_size_hint;
256        let payload_size = match sirm.required_payload_size {
257            0 => payload_hint,
258            required => {
259                if payload_hint != 0 && payload_hint != required {
260                    tracing::debug!(
261                        required,
262                        payload_hint,
263                        "SIRM requires a payload size other than the hint; using the SIRM's"
264                    );
265                }
266                required
267            }
268        };
269        let transport = Arc::clone(self.control.transport());
270        let packet = transport
271            .max_packet_size(ep)
272            .and_then(|size| u32::try_from(size).ok())
273            .unwrap_or(1);
274        let alignment = sirm.alignment()?.max(packet);
275        let layout = StreamLayout::new(
276            payload_size,
277            sirm.required_leader_size,
278            sirm.required_trailer_size,
279            alignment,
280            options.max_transfer_size,
281        )?;
282        let mut queue = transport.bulk_in(ep)?;
283        sirm.configure(&mut self.control, &layout)?;
284        queue
285            .reset()
286            .map_err(|error| unless_gone(error, || queue.is_present(), GONE_GRACE))?;
287        sirm.enable(&mut self.control)?;
288
289        let mut stream = U3vStream::new(queue, layout);
290        stream.set_transfers_in_flight(options.transfers_in_flight);
291        Ok(stream)
292    }
293
294    /// Clear StreamEnable: the device stops sending on the stream endpoint.
295    pub fn stop_stream(&mut self) -> Result<(), U3vError> {
296        let sirm = self.read_sirm()?;
297        sirm.disable(&mut self.control)
298    }
299
300    /// The device's event interface registers; an error when it has none
301    /// (U3VCP Capability bit 1, or an EIRM address of 0).
302    pub fn read_eirm(&mut self) -> Result<Eirm, U3vError> {
303        if self.sbrm.eirm_address == 0
304            || self.sbrm.u3vcp_capability & u3vcp_capability::EIRM_AVAILABLE == 0
305        {
306            return Err(U3vError::Device("has no event interface (EIRM)"));
307        }
308        Eirm::read_from(&mut self.control, self.sbrm.eirm_address)
309    }
310
311    /// Set EventEnable and return a [`U3vEventStream`] reading the event
312    /// endpoint (backlog TC-27 (4)). Which events the device sends is the
313    /// XML's `EventSelector` / `EventNotification` to choose.
314    pub fn open_events(&mut self) -> Result<U3vEventStream, U3vError>
315    where
316        T: 'static,
317    {
318        let ep = self
319            .event_ep
320            .ok_or(U3vError::Device("has no event endpoint"))?;
321        let eirm = self.read_eirm()?;
322        let transport = Arc::clone(self.control.transport());
323        let mut queue = transport.bulk_in(ep)?;
324        // As for the stream: whatever an earlier session left queued on the
325        // endpoint is dropped before events are enabled.
326        queue
327            .reset()
328            .map_err(|error| unless_gone(error, || queue.is_present(), GONE_GRACE))?;
329        eirm.set_enabled(&mut self.control, true)?;
330        Ok(U3vEventStream::new(
331            queue,
332            eirm.maximum_event_transfer_length,
333            transport.max_packet_size(ep),
334        ))
335    }
336
337    /// Clear EventEnable: the device stops sending events.
338    pub fn stop_events(&mut self) -> Result<(), U3vError> {
339        let eirm = self.read_eirm()?;
340        eirm.set_enabled(&mut self.control, false)
341    }
342
343    /// The bootstrap registers as read, decoded and raw, for a diagnostic
344    /// report. One camera has been checked against this (backlog TC-27), so
345    /// the raw SBRM and SIRM bytes are what settles a disagreement. A register the device refuses is listed as such.
346    pub fn describe(&mut self) -> Vec<(String, String)> {
347        let abrm = &self.abrm;
348        let sbrm = &self.sbrm;
349        let version = |v: u32| format!("{}.{}", v >> 16, v & 0xFFFF);
350        let mut lines = vec![
351            ("GenCP version".to_string(), version(abrm.gencp_version)),
352            (
353                "device capability".to_string(),
354                format!("{:#018x}", abrm.device_capability),
355            ),
356            (
357                "max device response time".to_string(),
358                format!("{} ms", abrm.max_device_response_time_ms),
359            ),
360            (
361                "manifest table".to_string(),
362                format!("{:#x}", abrm.manifest_table_address),
363            ),
364            ("SBRM".to_string(), format!("{:#x}", sbrm.base)),
365            ("U3V version".to_string(), version(sbrm.u3v_version)),
366            (
367                "U3VCP capability".to_string(),
368                format!("{:#018x}", sbrm.u3vcp_capability),
369            ),
370            (
371                "max command / ack transfer".to_string(),
372                format!(
373                    "{} / {} bytes",
374                    sbrm.max_cmd_transfer, sbrm.max_ack_transfer
375                ),
376            ),
377            (
378                "stream channels".to_string(),
379                sbrm.num_stream_channels.to_string(),
380            ),
381            (
382                "SIRM".to_string(),
383                format!("{:#x} ({} bytes)", sbrm.sirm_address, sbrm.sirm_length),
384            ),
385        ];
386        let sbrm_base = sbrm.base;
387        let sirm_base = sbrm.sirm_address;
388        lines.push((
389            "SBRM bytes".to_string(),
390            self.hex(sbrm_base, sbrm::LEN as usize),
391        ));
392        if sirm_base != 0 {
393            lines.push((
394                "SIRM bytes".to_string(),
395                self.hex(sirm_base, sirm::LEN as usize),
396            ));
397        }
398        lines
399    }
400
401    fn hex(&mut self, addr: u64, len: usize) -> String {
402        match self.control.read_mem(addr, len) {
403            Ok(bytes) => bytes.iter().fold(String::new(), |mut out, b| {
404                let _ = write!(out, "{b:02x}");
405                out
406            }),
407            Err(e) => format!("unreadable: {e}"),
408        }
409    }
410}
411
412// ---------------------------------------------------------------------------
413// Open a discovered device over nusb (convenience)
414// ---------------------------------------------------------------------------
415
416#[cfg(feature = "usb")]
417impl U3vDevice<crate::native::NusbTransfer> {
418    /// Open a USB3 Vision device from a [`U3vDeviceInfo`](crate::discovery::U3vDeviceInfo)
419    /// obtained via [`discover()`](crate::discovery::discover).
420    pub fn open_device(info: &crate::discovery::U3vDeviceInfo) -> Result<Self, U3vError> {
421        let transport = crate::native::NusbTransfer::open(info)?;
422        let iface = transport.interfaces().clone();
423        Self::open(
424            Arc::new(transport),
425            iface.control_ep_in,
426            iface.control_ep_out,
427            iface.stream_ep_in,
428            iface.event_ep_in,
429        )
430    }
431}