Debian Codegraph @

src/device.rs

raw symbols SCIP
1 use std::{io::ErrorKind, sync::Arc, time::Duration};
2
3 use log::error;
4
5 use crate::{
6 descriptors::{
7 decode_string_descriptor, validate_string_descriptor, ActiveConfigurationError,
8 Configuration, InterfaceAltSetting, DESCRIPTOR_TYPE_STRING,
9 },
10 platform,
11 transfer::{
12 Control, ControlIn, ControlOut, EndpointType, Queue, RequestBuffer, TransferError,
13 TransferFuture,
14 },
15 DeviceInfo, Error,
16 };
17
18 /// An opened USB device.
19 ///
20 /// Obtain a `Device` by calling [`DeviceInfo::open`]:
21 ///
22 /// ```no_run
23 /// use nusb;
24 /// let device_info = nusb::list_devices().unwrap()
25 /// .find(|dev| dev.vendor_id() == 0xAAAA && dev.product_id() == 0xBBBB)
26 /// .expect("device not connected");
27 ///
28 /// let device = device_info.open().expect("failed to open device");
29 /// let interface = device.claim_interface(0);
30 /// ```
31 ///
32 /// This type is reference-counted with an [`Arc`] internally, and can be cloned cheaply for
33 /// use in multiple places in your program. The device is closed when all clones and all
34 /// associated [`Interface`]s are dropped.
35 ///
36 /// Use [`.claim_interface(i)`][`Device::claim_interface`] to open an interface to submit
37 /// transfers.
38 #[derive(Clone)]
39 pub struct Device {
40 backend: Arc<crate::platform::Device>,
41 }
42
43 impl Device {
44 pub(crate) fn open(d: &DeviceInfo) -> Result<Device, std::io::Error> {
45 let backend = platform::Device::from_device_info(d)?;
46 Ok(Device { backend })
47 }
48
49 /// Wraps a device that is already open.
50 #[cfg(any(target_os = "android", target_os = "linux"))]
51 pub fn from_fd(fd: std::os::fd::OwnedFd) -> Result<Device, Error> {
52 Ok(Device {
53 backend: platform::Device::from_fd(fd)?,
54 })
55 }
56
57 /// Open an interface of the device and claim it for exclusive use.
58 pub fn claim_interface(&self, interface: u8) -> Result<Interface, Error> {
59 let backend = self.backend.claim_interface(interface)?;
60 Ok(Interface { backend })
61 }
62
63 /// Detach kernel drivers and open an interface of the device and claim it for exclusive use.
64 ///
65 /// ### Platform notes
66 /// This function can only detach kernel drivers on Linux. Calling on other platforms has
67 /// the same effect as [`claim_interface`][`Device::claim_interface`].
68 pub fn detach_and_claim_interface(&self, interface: u8) -> Result<Interface, Error> {
69 let backend = self.backend.detach_and_claim_interface(interface)?;
70 Ok(Interface { backend })
71 }
72
73 /// Detach kernel drivers for the specified interface.
74 ///
75 /// ### Platform notes
76 /// This function can only detach kernel drivers on Linux. Calling on other platforms has
77 /// no effect.
78 pub fn detach_kernel_driver(&self, interface: u8) -> Result<(), Error> {
79 #[cfg(target_os = "linux")]
80 self.backend.detach_kernel_driver(interface)?;
81 let _ = interface;
82
83 Ok(())
84 }
85
86 /// Attach kernel drivers for the specified interface.
87 ///
88 /// ### Platform notes
89 /// This function can only attach kernel drivers on Linux. Calling on other platforms has
90 /// no effect.
91 pub fn attach_kernel_driver(&self, interface: u8) -> Result<(), Error> {
92 #[cfg(target_os = "linux")]
93 self.backend.attach_kernel_driver(interface)?;
94 let _ = interface;
95
96 Ok(())
97 }
98
99 /// Get information about the active configuration.
100 ///
101 /// This returns cached data and does not perform IO. However, it can fail if the
102 /// device is unconfigured, or if it can't find a configuration descriptor for
103 /// the configuration reported as active by the OS.
104 pub fn active_configuration(&self) -> Result<Configuration, ActiveConfigurationError> {
105 let active = self.backend.active_configuration_value();
106
107 self.configurations()
108 .find(|c| c.configuration_value() == active)
109 .ok_or_else(|| ActiveConfigurationError {
110 configuration_value: active,
111 })
112 }
113
114 /// Get an iterator returning information about each configuration of the device.
115 ///
116 /// This returns cached data and does not perform IO.
117 pub fn configurations(&self) -> impl Iterator<Item = Configuration> {
118 self.backend
119 .configuration_descriptors()
120 .map(Configuration::new)
121 }
122
123 /// Set the device configuration.
124 ///
125 /// The argument is the desired configuration's `bConfigurationValue`
126 /// descriptor field from [`Configuration::configuration_value`] or `0` to
127 /// unconfigure the device.
128 ///
129 /// ### Platform-specific notes
130 /// * Not supported on Windows
131 pub fn set_configuration(&self, configuration: u8) -> Result<(), Error> {
132 self.backend.set_configuration(configuration)
133 }
134
135 /// Request a descriptor from the device.
136 ///
137 /// The `language_id` should be `0` unless you are requesting a string descriptor.
138 ///
139 /// ### Platform-specific details
140 ///
141 /// * On Windows, the timeout argument is ignored, and an OS-defined timeout is used.
142 /// * On Windows, this does not wake suspended devices. Reading their
143 /// descriptors will return an error.
144 pub fn get_descriptor(
145 &self,
146 desc_type: u8,
147 desc_index: u8,
148 language_id: u16,
149 timeout: Duration,
150 ) -> Result<Vec<u8>, Error> {
151 #[cfg(target_os = "windows")]
152 {
153 let _ = timeout;
154 self.backend
155 .get_descriptor(desc_type, desc_index, language_id)
156 }
157
158 #[cfg(not(target_os = "windows"))]
159 {
160 const STANDARD_REQUEST_GET_DESCRIPTOR: u8 = 0x06;
161 use crate::transfer::{ControlType, Recipient};
162
163 let mut buf = vec![0; 4096];
164 let len = self.control_in_blocking(
165 Control {
166 control_type: ControlType::Standard,
167 recipient: Recipient::Device,
168 request: STANDARD_REQUEST_GET_DESCRIPTOR,
169 value: ((desc_type as u16) << 8) | desc_index as u16,
170 index: language_id,
171 },
172 &mut buf,
173 timeout,
174 )?;
175
176 buf.truncate(len);
177 Ok(buf)
178 }
179 }
180
181 /// Request the list of supported languages for string descriptors.
182 ///
183 /// ### Platform-specific details
184 ///
185 /// See notes on [`get_descriptor`][`Self::get_descriptor`].
186 pub fn get_string_descriptor_supported_languages(
187 &self,
188 timeout: Duration,
189 ) -> Result<impl Iterator<Item = u16>, Error> {
190 let data = self.get_descriptor(DESCRIPTOR_TYPE_STRING, 0, 0, timeout)?;
191
192 if !validate_string_descriptor(&data) {
193 error!("String descriptor language list read {data:?}, not a valid string descriptor");
194 return Err(Error::new(
195 ErrorKind::InvalidData,
196 "string descriptor data was invalid",
197 ));
198 }
199
200 //TODO: Use array_chunks once stable
201 let mut iter = data.into_iter().skip(2);
202 Ok(std::iter::from_fn(move || {
203 Some(u16::from_le_bytes([iter.next()?, iter.next()?]))
204 }))
205 }
206
207 /// Request a string descriptor from the device.
208 ///
209 /// Almost all devices support only the language ID [`US_ENGLISH`][`crate::descriptors::language_id::US_ENGLISH`].
210 ///
211 /// Unpaired UTF-16 surrogates will be replaced with `�`, like [`String::from_utf16_lossy`].
212 ///
213 /// ### Platform-specific details
214 ///
215 /// See notes on [`get_descriptor`][`Self::get_descriptor`].
216 pub fn get_string_descriptor(
217 &self,
218 desc_index: u8,
219 language_id: u16,
220 timeout: Duration,
221 ) -> Result<String, Error> {
222 if desc_index == 0 {
223 return Err(Error::new(
224 ErrorKind::InvalidInput,
225 "string descriptor index 0 is reserved for the language table",
226 ));
227 }
228 let data = self.get_descriptor(DESCRIPTOR_TYPE_STRING, desc_index, language_id, timeout)?;
229
230 decode_string_descriptor(&data)
231 .map_err(|_| Error::new(ErrorKind::InvalidData, "string descriptor data was invalid"))
232 }
233
234 /// Reset the device, forcing it to re-enumerate.
235 ///
236 /// This `Device` will no longer be usable, and you should drop it and call
237 /// [`super::list_devices`] to find and re-open it again.
238 ///
239 /// ### Platform-specific notes
240 /// * Not supported on Windows
241 pub fn reset(&self) -> Result<(), Error> {
242 self.backend.reset()
243 }
244
245 /// Synchronously perform a single **IN (device-to-host)** transfer on the default **control** endpoint.
246 ///
247 /// ### Platform-specific notes
248 ///
249 /// * Not supported on Windows. You must [claim an interface][`Device::claim_interface`]
250 /// and use the interface handle to submit transfers.
251 /// * On Linux, this takes a device-wide lock, so if you have multiple threads, you
252 /// are better off using the async methods.
253 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "android"))]
254 pub fn control_in_blocking(
255 &self,
256 control: Control,
257 data: &mut [u8],
258 timeout: Duration,
259 ) -> Result<usize, TransferError> {
260 self.backend.control_in_blocking(control, data, timeout)
261 }
262
263 /// Synchronously perform a single **OUT (host-to-device)** transfer on the default **control** endpoint.
264 ///
265 /// ### Platform-specific notes
266 ///
267 /// * Not supported on Windows. You must [claim an interface][`Device::claim_interface`]
268 /// and use the interface handle to submit transfers.
269 /// * On Linux, this takes a device-wide lock, so if you have multiple threads, you
270 /// are better off using the async methods.
271 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "android"))]
272 pub fn control_out_blocking(
273 &self,
274 control: Control,
275 data: &[u8],
276 timeout: Duration,
277 ) -> Result<usize, TransferError> {
278 self.backend.control_out_blocking(control, data, timeout)
279 }
280
281 /// Asynchronously submit a single **IN (device-to-host)** transfer on the default **control** endpoint.
282 ///
283 /// ### Example
284 ///
285 /// ```no_run
286 /// use futures_lite::future::block_on;
287 /// use nusb::transfer::{ ControlIn, ControlType, Recipient };
288 /// # fn main() -> Result<(), std::io::Error> {
289 /// # let di = nusb::list_devices().unwrap().next().unwrap();
290 /// # let device = di.open().unwrap();
291 ///
292 /// let data: Vec<u8> = block_on(device.control_in(ControlIn {
293 /// control_type: ControlType::Vendor,
294 /// recipient: Recipient::Device,
295 /// request: 0x30,
296 /// value: 0x0,
297 /// index: 0x0,
298 /// length: 64,
299 /// })).into_result()?;
300 /// # Ok(()) }
301 /// ```
302 ///
303 /// ### Platform-specific notes
304 ///
305 /// * Not supported on Windows. You must [claim an interface][`Device::claim_interface`]
306 /// and use the interface handle to submit transfers.
307 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "android"))]
308 pub fn control_in(&self, data: ControlIn) -> TransferFuture<ControlIn> {
309 let mut t = self.backend.make_control_transfer();
310 t.submit::<ControlIn>(data);
311 TransferFuture::new(t)
312 }
313
314 /// Submit a single **OUT (host-to-device)** transfer on the default **control** endpoint.
315 ///
316 /// ### Example
317 ///
318 /// ```no_run
319 /// use futures_lite::future::block_on;
320 /// use nusb::transfer::{ ControlOut, ControlType, Recipient };
321 /// # fn main() -> Result<(), std::io::Error> {
322 /// # let di = nusb::list_devices().unwrap().next().unwrap();
323 /// # let device = di.open().unwrap();
324 ///
325 /// block_on(device.control_out(ControlOut {
326 /// control_type: ControlType::Vendor,
327 /// recipient: Recipient::Device,
328 /// request: 0x32,
329 /// value: 0x0,
330 /// index: 0x0,
331 /// data: &[0x01, 0x02, 0x03, 0x04],
332 /// })).into_result()?;
333 /// # Ok(()) }
334 /// ```
335 ///
336 /// ### Platform-specific notes
337 ///
338 /// * Not supported on Windows. You must [claim an interface][`Device::claim_interface`]
339 /// and use the interface handle to submit transfers.
340 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "android"))]
341 pub fn control_out(&self, data: ControlOut) -> TransferFuture<ControlOut> {
342 let mut t = self.backend.make_control_transfer();
343 t.submit::<ControlOut>(data);
344 TransferFuture::new(t)
345 }
346 }
347
348 /// An opened interface of a USB device.
349 ///
350 /// Obtain an `Interface` with the [`Device::claim_interface`] method.
351 ///
352 /// This type is reference-counted with an [`Arc`] internally, and can be cloned cheaply for
353 /// use in multiple places in your program. The interface is released when all clones, and all
354 /// associated [`TransferFuture`]s and [`Queue`]s are dropped.
355 #[derive(Clone)]
356 pub struct Interface {
357 backend: Arc<platform::Interface>,
358 }
359
360 impl Interface {
361 /// Select the alternate setting of this interface.
362 ///
363 /// An alternate setting is a mode of the interface that makes particular endpoints available
364 /// and may enable or disable functionality of the device. The OS resets the device to the default
365 /// alternate setting when the interface is released or the program exits.
366 pub fn set_alt_setting(&self, alt_setting: u8) -> Result<(), Error> {
367 self.backend.set_alt_setting(alt_setting)
368 }
369
370 /// Synchronously perform a single **IN (device-to-host)** transfer on the default **control** endpoint.
371 ///
372 /// ### Platform-specific notes
373 ///
374 /// * On Linux, this takes a device-wide lock, so if you have multiple
375 /// threads, you are better off using the async methods.
376 /// * On Windows, if the `recipient` is `Interface`, the WinUSB driver sends
377 /// the interface number in the least significant byte of `index`,
378 /// overriding any value passed. A warning is logged if the passed `index`
379 /// least significant byte differs from the interface number, and this may
380 /// become an error in the future.
381 pub fn control_in_blocking(
382 &self,
383 control: Control,
384 data: &mut [u8],
385 timeout: Duration,
386 ) -> Result<usize, TransferError> {
387 self.backend.control_in_blocking(control, data, timeout)
388 }
389
390 /// Synchronously perform a single **OUT (host-to-device)** transfer on the default **control** endpoint.
391 ///
392 /// ### Platform-specific notes
393 ///
394 /// * On Linux, this takes a device-wide lock, so if you have multiple
395 /// threads, you are better off using the async methods.
396 /// * On Windows, if the `recipient` is `Interface`, the WinUSB driver sends
397 /// the interface number in the least significant byte of `index`,
398 /// overriding any value passed. A warning is logged if the passed `index`
399 /// least significant byte differs from the interface number, and this may
400 /// become an error in the future.
401 pub fn control_out_blocking(
402 &self,
403 control: Control,
404 data: &[u8],
405 timeout: Duration,
406 ) -> Result<usize, TransferError> {
407 self.backend.control_out_blocking(control, data, timeout)
408 }
409
410 /// Submit a single **IN (device-to-host)** transfer on the default **control** endpoint.
411 ///
412 /// ### Example
413 ///
414 /// ```no_run
415 /// use futures_lite::future::block_on;
416 /// use nusb::transfer::{ ControlIn, ControlType, Recipient };
417 /// # fn main() -> Result<(), std::io::Error> {
418 /// # let di = nusb::list_devices().unwrap().next().unwrap();
419 /// # let device = di.open().unwrap();
420 /// # let interface = device.claim_interface(0).unwrap();
421 ///
422 /// let data: Vec<u8> = block_on(interface.control_in(ControlIn {
423 /// control_type: ControlType::Vendor,
424 /// recipient: Recipient::Device,
425 /// request: 0x30,
426 /// value: 0x0,
427 /// index: 0x0,
428 /// length: 64,
429 /// })).into_result()?;
430 /// # Ok(()) }
431 /// ```
432 ///
433 /// ### Platform-specific notes
434 /// * On Windows, if the `recipient` is `Interface`, the WinUSB driver sends
435 /// the interface number in the least significant byte of `index`,
436 /// overriding any value passed. A warning is logged if the passed `index`
437 /// least significant byte differs from the interface number, and this may
438 /// become an error in the future.
439 pub fn control_in(&self, data: ControlIn) -> TransferFuture<ControlIn> {
440 let mut t = self.backend.make_transfer(0, EndpointType::Control);
441 t.submit::<ControlIn>(data);
442 TransferFuture::new(t)
443 }
444
445 /// Submit a single **OUT (host-to-device)** transfer on the default **control** endpoint.
446 ///
447 /// ### Example
448 ///
449 /// ```no_run
450 /// use futures_lite::future::block_on;
451 /// use nusb::transfer::{ ControlOut, ControlType, Recipient };
452 /// # fn main() -> Result<(), std::io::Error> {
453 /// # let di = nusb::list_devices().unwrap().next().unwrap();
454 /// # let device = di.open().unwrap();
455 /// # let interface = device.claim_interface(0).unwrap();
456 ///
457 /// block_on(interface.control_out(ControlOut {
458 /// control_type: ControlType::Vendor,
459 /// recipient: Recipient::Device,
460 /// request: 0x32,
461 /// value: 0x0,
462 /// index: 0x0,
463 /// data: &[0x01, 0x02, 0x03, 0x04],
464 /// })).into_result()?;
465 /// # Ok(()) }
466 /// ```
467 ///
468 /// ### Platform-specific notes
469 /// * On Windows, if the `recipient` is `Interface`, the WinUSB driver sends
470 /// the interface number in the least significant byte of `index`,
471 /// overriding any value passed. A warning is logged if the passed `index`
472 /// least significant byte differs from the interface number, and this may
473 /// become an error in the future.
474 pub fn control_out(&self, data: ControlOut) -> TransferFuture<ControlOut> {
475 let mut t = self.backend.make_transfer(0, EndpointType::Control);
476 t.submit::<ControlOut>(data);
477 TransferFuture::new(t)
478 }
479
480 /// Submit a single **IN (device-to-host)** transfer on the specified **bulk** endpoint.
481 ///
482 /// * The requested length must be a multiple of the endpoint's maximum packet size
483 /// * An IN endpoint address must have the top (`0x80`) bit set.
484 pub fn bulk_in(&self, endpoint: u8, buf: RequestBuffer) -> TransferFuture<RequestBuffer> {
485 let mut t = self.backend.make_transfer(endpoint, EndpointType::Bulk);
486 t.submit(buf);
487 TransferFuture::new(t)
488 }
489
490 /// Submit a single **OUT (host-to-device)** transfer on the specified **bulk** endpoint.
491 ///
492 /// * An OUT endpoint address must have the top (`0x80`) bit clear.
493 pub fn bulk_out(&self, endpoint: u8, buf: Vec<u8>) -> TransferFuture<Vec<u8>> {
494 let mut t = self.backend.make_transfer(endpoint, EndpointType::Bulk);
495 t.submit(buf);
496 TransferFuture::new(t)
497 }
498
499 /// Create a queue for managing multiple **IN (device-to-host)** transfers on a **bulk** endpoint.
500 ///
501 /// * An IN endpoint address must have the top (`0x80`) bit set.
502 pub fn bulk_in_queue(&self, endpoint: u8) -> Queue<RequestBuffer> {
503 Queue::new(self.backend.clone(), endpoint, EndpointType::Bulk)
504 }
505
506 /// Create a queue for managing multiple **OUT (host-to-device)** transfers on a **bulk** endpoint.
507 ///
508 /// * An OUT endpoint address must have the top (`0x80`) bit clear.
509 pub fn bulk_out_queue(&self, endpoint: u8) -> Queue<Vec<u8>> {
510 Queue::new(self.backend.clone(), endpoint, EndpointType::Bulk)
511 }
512
513 /// Submit a single **IN (device-to-host)** transfer on the specified **interrupt** endpoint.
514 ///
515 /// * The requested length must be a multiple of the endpoint's maximum packet size
516 /// * An IN endpoint address must have the top (`0x80`) bit set.
517 pub fn interrupt_in(&self, endpoint: u8, buf: RequestBuffer) -> TransferFuture<RequestBuffer> {
518 let mut t = self
519 .backend
520 .make_transfer(endpoint, EndpointType::Interrupt);
521 t.submit(buf);
522 TransferFuture::new(t)
523 }
524
525 /// Submit a single **OUT (host-to-device)** transfer on the specified **interrupt** endpoint.
526 ///
527 /// * An OUT endpoint address must have the top (`0x80`) bit clear.
528 pub fn interrupt_out(&self, endpoint: u8, buf: Vec<u8>) -> TransferFuture<Vec<u8>> {
529 let mut t = self
530 .backend
531 .make_transfer(endpoint, EndpointType::Interrupt);
532 t.submit(buf);
533 TransferFuture::new(t)
534 }
535
536 /// Create a queue for managing multiple **IN (device-to-host)** transfers on an **interrupt** endpoint.
537 ///
538 /// * An IN endpoint address must have the top (`0x80`) bit set.
539 pub fn interrupt_in_queue(&self, endpoint: u8) -> Queue<RequestBuffer> {
540 Queue::new(self.backend.clone(), endpoint, EndpointType::Interrupt)
541 }
542
543 /// Create a queue for managing multiple **OUT (device-to-host)** transfers on an **interrupt** endpoint.
544 ///
545 /// * An OUT endpoint address must have the top (`0x80`) bit clear.
546 pub fn interrupt_out_queue(&self, endpoint: u8) -> Queue<Vec<u8>> {
547 Queue::new(self.backend.clone(), endpoint, EndpointType::Interrupt)
548 }
549
550 /// Clear a bulk or interrupt endpoint's halt / stall condition.
551 ///
552 /// Sends a `CLEAR_FEATURE` `ENDPOINT_HALT` control transfer to tell the
553 /// device to reset the endpoint's data toggle and clear the halt / stall
554 /// condition, and resets the host-side data toggle.
555 ///
556 /// Use this after receiving [`TransferError::Stall`] to clear the error and
557 /// resume use of the endpoint.
558 ///
559 /// This should not be called when transfers are pending on the endpoint.
560 pub fn clear_halt(&self, endpoint: u8) -> Result<(), Error> {
561 self.backend.clear_halt(endpoint)
562 }
563
564 /// Get the interface number.
565 pub fn interface_number(&self) -> u8 {
566 self.backend.interface_number
567 }
568
569 /// Get the interface descriptors for the alternate settings of this interface.
570 ///
571 /// This returns cached data and does not perform IO.
572 pub fn descriptors(&self) -> impl Iterator<Item = InterfaceAltSetting> {
573 let active = self.backend.device.active_configuration_value();
574
575 let configuration = self
576 .backend
577 .device
578 .configuration_descriptors()
579 .map(Configuration::new)
580 .find(|c| c.configuration_value() == active);
581
582 configuration
583 .into_iter()
584 .flat_map(|i| i.interface_alt_settings())
585 .filter(|g| g.interface_number() == self.backend.interface_number)
586 }
587 }
588
589 #[test]
590 fn assert_send_sync() {
591 fn require_send_sync<T: Send + Sync>() {}
592 require_send_sync::<Interface>();
593 require_send_sync::<Device>();
594 }