Skip to content

dev: add class field to UsbDevice #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1 +1 @@
merge_imports = true
imports_granularity="Crate"
56 changes: 28 additions & 28 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
[package]
authors = ["Tim Fish <[email protected]>"]
description = "A cross platform library that returns details of currently connected USB devices"
edition = "2018"
license = "MIT"
name = "usb_enumeration"
readme = "README.md"
repository = "https://github.com/meatysolutions/usb_enumeration"
version = "0.2.0"
[lib]
crate-type = ["lib"]
path = "src/lib.rs"
[features]
# Used to fail build on warnings
strict = []
[dependencies]
crossbeam = "0.8"
[target.'cfg(target_os = "windows")'.dependencies]
winapi = {version = "0.3", features = ["setupapi", "impl-default"]}
[target.'cfg(target_os = "linux")'.dependencies]
udev = "0.5"
[target.'cfg(target_os = "macos")'.dependencies]
core-foundation = "0.6"
io-kit-sys = "0.1.0"
mach = "0.3.2"
[package]
authors = ["Tim Fish <[email protected]>"]
description = "A cross platform library that returns details of currently connected USB devices"
edition = "2018"
license = "MIT"
name = "usb_enumeration"
readme = "README.md"
repository = "https://github.com/meatysolutions/usb_enumeration"
version = "0.2.0"

[lib]
crate-type = ["lib"]
path = "src/lib.rs"

[features]
# Used to fail build on warnings
strict = []

[dependencies]
crossbeam = "0.8"
[target.'cfg(target_os = "windows")'.dependencies]
windows-sys = { version = "0.52.0", features = ["Win32_Devices_DeviceAndDriverInstallation", "Win32_Foundation"] }
[target.'cfg(target_os = "linux")'.dependencies]
udev = "0.8"
[target.'cfg(target_os = "macos")'.dependencies]
core-foundation = "0.9"
io-kit-sys = "0.4.1"
mach = "0.3.2"
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# usb_enumeration

A cross platform Rust library that returns the vendor and product IDs of
A cross-platform Rust library that returns the vendor and product IDs of
currently connected USB devices

[![Actions Status](https://github.com/timfish/usb-enumeration/workflows/Build/badge.svg)](https://github.com/timfish/usb-enumeration/actions)
Expand Down
6 changes: 6 additions & 0 deletions examples/list.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//! Enumerate usb devices.

fn main() {
let devices = usb_enumeration::enumerate(None, None);
println!("{:#?}", devices);
}
14 changes: 14 additions & 0 deletions examples/sub.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use usb_enumeration::{Event, Observer};

fn main() {
let sub = Observer::new().with_poll_interval(2).subscribe();

// when sub is dropped, the background thread will close
for event in sub.rx_event.iter() {
match event {
Event::Initial(d) => println!("Initial devices: {:?}", d),
Event::Connect(d) => println!("Connected device: {:?}", d),
Event::Disconnect(d) => println!("Disconnected device: {:?}", d),
}
}
}
2 changes: 2 additions & 0 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pub struct UsbDevice {
pub description: Option<String>,
/// Optional serial number
pub serial_number: Option<String>,
/// Class of device.
pub class: Option<String>,
}

#[derive(Copy, Clone, Debug)]
Expand Down
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ use std::{collections::HashSet, thread, time::Duration};
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
use crate::windows::*;
use crate::windows::enumerate_platform;

#[cfg(target_os = "macos")]
mod macos;
Expand All @@ -93,6 +93,7 @@ use crate::linux::*;
/// ```no_run
/// let devices = usb_enumeration::enumerate(Some(0x1234), None);
/// ```
#[must_use]
pub fn enumerate(vendor_id: Option<u16>, product_id: Option<u16>) -> Vec<UsbDevice> {
enumerate_platform(vendor_id, product_id)
}
Expand Down Expand Up @@ -233,7 +234,7 @@ mod tests {
#[test]
fn test_enumerate() {
let devices = enumerate(None, None);
println!("Enumerated devices: {:#?}", devices);
println!("Enumerated devices: {devices:#?}");
assert!(!devices.is_empty());
}

Expand Down
63 changes: 42 additions & 21 deletions src/windows.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,32 @@
use crate::common::*;
use crate::common::{ParseError, UsbDevice};
use std::{
error::Error,
ffi::OsStr,
mem::size_of,
os::windows::ffi::OsStrExt,
mem::{size_of, zeroed},
ptr::{null, null_mut},
};
use winapi::um::setupapi::*;
use windows_sys::{
w,
Win32::Devices::DeviceAndDriverInstallation::{
SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInfo, SetupDiGetClassDevsW,
SetupDiGetDeviceInstanceIdW, SetupDiGetDeviceRegistryPropertyW, DIGCF_ALLCLASSES,
DIGCF_PRESENT, SPDRP_CLASS, SPDRP_DEVICEDESC, SPDRP_HARDWAREID, SP_DEVINFO_DATA,
},
};

pub fn enumerate_platform(vid: Option<u16>, pid: Option<u16>) -> Vec<UsbDevice> {
let mut output: Vec<UsbDevice> = Vec::new();

let usb: Vec<u16> = OsStr::new("USB\0").encode_wide().collect();
let dev_info = unsafe {
SetupDiGetClassDevsW(
null(),
usb.as_ptr(),
null_mut(),
DIGCF_ALLCLASSES | DIGCF_PRESENT,
)
};

let mut dev_info_data = SP_DEVINFO_DATA {
cbSize: size_of::<SP_DEVINFO_DATA>() as u32,
..Default::default()
// let usb: Vec<u16> = OsStr::new("USB\0").encode_wide().collect();
let usb = w!("USB\0");
let dev_info =
unsafe { SetupDiGetClassDevsW(null(), usb, -1, DIGCF_ALLCLASSES | DIGCF_PRESENT) };

let mut dev_info_data = unsafe {
SP_DEVINFO_DATA {
cbSize: size_of::<SP_DEVINFO_DATA>() as u32,
ClassGuid: zeroed(),
DevInst: zeroed(),
Reserved: zeroed(),
}
};

let mut i = 0;
Expand Down Expand Up @@ -58,6 +61,24 @@ pub fn enumerate_platform(vid: Option<u16>, pid: Option<u16>) -> Vec<UsbDevice>

buf = vec![0; 1000];

let mut class = None;
if unsafe {
SetupDiGetDeviceRegistryPropertyW(
dev_info,
&mut dev_info_data,
SPDRP_CLASS,
null_mut(),
buf.as_mut_ptr(),
buf.len() as u32,
null_mut(),
)
} > 0
{
class = Some(string_from_buf_u8(buf));
}

buf = vec![0; 1000];

if unsafe {
SetupDiGetDeviceRegistryPropertyW(
dev_info,
Expand Down Expand Up @@ -92,6 +113,7 @@ pub fn enumerate_platform(vid: Option<u16>, pid: Option<u16>) -> Vec<UsbDevice>
product_id,
description: Some(description),
serial_number,
class,
});
}
}
Expand Down Expand Up @@ -119,7 +141,7 @@ fn extract_vid_pid(buf: Vec<u8>) -> Result<(u16, u16), Box<dyn Error + Send + Sy
fn extract_serial_number(buf: Vec<u16>) -> Option<String> {
let id = string_from_buf_u16(buf);

id.split("\\").last().map(|s| s.to_owned())
id.split('\\').last().map(std::borrow::ToOwned::to_owned)
}

fn string_from_buf_u16(buf: Vec<u16>) -> String {
Expand All @@ -135,7 +157,6 @@ fn string_from_buf_u16(buf: Vec<u16>) -> String {
fn string_from_buf_u8(buf: Vec<u8>) -> String {
let str_vec: Vec<u16> = buf
.chunks_exact(2)
.into_iter()
.map(|a| u16::from_ne_bytes([a[0], a[1]]))
.collect();

Expand Down
Loading