use super::traits::*;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
pub struct LinuxSensor {
hwmon_path: PathBuf,
chip_name: String,
}
impl LinuxSensor {
pub fn new(hwmon_path: PathBuf) -> Result<Self, Error> {
let name_path = hwmon_path.join("name");
let chip_name = fs::read_to_string(&name_path)
.map_err(|e| Error::InitializationFailed(format!("Failed to read sensor name: {}", e)))?
.trim()
.to_string();
Ok(Self {
hwmon_path,
chip_name,
})
}
fn read_input(&self, pattern: &str, index: u32) -> Option<i64> {
let path = self.hwmon_path.join(format!("{}{}_input", pattern, index));
fs::read_to_string(path).ok()?.trim().parse::<i64>().ok()
}
fn read_label(&self, pattern: &str, index: u32) -> Option<String> {
let path = self.hwmon_path.join(format!("{}{}_label", pattern, index));
fs::read_to_string(path).ok().map(|s| s.trim().to_string())
}
fn read_max(&self, pattern: &str, index: u32) -> Option<i64> {
let path = self.hwmon_path.join(format!("{}{}_max", pattern, index));
fs::read_to_string(path).ok()?.trim().parse::<i64>().ok()
}
fn read_crit(&self, pattern: &str, index: u32) -> Option<i64> {
let path = self.hwmon_path.join(format!("{}{}_crit", pattern, index));
fs::read_to_string(path).ok()?.trim().parse::<i64>().ok()
}
fn classify_sensor(label: &str) -> SensorType {
let label_lower = label.to_lowercase();
if label_lower.contains("cpu")
|| label_lower.contains("core")
|| label_lower.contains("package")
{
SensorType::Cpu
} else if label_lower.contains("chipset") || label_lower.contains("pch") {
SensorType::Chipset
} else if label_lower.contains("vrm") || label_lower.contains("vcore") {
SensorType::Vrm
} else if label_lower.contains("ambient") || label_lower.contains("system") {
SensorType::Ambient
} else if label_lower.contains("m.2") || label_lower.contains("nvme") {
SensorType::M2Slot
} else {
SensorType::Other
}
}
}
impl MotherboardDevice for LinuxSensor {
#[allow(clippy::misnamed_getters)]
fn name(&self) -> &str {
&self.chip_name
}
fn device_path(&self) -> Option<String> {
Some(self.hwmon_path.to_string_lossy().to_string())
}
fn temperature_sensors(&self) -> Result<Vec<TemperatureSensor>, Error> {
let mut sensors = Vec::new();
for i in 1..=32 {
if let Some(temp_millic) = self.read_input("temp", i) {
let label = self
.read_label("temp", i)
.unwrap_or_else(|| format!("temp{}", i));
let temperature = temp_millic as f32 / 1000.0;
let max = self.read_max("temp", i).map(|v| v as f32 / 1000.0);
let critical = self.read_crit("temp", i).map(|v| v as f32 / 1000.0);
let sensor_type = Self::classify_sensor(&label);
sensors.push(TemperatureSensor {
label,
temperature: Some(temperature),
max,
critical,
sensor_type,
});
}
}
Ok(sensors)
}
fn voltage_rails(&self) -> Result<Vec<VoltageRail>, Error> {
let mut rails = Vec::new();
for i in 0..=32 {
if let Some(voltage_milliv) = self.read_input("in", i) {
let label = self
.read_label("in", i)
.unwrap_or_else(|| format!("in{}", i));
let voltage = voltage_milliv as f32 / 1000.0;
let min = self.read_max("in", i).map(|v| v as f32 / 1000.0);
let max = self.read_crit("in", i).map(|v| v as f32 / 1000.0);
rails.push(VoltageRail {
label,
voltage: Some(voltage),
min,
max,
});
}
}
Ok(rails)
}
fn fans(&self) -> Result<Vec<FanInfo>, Error> {
let mut fans = Vec::new();
for i in 1..=16 {
if let Some(rpm) = self.read_input("fan", i) {
let label = self
.read_label("fan", i)
.unwrap_or_else(|| format!("fan{}", i));
let pwm_path = self.hwmon_path.join(format!("pwm{}", i));
let pwm = fs::read_to_string(&pwm_path)
.ok()
.and_then(|s| s.trim().parse::<u8>().ok());
let pwm_enable_path = self.hwmon_path.join(format!("pwm{}_enable", i));
let controllable = match fs::metadata(&pwm_enable_path) {
Ok(m) => Some(!m.permissions().readonly()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(false),
Err(_) => None,
};
let rpm_value = if rpm > 0 { Some(rpm as u32) } else { None };
fans.push(FanInfo {
label,
rpm: rpm_value,
pwm,
min_rpm: None,
max_rpm: None,
controllable,
});
}
}
Ok(fans)
}
fn set_fan_speed(&self, fan_index: usize, speed: FanControl) -> Result<(), Error> {
let pwm_path = self.hwmon_path.join(format!("pwm{}", fan_index + 1));
let pwm_enable_path = self.hwmon_path.join(format!("pwm{}_enable", fan_index + 1));
if !pwm_path.exists() {
return Err(Error::FanControlError(format!(
"Fan {} does not support PWM control",
fan_index
)));
}
match speed {
FanControl::Manual(pwm_value) => {
fs::write(&pwm_enable_path, "1\n").map_err(|e| {
Error::PermissionDenied(format!("Failed to set fan mode: {}", e))
})?;
fs::write(&pwm_path, format!("{}\n", pwm_value)).map_err(|e| {
Error::PermissionDenied(format!("Failed to set fan speed: {}", e))
})?;
}
FanControl::Automatic => {
fs::write(&pwm_enable_path, "2\n").map_err(|e| {
Error::PermissionDenied(format!("Failed to set fan mode: {}", e))
})?;
}
}
Ok(())
}
}
pub fn enumerate() -> Result<Vec<Box<dyn MotherboardDevice>>, Error> {
let hwmon_dir = Path::new("/sys/class/hwmon");
if !hwmon_dir.exists() {
return Err(Error::NoSensorsFound);
}
let mut devices: Vec<Box<dyn MotherboardDevice>> = Vec::new();
for entry in fs::read_dir(hwmon_dir).map_err(Error::IoError)? {
let entry = entry.map_err(Error::IoError)?;
let path = entry.path();
if !path.is_dir() {
continue;
}
if let Ok(sensor) = LinuxSensor::new(path) {
devices.push(Box::new(sensor));
}
}
if devices.is_empty() {
Err(Error::NoSensorsFound)
} else {
Ok(devices)
}
}
fn read_dmi(path: &str) -> Option<String> {
fs::read_to_string(Path::new("/sys/class/dmi/id").join(path))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
fn detect_firmware_type() -> FirmwareType {
if Path::new("/sys/firmware/efi").exists() {
FirmwareType::Uefi
} else if Path::new("/sys/firmware").exists() {
FirmwareType::Bios
} else {
FirmwareType::Unknown
}
}
fn machine_architecture() -> Option<String> {
let mut buf: libc::utsname = unsafe { std::mem::zeroed() };
if unsafe { libc::uname(&mut buf) } != 0 {
return None;
}
let bytes: Vec<u8> = buf
.machine
.iter()
.take_while(|&&c| c != 0)
.map(|&c| c as u8)
.collect();
String::from_utf8(bytes).ok().filter(|s| !s.is_empty())
}
pub fn get_system_info() -> Result<SystemInfo, Error> {
let os_release = fs::read_to_string("/etc/os-release")
.or_else(|_| fs::read_to_string("/usr/lib/os-release"))
.unwrap_or_default();
let mut os_info = HashMap::new();
for line in os_release.lines() {
if let Some((key, value)) = line.split_once('=') {
os_info.insert(key.to_string(), value.trim_matches('"').to_string());
}
}
let os_name = os_info
.get("PRETTY_NAME")
.or_else(|| os_info.get("NAME"))
.filter(|s| !s.is_empty())
.cloned();
let os_version = ["VERSION", "VERSION_ID"]
.iter()
.filter_map(|key| os_info.get(*key))
.find(|v| !v.is_empty())
.cloned();
let kernel_version = fs::read_to_string("/proc/version")
.ok()
.and_then(|v| v.split_whitespace().nth(2).map(String::from));
let architecture = machine_architecture();
let hostname = fs::read_to_string("/etc/hostname")
.ok()
.map(|s| s.trim().to_string());
let bios = BiosInfo {
vendor: read_dmi("bios_vendor"),
version: read_dmi("bios_version"),
release_date: read_dmi("bios_date"),
revision: None,
firmware_type: detect_firmware_type(),
secure_boot: None, };
let manufacturer = read_dmi("sys_vendor");
let product_name = read_dmi("product_name");
let serial_number = read_dmi("product_serial");
let uuid = read_dmi("product_uuid");
let board_vendor = read_dmi("board_vendor");
let board_name = read_dmi("board_name");
let board_version = read_dmi("board_version");
let cpuinfo = fs::read_to_string("/proc/cpuinfo").unwrap_or_default();
let cpu_name = cpuinfo
.lines()
.find(|line| line.starts_with("model name"))
.and_then(|line| line.split(':').nth(1))
.map(|s| s.trim().to_string());
let cpu_cores = cpuinfo
.lines()
.find(|line| line.starts_with("cpu cores"))
.and_then(|line| line.split(':').nth(1))
.and_then(|s| s.trim().parse::<u32>().ok());
let cpu_threads = cpuinfo
.lines()
.filter(|line| line.starts_with("processor"))
.count() as u32;
let cpu_threads = if cpu_threads > 0 {
Some(cpu_threads)
} else {
None
};
Ok(SystemInfo {
os_name,
os_version,
kernel_version,
architecture,
hostname,
bios,
manufacturer,
product_name,
serial_number,
uuid,
board_vendor,
board_name,
board_version,
cpu_name,
cpu_cores,
cpu_threads,
})
}
pub fn get_driver_versions() -> Result<Vec<DriverInfo>, Error> {
let mut drivers = Vec::new();
if let Ok(version) = fs::read_to_string("/sys/module/nvidia/version") {
drivers.push(DriverInfo {
name: "nvidia".to_string(),
version: (!version.trim().is_empty()).then(|| version.trim().to_string()),
driver_type: DriverType::Gpu,
description: Some("NVIDIA GPU Driver".to_string()),
vendor: Some("NVIDIA".to_string()),
date: None,
});
}
if let Ok(version) = fs::read_to_string("/sys/module/amdgpu/version") {
drivers.push(DriverInfo {
name: "amdgpu".to_string(),
version: (!version.trim().is_empty()).then(|| version.trim().to_string()),
driver_type: DriverType::Gpu,
description: Some("AMD GPU Driver".to_string()),
vendor: Some("AMD".to_string()),
date: None,
});
}
if let Ok(version) = fs::read_to_string("/sys/module/i915/version") {
drivers.push(DriverInfo {
name: "i915".to_string(),
version: (!version.trim().is_empty()).then(|| version.trim().to_string()),
driver_type: DriverType::Gpu,
description: Some("Intel GPU Driver".to_string()),
vendor: Some("Intel".to_string()),
date: None,
});
}
for module in &["nvme", "ahci", "sata_nv", "megaraid_sas"] {
let version_path = format!("/sys/module/{}/version", module);
if let Ok(version) = fs::read_to_string(&version_path) {
drivers.push(DriverInfo {
name: module.to_string(),
version: (!version.trim().is_empty()).then(|| version.trim().to_string()),
driver_type: DriverType::Storage,
description: Some(format!("{} Storage Driver", module.to_uppercase())),
vendor: None,
date: None,
});
}
}
for module in &["e1000e", "igb", "ixgbe", "r8169", "bnx2x"] {
let version_path = format!("/sys/module/{}/version", module);
if let Ok(version) = fs::read_to_string(&version_path) {
drivers.push(DriverInfo {
name: module.to_string(),
version: (!version.trim().is_empty()).then(|| version.trim().to_string()),
driver_type: DriverType::Network,
description: Some(format!("{} Network Driver", module.to_uppercase())),
vendor: None,
date: None,
});
}
}
Ok(drivers)
}
pub fn get_pcie_devices() -> Result<Vec<PcieDeviceInfo>, Error> {
let pci_dir = Path::new("/sys/bus/pci/devices");
if !pci_dir.exists() {
return Ok(Vec::new());
}
let mut devices = Vec::new();
for entry in fs::read_dir(pci_dir).map_err(Error::IoError)? {
let entry = entry.map_err(Error::IoError)?;
let path = entry.path();
if !path.is_dir() {
continue;
}
let bus_id = entry.file_name().to_string_lossy().to_string();
let class = fs::read_to_string(path.join("class"))
.ok()
.map(|s| s.trim().to_string());
let vendor_id = fs::read_to_string(path.join("vendor"))
.ok()
.map(|s| s.trim().to_string());
let device_id = fs::read_to_string(path.join("device"))
.ok()
.map(|s| s.trim().to_string());
let device_class = class.as_deref().and_then(classify_pci_class);
let current_link_speed = fs::read_to_string(path.join("current_link_speed"))
.ok()
.map(|s| s.trim().to_string());
let current_link_width = fs::read_to_string(path.join("current_link_width"))
.ok()
.and_then(|s| s.trim().parse::<u8>().ok());
let pcie_version = current_link_speed.as_deref().and_then(|s| {
let rate = s.split_whitespace().next().unwrap_or("");
match rate {
"2.5" => Some("PCIe 1.0".to_string()),
"5" | "5.0" => Some("PCIe 2.0".to_string()),
"8" | "8.0" => Some("PCIe 3.0".to_string()),
"16" | "16.0" => Some("PCIe 4.0".to_string()),
"32" | "32.0" => Some("PCIe 5.0".to_string()),
"64" | "64.0" => Some("PCIe 6.0".to_string()),
_ => None,
}
});
let name = fs::read_to_string(path.join("label"))
.ok()
.map(|s| s.trim().to_string())
.unwrap_or_else(|| {
format!(
"PCI {} ({})",
bus_id,
device_class.as_deref().unwrap_or("Unknown")
)
});
devices.push(PcieDeviceInfo {
name,
device_id,
vendor: vendor_id,
pcie_version,
link_width: current_link_width,
link_speed: current_link_speed,
slot: Some(bus_id),
device_class,
});
}
Ok(devices)
}
fn classify_pci_class(class_hex: &str) -> Option<String> {
let class_code = u32::from_str_radix(class_hex.trim_start_matches("0x"), 16).ok()?;
let class_id = (class_code >> 16) & 0xFF;
Some(match class_id {
0x00 => "Unclassified".to_string(),
0x01 => "Storage".to_string(),
0x02 => "Network".to_string(),
0x03 => "Display/VGA".to_string(),
0x04 => "Multimedia".to_string(),
0x05 => "Memory".to_string(),
0x06 => "Bridge".to_string(),
0x07 => "Communication".to_string(),
0x08 => "System Peripheral".to_string(),
0x09 => "Input Device".to_string(),
0x0A => "Docking Station".to_string(),
0x0B => "Processor".to_string(),
0x0C => "Serial Bus".to_string(),
0x0D => "Wireless".to_string(),
0x0E => "Intelligent I/O".to_string(),
0x0F => "Satellite Communication".to_string(),
0x10 => "Encryption/Decryption".to_string(),
0x11 => "Signal Processing".to_string(),
0x12 => "Processing Accelerator".to_string(),
0x13 => "Non-Essential Instrumentation".to_string(),
0x40 => "Co-Processor".to_string(),
_ => format!("Class 0x{:02X}", class_id),
})
}
pub fn get_sata_devices() -> Result<Vec<SataDeviceInfo>, Error> {
let block_dir = Path::new("/sys/class/block");
if !block_dir.exists() {
return Ok(Vec::new());
}
let mut devices = Vec::new();
for entry in fs::read_dir(block_dir).map_err(Error::IoError)? {
let entry = entry.map_err(Error::IoError)?;
let name = entry.file_name().to_string_lossy().to_string();
if name.contains('p') && name.starts_with("nvme") {
continue; }
if name.chars().last().is_some_and(|c| c.is_ascii_digit()) && !name.starts_with("nvme") {
let base: String = name.chars().take_while(|c| !c.is_ascii_digit()).collect();
if base.len() < name.len()
&& (base.starts_with("sd") || base.starts_with("hd") || base.starts_with("vd"))
{
continue;
}
}
let path = entry.path();
let device_path = path.join("device");
if name.starts_with("loop") || name.starts_with("ram") || name.starts_with("dm-") {
continue;
}
let model = fs::read_to_string(device_path.join("model"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let serial = fs::read_to_string(device_path.join("serial"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let firmware = fs::read_to_string(device_path.join("firmware_rev"))
.or_else(|_| fs::read_to_string(device_path.join("rev")))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let capacity_gb = fs::read_to_string(path.join("size"))
.ok()
.and_then(|s| s.trim().parse::<u64>().ok())
.map(|sectors| (sectors * 512) as f64 / (1024.0 * 1024.0 * 1024.0));
let rotation = fs::read_to_string(path.join("queue/rotational"))
.ok()
.and_then(|s| s.trim().parse::<u32>().ok());
let media_type = match rotation {
Some(0) => SataMediaType::Ssd,
Some(1) => SataMediaType::Hdd,
_ => SataMediaType::Unknown,
};
let temperature = fs::read_dir(device_path.join("hwmon"))
.ok()
.and_then(|mut entries| entries.next())
.and_then(|entry| entry.ok())
.and_then(|entry| {
fs::read_to_string(entry.path().join("temp1_input"))
.ok()
.and_then(|s| s.trim().parse::<f32>().ok())
.map(|t| t / 1000.0)
});
let ata_port = fs::canonicalize(&path).ok().and_then(|p| ata_port_of(&p));
let interface_speed = if name.starts_with("nvme") {
Some("NVMe".to_string())
} else {
ata_port
.and_then(|n| {
fs::read_to_string(format!("/sys/class/ata_link/link{n}/sata_spd")).ok()
})
.map(|s| {
let s = s.trim();
match s {
"6.0 Gbps" | "6" => "SATA III (6 Gbps)".to_string(),
"3.0 Gbps" | "3" => "SATA II (3 Gbps)".to_string(),
"1.5 Gbps" | "1.5" => "SATA I (1.5 Gbps)".to_string(),
_ => format!("SATA ({})", s),
}
})
};
devices.push(SataDeviceInfo {
name,
model,
serial,
firmware,
capacity_gb,
interface_speed,
port: ata_port.and_then(|n| u8::try_from(n).ok()),
temperature,
media_type,
});
}
Ok(devices)
}
fn ata_port_of(path: &Path) -> Option<u32> {
path.components().find_map(|c| {
c.as_os_str()
.to_str()?
.strip_prefix("ata")?
.parse::<u32>()
.ok()
})
}
pub fn get_system_temperatures() -> Result<SystemTemperatures, Error> {
let sensors = enumerate()?;
let mut cpu_temp: Option<f32> = None;
let mut mb_temp: Option<f32> = None;
let mut storage_temps: Vec<(String, f32)> = Vec::new();
for sensor in &sensors {
if let Ok(temp_sensors) = sensor.temperature_sensors() {
for ts in &temp_sensors {
match ts.sensor_type {
SensorType::Cpu => {
if let Some(celsius) = ts.temperature {
if cpu_temp.is_none_or(|t| celsius > t) {
cpu_temp = Some(celsius);
}
}
}
SensorType::Chipset | SensorType::Ambient | SensorType::Vrm => {
if let Some(celsius) = ts.temperature {
if mb_temp.is_none_or(|t| celsius > t) {
mb_temp = Some(celsius);
}
}
}
SensorType::M2Slot => {
if let Some(celsius) = ts.temperature {
storage_temps.push((ts.label.clone(), celsius));
}
}
_ => {}
}
}
}
}
let block_dir = Path::new("/sys/class/block");
if block_dir.exists() {
if let Ok(entries) = fs::read_dir(block_dir) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with("sd") || name.starts_with("nvme") {
let hwmon_path = entry.path().join("device/hwmon");
if let Ok(mut hwmon_entries) = fs::read_dir(&hwmon_path) {
if let Some(Ok(hwmon_entry)) = hwmon_entries.next() {
if let Ok(temp_str) =
fs::read_to_string(hwmon_entry.path().join("temp1_input"))
{
if let Ok(temp_millic) = temp_str.trim().parse::<f32>() {
let temp_c = temp_millic / 1000.0;
if temp_c > 0.0 && temp_c < 150.0 {
storage_temps.push((name, temp_c));
}
}
}
}
}
}
}
}
}
Ok(SystemTemperatures {
cpu: cpu_temp,
gpu: None, motherboard: mb_temp,
storage: storage_temps,
network: Vec::new(),
})
}
pub fn get_peripherals() -> Result<PeripheralsInfo, Error> {
let mut info = PeripheralsInfo::default();
let usb_dir = Path::new("/sys/bus/usb/devices");
if usb_dir.exists() {
if let Ok(entries) = fs::read_dir(usb_dir) {
for entry in entries.flatten() {
let path = entry.path();
let name_str = entry.file_name().to_string_lossy().to_string();
if name_str.contains(':') {
continue; }
let product = fs::read_to_string(path.join("product"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let manufacturer = fs::read_to_string(path.join("manufacturer"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let vendor_id = fs::read_to_string(path.join("idVendor"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let product_id = fs::read_to_string(path.join("idProduct"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let speed = fs::read_to_string(path.join("speed"))
.ok()
.and_then(|s| s.trim().parse::<u32>().ok());
let dev_class = fs::read_to_string(path.join("bDeviceClass"))
.ok()
.map(|s| s.trim().to_string());
if dev_class.as_deref() == Some("09") {
continue; }
let name = product.unwrap_or_else(|| format!("USB Device {}", name_str));
let usb_version = match speed {
Some(s) if s >= 10000 => UsbVersion::Usb3_1,
Some(s) if s >= 5000 => UsbVersion::Usb3_0,
Some(s) if s >= 480 => UsbVersion::Usb2_0,
Some(s) if s >= 12 => UsbVersion::Usb1_1,
_ => UsbVersion::Unknown,
};
info.usb_devices.push(UsbDeviceInfo {
name,
device_id: None,
vendor: manufacturer,
product_id,
vendor_id,
usb_version,
device_class: dev_class,
status: Some("Connected".to_string()),
hub_port: None,
});
}
}
}
let drm_dir = Path::new("/sys/class/drm");
if drm_dir.exists() {
if let Ok(entries) = fs::read_dir(drm_dir) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if !name.contains('-') || name == "version" {
continue;
}
let status = fs::read_to_string(entry.path().join("status"))
.ok()
.map(|s| s.trim().to_string());
let output_type = if name.contains("HDMI") {
DisplayOutputType::Hdmi
} else if name.contains("eDP") {
DisplayOutputType::Internal
} else if name.contains("DP") || name.contains("DisplayPort") {
DisplayOutputType::DisplayPort
} else if name.contains("VGA") {
DisplayOutputType::Vga
} else if name.contains("DVI") {
DisplayOutputType::Dvi
} else {
DisplayOutputType::Unknown
};
info.display_outputs.push(DisplayOutputInfo {
name: name.clone(),
output_type,
connected: status.as_deref() == Some("connected"),
resolution: None,
refresh_rate: None,
adapter: None,
});
}
}
}
if let Ok(content) = fs::read_to_string("/proc/asound/cards") {
for line in content.lines() {
let line = line.trim();
if line.starts_with(|c: char| c.is_ascii_digit()) {
let parts: Vec<&str> = line.splitn(2, ':').collect();
if parts.len() == 2 {
let name = parts[1].trim().to_string();
let pcm_names: Vec<String> = line
.split_whitespace()
.next()
.and_then(|n| n.parse::<u32>().ok())
.and_then(|card| fs::read_dir(format!("/proc/asound/card{card}")).ok())
.into_iter()
.flatten()
.flatten()
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
info.audio_devices.push(AudioDeviceInfo {
name,
device_type: alsa_card_type(pcm_names.iter().map(String::as_str)),
manufacturer: None,
status: Some("Available".to_string()),
is_default: false,
});
}
}
}
}
let bt_dir = Path::new("/sys/class/bluetooth");
if bt_dir.exists() {
if let Ok(entries) = fs::read_dir(bt_dir) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
let address = fs::read_to_string(entry.path().join("address"))
.ok()
.map(|s| s.trim().to_string());
info.bluetooth_devices.push(BluetoothDeviceInfo {
name: format!("Bluetooth Adapter ({})", name),
address,
connected: true,
device_type: Some("Adapter".to_string()),
paired: false,
});
}
}
}
let net_dir = Path::new("/sys/class/net");
if net_dir.exists() {
if let Ok(entries) = fs::read_dir(net_dir) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if name == "lo" {
continue; }
let speed = fs::read_to_string(entry.path().join("speed"))
.ok()
.and_then(|s| s.trim().parse::<u32>().ok());
let operstate = fs::read_to_string(entry.path().join("operstate"))
.ok()
.map(|s| s.trim().to_string());
let port_type = if name.starts_with("wl") || name.starts_with("wlan") {
NetworkPortType::WiFi
} else if name.starts_with("eth") || name.starts_with("en") {
NetworkPortType::Ethernet
} else {
NetworkPortType::Other
};
info.network_ports.push(NetworkPortInfo {
name,
port_type,
speed: speed.map(|mbps| format!("{mbps} Mb/s")),
connected: match operstate.as_deref() {
Some("up") => Some(true),
Some("down" | "lowerlayerdown") => Some(false),
_ => None,
},
mac_address: fs::read_to_string(entry.path().join("address"))
.ok()
.map(|s| s.trim().to_string()),
});
}
}
}
Ok(info)
}
fn alsa_card_type<'a>(entries: impl IntoIterator<Item = &'a str>) -> Option<AudioDeviceType> {
let mut playback = false;
let mut capture = false;
for entry in entries {
let Some(rest) = entry.strip_prefix("pcm") else {
continue;
};
let Some(direction) = rest.chars().last() else {
continue;
};
let digits = &rest[..rest.len() - direction.len_utf8()];
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
continue;
}
match direction {
'p' => playback = true,
'c' => capture = true,
_ => {}
}
}
match (playback, capture) {
(true, true) => Some(AudioDeviceType::OutputInput),
(true, false) => Some(AudioDeviceType::Output),
(false, true) => Some(AudioDeviceType::Input),
(false, false) => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_card_is_its_directions_from_any_pcm_number() {
assert_eq!(
alsa_card_type(["pcm0p", "pcm3p", "pcm0c"]),
Some(AudioDeviceType::OutputInput)
);
assert_eq!(alsa_card_type(["pcm7p"]), Some(AudioDeviceType::Output));
assert_eq!(alsa_card_type(["pcm0c"]), Some(AudioDeviceType::Input));
}
#[test]
fn a_card_with_no_pcm_entries_has_no_direction() {
assert_eq!(alsa_card_type(std::iter::empty()), None);
assert_eq!(alsa_card_type(["id", "pcmp", "pcmx"]), None);
}
#[test]
fn ata_port_comes_from_the_disks_own_sysfs_path() {
let sda = Path::new(
"/sys/devices/pci0000:00/0000:00:17.0/ata3/host2/target2:0:0/2:0:0:0/block/sda",
);
assert_eq!(ata_port_of(sda), Some(3));
let usb = Path::new("/sys/devices/pci0000:00/0000:00:14.0/usb2/2-1/host6/block/sdb");
assert_eq!(ata_port_of(usb), None);
}
}