Skip to content
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

linux: support getting usb port info without libudev #220

Merged
merged 6 commits into from
Oct 14, 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: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ project adheres to [Semantic Versioning](https://semver.org/).

* Add recommendation on how to interpret `UsbPortInfo::interface_number`.
[#219](https://github.com/serialport/serialport-rs/pull/219)
* Add support for retrieving USB port info on Linux without libudev.
[#220](https://github.com/serialport/serialport-rs/pull/220)

### Changed

Expand Down
40 changes: 23 additions & 17 deletions examples/list_ports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,52 @@ use serialport::{available_ports, SerialPortType};

fn main() {
match available_ports() {
Ok(ports) => {
Ok(mut ports) => {
// Let's output ports in a stable order to facilitate comparing the output from
// different runs (on different platforms, with different features, ...).
ports.sort_by_key(|i| i.port_name.clone());

match ports.len() {
0 => println!("No ports found."),
1 => println!("Found 1 port:"),
n => println!("Found {} ports:", n),
};

for p in ports {
println!(" {}", p.port_name);
println!(" {}", p.port_name);
match p.port_type {
SerialPortType::UsbPort(info) => {
println!(" Type: USB");
println!(" VID:{:04x} PID:{:04x}", info.vid, info.pid);
println!(" Type: USB");
println!(" VID: {:04x}", info.vid);
println!(" PID: {:04x}", info.pid);
#[cfg(feature = "usbportinfo-interface")]
println!(
" Interface: {}",
info.interface
.as_ref()
.map_or("".to_string(), |x| format!("{:02x}", *x))
);
println!(
" Serial Number: {}",
" Serial Number: {}",
info.serial_number.as_ref().map_or("", String::as_str)
);
println!(
" Manufacturer: {}",
" Manufacturer: {}",
info.manufacturer.as_ref().map_or("", String::as_str)
);
println!(
" Product: {}",
" Product: {}",
info.product.as_ref().map_or("", String::as_str)
);
#[cfg(feature = "usbportinfo-interface")]
println!(
" Interface: {}",
info.interface
.as_ref()
.map_or("".to_string(), |x| format!("{:02x}", *x))
);
}
SerialPortType::BluetoothPort => {
println!(" Type: Bluetooth");
println!(" Type: Bluetooth");
}
SerialPortType::PciPort => {
println!(" Type: PCI");
println!(" Type: PCI");
}
SerialPortType::Unknown => {
println!(" Type: Unknown");
println!(" Type: Unknown");
}
}
}
Expand Down
64 changes: 56 additions & 8 deletions src/posix/enumerate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,7 @@ cfg_if! {
target_os = "macos"
))]
use crate::SerialPortType;
#[cfg(any(
target_os = "ios",
all(target_os = "linux", not(target_env = "musl"), feature = "libudev"),
target_os = "macos"
))]
#[cfg(any(target_os = "ios", target_os = "linux", target_os = "macos"))]
use crate::UsbPortInfo;
#[cfg(any(
target_os = "android",
Expand Down Expand Up @@ -538,11 +534,61 @@ cfg_if! {
use std::io::Read;
use std::path::Path;

fn read_file_to_trimmed_string(dir: &Path, file: &str) -> Option<String> {
let path = dir.join(file);
let mut s = String::new();
File::open(path).ok()?.read_to_string(&mut s).ok()?;
Some(s.trim().to_owned())
}

fn read_file_to_u16(dir: &Path, file: &str) -> Option<u16> {
u16::from_str_radix(&read_file_to_trimmed_string(dir, file)?, 16).ok()
}

#[cfg(feature = "usbportinfo-interface")]
fn read_file_to_u8(dir: &Path, file: &str) -> Option<u8> {
u8::from_str_radix(&read_file_to_trimmed_string(dir, file)?, 16).ok()
}

fn read_usb_port_info(device_path: &Path) -> Option<SerialPortType> {
let device_path = device_path
.canonicalize()
.ok()?;
let subsystem = device_path.join("subsystem").canonicalize().ok()?;
let subsystem = subsystem.file_name()?.to_string_lossy();

let usb_interface_path = if subsystem == "usb-serial" {
device_path.parent()?
} else if subsystem == "usb" {
&device_path
} else {
return None;
};
let usb_device_path = usb_interface_path.parent()?;

let vid = read_file_to_u16(&usb_device_path, &"idVendor")?;
let pid = read_file_to_u16(&usb_device_path, &"idProduct")?;
#[cfg(feature = "usbportinfo-interface")]
let interface = read_file_to_u8(&usb_interface_path, &"bInterfaceNumber");
let serial_number = read_file_to_trimmed_string(&usb_device_path, &"serial");
let product = read_file_to_trimmed_string(&usb_device_path, &"product");
let manufacturer = read_file_to_trimmed_string(&usb_device_path, &"manufacturer");
Some(SerialPortType::UsbPort(UsbPortInfo {
vid,
pid,
serial_number,
manufacturer,
product,
#[cfg(feature = "usbportinfo-interface")]
interface,
}))
}

/// Scans `/sys/class/tty` for serial devices (on Linux systems without libudev).
pub fn available_ports() -> Result<Vec<SerialPortInfo>> {
let mut vec = Vec::new();
let sys_path = Path::new("/sys/class/tty/");
let device_path = Path::new("/dev");
let dev_path = Path::new("/dev");
let mut s;
for path in sys_path.read_dir().expect("/sys/class/tty/ doesn't exist on this system") {
let raw_path = path?.path().clone();
Expand All @@ -553,6 +599,8 @@ cfg_if! {
continue;
}

let port_type = read_usb_port_info(&path).unwrap_or(SerialPortType::Unknown);

path.push("driver_override");
if path.is_file() {
s = String::new();
Expand All @@ -568,14 +616,14 @@ cfg_if! {
//
// See https://github.com/serialport/serialport-rs/issues/66 for details.
if let Some(file_name) = raw_path.file_name() {
let device_file = device_path.join(file_name);
let device_file = dev_path.join(file_name);
if !device_file.exists() {
continue;
}

vec.push(SerialPortInfo {
port_name: device_file.to_string_lossy().to_string(),
port_type: SerialPortType::Unknown,
port_type,
});
}
}
Expand Down
Loading