Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 #![warn(missing_docs)]
2 //! A new library for cross-platform low-level access to USB devices.
3 //!
4 //! `nusb` is comparable to the C library [libusb] and its Rust bindings [rusb],
5 //! but written in pure Rust. It's built on and exposes async APIs by default,
6 //! but can be made blocking using [`futures_lite::future::block_on`][block_on]
7 //! or similar.
8 //!
9 //! [libusb]: https://libusb.info
10 //! [rusb]: https://docs.rs/rusb/
11 //! [block_on]: https://docs.rs/futures-lite/latest/futures_lite/future/fn.block_on.html
12 //!
13 //! Use `nusb` to write user-space drivers in Rust for non-standard USB devices
14 //! or those without kernel support. For devices implementing a standard USB
15 //! class such as Mass Storage, CDC (Serial), HID, Audio, or Video, this is
16 //! probably not the library you're looking for -- use something built on the
17 //! existing kernel driver instead. (On some platforms you could detach or
18 //! replace the kernel driver and program the device from user-space using this
19 //! library, but you'd have to re-implement the class functionality yourself.)
20 //!
21 //! ## USB and usage overview
22 //!
23 //! When a USB device connects, the OS queries the device descriptor containing
24 //! basic device information such as the vendor and product ID (VID / PID) and
25 //! string descriptors like the manufacturer, product, and serial number
26 //! strings. [`list_devices`] returns an iterator listing connected USB devices,
27 //! which can be filtered by these fields to identify and select the desired
28 //! device.
29 //!
30 //! Call [`device_info.open()`](`DeviceInfo::open`) to open a selected device.
31 //! Additional information about the device can be queried with
32 //! [`device.active_configuration()`](`Device::active_configuration`).
33 //!
34 //! USB devices consist of one or more interfaces exposing a group of
35 //! functionality. A device with multiple interfaces is known as a composite
36 //! device. To open an interface, call [`Device::claim_interface`]. Only one
37 //! program (or kernel driver) may claim an interface at a time.
38 //!
39 //! Use the resulting [`Interface`] to transfer data on the device's control,
40 //! bulk or interrupt endpoints. Transfers are async by default, and can be
41 //! awaited as individual [`Future`][`transfer::TransferFuture`]s, or use a
42 //! [`Queue`][`transfer::Queue`] to manage streams of data.
43 //!
44 //! *For more details on how USB works, [USB in a
45 //! Nutshell](https://beyondlogic.org/usbnutshell/usb1.shtml) is a good
46 //! overview.*
47 //!
48 //! ## Logging
49 //!
50 //! `nusb` uses the [`log`](https://docs.rs/log) crate to log debug and error
51 //! information.
52 //!
53 //! When [submitting a bug report][gh-issues], please include the logs: use a
54 //! `log` backend like [`env_logger`](https://docs.rs/env_logger) and configure
55 //! it to enable log output for this crate (for `env_logger` set environment
56 //! variable `RUST_LOG=nusb=debug`.)
57 //!
58 //! [gh-issues]: https://github.com/kevinmehall/nusb/issues
59 //!
60 //! ## Platform support
61 //!
62 //! ### Linux
63 //!
64 //! `nusb` is built on the kernel's [usbfs] API.
65 //!
66 //! A user must have write access on the `/dev/bus/usb/XXX/YYY` nodes to
67 //! successfully open a device. Use [udev rules] to configure these permissions.
68 //!
69 //! For a single-user system used for development, it may be desirable to give
70 //! your user account access to all USB devices by placing the following in
71 //! `/etc/udev/rules.d/70-plugdev-usb.rules`:
72 //!
73 //! ```not_rust
74 //! SUBSYSTEM=="usb", MODE="0660", GROUP="plugdev"
75 //! ```
76 //!
77 //! This grants access on all USB devices to the `plugdev` group, which your
78 //! user may be a member of by default on Debian/Ubuntu-based distros. If you
79 //! are developing an app for others to install, you should scope the
80 //! permissions more narrowly using the `ATTRS{idVendor}=="ZZZZ",
81 //! ATTRS{idProduct}=="ZZZZ"` filters to only apply to your device.
82 //!
83 //! [usbfs]:
84 //! https://www.kernel.org/doc/html/latest/driver-api/usb/usb.html#the-usb-character-device-nodes
85 //! [udev rules]: https://www.reactivated.net/writing_udev_rules.html
86 //!
87 //! ### Windows
88 //!
89 //! `nusb` uses [WinUSB] on Windows.
90 //!
91 //! On Windows, devices are associated with a particular driver, which persists
92 //! across connections and reboots. Composite devices appear as multiple devices
93 //! in the Windows device model, and each interface can be associated with a
94 //! separate driver.
95 //!
96 //! To use `nusb`, your device or interface must be associated with the `WinUSB`
97 //! driver. If you control the device firmware, the recommended way is to use a
98 //! [WCID] descriptor to tell Windows to install the WinUSB driver automatically
99 //! when the device is first connected. Alternatively [Zadig] (GUI) or [libwdi]
100 //! (CLI / C library) can be used to manually install the WinUSB driver for a
101 //! device.
102 //!
103 //! [SetupAPI]:
104 //! https://learn.microsoft.com/en-us/windows-hardware/drivers/install/setupapi
105 //! [WinUSB]: https://learn.microsoft.com/en-us/windows/win32/api/winusb/
106 //! [WCID]: https://github.com/pbatard/libwdi/wiki/WCID-Devices
107 //! [Zadig]:https://zadig.akeo.ie/
108 //! [libwdi]: https://github.com/pbatard/libwdi
109 //!
110 //! ### macOS
111 //!
112 //! `nusb` uses IOKit on macOS.
113 //!
114 //! Users have access to USB devices by default, with no permission configuration needed.
115 //! Devices with a kernel driver are not accessible.
116
117 use std::io;
118
119 mod platform;
120
121 pub mod descriptors;
122 mod enumeration;
123 pub use enumeration::{DeviceId, DeviceInfo, InterfaceInfo, Speed};
124
125 mod device;
126 pub use device::{Device, Interface};
127
128 pub mod transfer;
129
130 pub mod hotplug;
131
132 /// OS error returned from operations other than transfers.
133 pub type Error = io::Error;
134
135 /// Get an iterator listing the connected devices.
136 ///
137 /// ### Example
138 ///
139 /// ```no_run
140 /// use nusb;
141 /// let device = nusb::list_devices().unwrap()
142 /// .find(|dev| dev.vendor_id() == 0xAAAA && dev.product_id() == 0xBBBB)
143 /// .expect("device not connected");
144 /// ```
145 ///
146 /// ### Platform-specific notes
147 /// * On Windows, hubs are not included in the list
148 pub fn list_devices() -> Result<impl Iterator<Item = DeviceInfo>, Error> {
149 platform::list_devices()
150 }
151
152 /// Get a [`Stream`][`futures_core::Stream`] that yields an
153 /// [event][`hotplug::HotplugEvent`] when a USB device is connected or
154 /// disconnected from the system.
155 ///
156 /// Events will be returned for devices connected or disconnected beginning at
157 /// the time this function is called. To maintain a list of connected devices,
158 /// call [`list_devices`] after creating the watch with this function to avoid
159 /// potentially missing a newly-attached device:
160 ///
161 /// ## Example
162 ///
163 /// ```no_run
164 /// use std::collections::HashMap;
165 /// use nusb::{DeviceInfo, DeviceId, hotplug::HotplugEvent};
166 /// let watch = nusb::watch_devices().unwrap();
167 /// let mut devices: HashMap<DeviceId, DeviceInfo> = nusb::list_devices().unwrap()
168 /// .map(|d| (d.id(), d)).collect();
169 /// for event in futures_lite::stream::block_on(watch) {
170 /// match event {
171 /// HotplugEvent::Connected(d) => {
172 /// devices.insert(d.id(), d);
173 /// }
174 /// HotplugEvent::Disconnected(id) => {
175 /// devices.remove(&id);
176 /// }
177 /// }
178 /// }
179 /// ```
180 ///
181 /// ### Platform-specific notes:
182 ///
183 /// * On Windows, the interfaces of a composite device might not be ready
184 /// when the `Connected` event is emitted. If you are immediately opening the device
185 /// and claiming an interface when receiving a `Connected` event,
186 /// you should retry after a short delay if opening or claiming fails.
187 pub fn watch_devices() -> Result<hotplug::HotplugWatch, Error> {
188 Ok(hotplug::HotplugWatch(platform::HotplugWatch::new()?))
189 }