sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::fs::File;
use std::io::Read;
use std::path::Path;

use super::ComponentInner;

pub(super) fn get_file_line(file: &Path, capacity: usize) -> Option<String> {
    let mut reader = String::with_capacity(capacity);
    let mut f = File::open(file).ok()?;
    f.read_to_string(&mut reader).ok()?;
    reader.truncate(reader.trim_end().len());
    Some(reader)
}

/// Primarily designed for reading an `i32` or `u32` (a `c_long`) from a `/sys/class/hwmon` sysfs file.
pub(super) fn read_number_from_file<N>(file: &Path) -> Option<N>
where
    N: std::str::FromStr,
{
    let mut reader = [0u8; 32];
    let mut f = File::open(file).ok()?;
    let n = f.read(&mut reader).ok()?;
    // Parsing and trimming would complain about `\0`.
    let number = &reader[..n];
    let number = std::str::from_utf8(number).ok()?;
    let number = number.trim();
    // Assert that the string has been cleaned.
    if cfg!(feature = "debug") {
        assert!(!number.contains('\n') && !number.contains('\0'));
    }
    number.parse().ok()
}

// Read a temperature from a `tempN_item` sensor in sysfs.
#[inline]
pub(super) fn get_temperature_from_file(file: &Path) -> Option<f32> {
    let temp = read_number_from_file(file);
    convert_temp_celsius(temp)
}

/// Takes a raw temperature in millidegrees Celsius and converts it to Celsius.
#[inline]
pub(super) fn convert_temp_celsius(temp: Option<i32>) -> Option<f32> {
    temp.map(|n| (n as f32) / 1000f32)
}

/// Information about a thermal sensor.
pub(super) enum ThermalSensorType {
    /// 1: CPU embedded diode
    CPUEmbeddedDiode,
    /// 2: 3904 transistor
    Transistor3904,
    /// 3: thermal diode
    ThermalDiode,
    /// 4: thermistor
    Thermistor,
    /// 5: AMD AMDSI
    AMDAMDSI,
    /// 6: Intel PECI
    IntelPECI,
    /// Not all types are supported by all chips, so space is kept for unknown sensors.
    #[allow(dead_code)]
    Unknown(u8),
}

impl From<u8> for ThermalSensorType {
    fn from(input: u8) -> Self {
        match input {
            0 => Self::CPUEmbeddedDiode,
            1 => Self::Transistor3904,
            3 => Self::ThermalDiode,
            4 => Self::Thermistor,
            5 => Self::AMDAMDSI,
            6 => Self::IntelPECI,
            n => Self::Unknown(n),
        }
    }
}

/// Check `item` and read the matching `file` with the correct parsing, storing the data in `component`.
pub(super) fn fill_component(
    component: &mut ComponentInner,
    item: &str,
    folder: &Path,
    file: &str,
) {
    let hwmon_file = folder.join(file);
    match item {
        "type" => {
            component.sensor_type =
                read_number_from_file::<u8>(&hwmon_file).map(ThermalSensorType::from)
        }
        "input" => {
            let temperature = get_temperature_from_file(&hwmon_file);
            component.input_file = Some(hwmon_file);
            component.temperature = temperature;
            // Try to get the maximum from `highest`; otherwise, use the current temperature.
            if component.max.is_none() {
                component.max = temperature;
            }
        }
        "label" => component.label = get_file_line(&hwmon_file, 10).unwrap_or_default(),
        "highest" => {
            component.max = get_temperature_from_file(&hwmon_file).or(component.temperature);
            component.highest_file = Some(hwmon_file);
        }
        // "max" => component.threshold_max = get_temperature_from_file(&hwmon_file), "min" => component.threshold_min = get_temperature_from_file(&hwmon_file),
        "crit" => component.threshold_critical = get_temperature_from_file(&hwmon_file),
        _ => {
            sinf_debug!(
                "This hwmon-temp file is still not supported! Contributions are appreciated.;) {:?}",
                hwmon_file,
            );
        }
    }
}