sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
// Information about the values readable from the `hwmon` sysfs interface.

use crate::{Component, Error};

use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::read_dir;
use std::path::{Path, PathBuf};

#[derive(Default)]
pub(crate) struct ComponentInner {
    /// Optional device associated with a `Component`.
    device_model: Option<String>,

    /// Identifier of a `Component`.
    id: Option<String>,

    /// Chip name.
    name: String,
    /// Current temperature.
    temperature: Option<f32>,
    /// Maximum value computed by `sinf`.
    max: Option<f32>,
    /// Critical threshold provided by the chip/kernel, as previously written by user space.
    threshold_critical: Option<f32>,
    /// Sensor type.
    sensor_type: Option<ThermalSensorType>,
    /// Component label.
    label: String,
    // Historical minimum temperature - Read in:`temp[1-*]_lowest
    input_file: Option<PathBuf>,
    /// `temp[1-*]_highest` file, read for the highest available value when present.
    highest_file: Option<PathBuf>,
    pub(crate) updated: bool,
}

impl ComponentInner {
    fn update_from(
        &mut self,
        Component {
            inner:
                ComponentInner {
                    temperature,
                    max,
                    input_file,
                    highest_file,
                    ..
                },
        }: Component,
    ) {
        if let Some(temp) = temperature {
            self.temperature = Some(temp);
        }
        match (max, self.max) {
            (Some(new_max), Some(old_max)) => self.max = Some(new_max.max(old_max)),
            (Some(max), None) => self.max = Some(max),
            _ => {}
        }
        if input_file.is_some() && input_file != self.input_file {
            self.input_file = input_file;
        }
        if highest_file.is_some() && highest_file != self.highest_file {
            self.highest_file = highest_file;
        }
        self.updated = true;
    }
}

// Read arbitrary data from sysfs.

mod helpers;

#[cfg(test)]
mod tests;

use self::helpers::*;

impl ComponentInner {
    /// Reads `hwmon` (hardware monitor) information from `folder`.
    fn from_hwmon(components: &mut Vec<Component>, folder: &Path) -> Option<()> {
        let dir = read_dir(folder).ok()?;
        let mut matchings: HashMap<u32, Component> = HashMap::with_capacity(10);
        for entry in dir.flatten() {
            if !entry.file_type().is_ok_and(|file_type| !file_type.is_dir()) {
                continue;
            }

            let entry = entry.path();
            let filename = entry.file_name().and_then(|x| x.to_str()).unwrap_or("");
            let Some((id, item)) = filename
                .strip_prefix("temp")
                .and_then(|f| f.split_once('_'))
                .and_then(|(id, item)| Some((id.parse::<u32>().ok()?, item)))
            else {
                continue;
            };

            let component = matchings.entry(id).or_insert_with(|| Component {
                inner: ComponentInner::default(),
            });
            let component = &mut component.inner;
            let name = get_file_line(&folder.join("name"), 16);
            let component_id = folder
                .file_name()
                .and_then(OsStr::to_str)
                .map(|f| format!("{f}_{id}"));
            component.name = name.unwrap_or_default();
            component.id = component_id;
            let device_model = get_file_line(&folder.join("device/model"), 16);
            component.device_model = device_model;
            fill_component(component, item, folder, filename);
        }
        for (id, mut new_comp) in matchings
            .into_iter()
            // Remove components without a `tempN_input` file.
            .filter(|(_, c)| c.inner.input_file.is_some())
        {
            // Compute the label from the known data.
            new_comp.inner.label = new_comp.inner.format_label("temp", id);
            if let Some(comp) = components
                .iter_mut()
                .find(|comp| comp.inner.label == new_comp.inner.label)
            {
                comp.inner.update_from(new_comp);
            } else {
                new_comp.inner.updated = true;
                components.push(new_comp);
            }
        }

        Some(())
    }

    /// Computes a label from the available information.
    fn format_label(&self, class: &str, id: u32) -> String {
        let ComponentInner {
            device_model,
            name,
            label,
            ..
        } = self;
        let has_label = !label.is_empty();
        match (has_label, device_model) {
            (true, Some(device_model)) => {
                format!("{name} {label} {device_model}")
            }
            (true, None) => format!("{name} {label}"),
            (false, Some(device_model)) => format!("{name} {device_model}"),
            (false, None) => format!("{name} {class}{id}"),
        }
    }

    pub(crate) fn temperature(&self) -> Option<f32> {
        self.temperature
    }

    pub(crate) fn max(&self) -> Option<f32> {
        self.max
    }

    pub(crate) fn critical(&self) -> Option<f32> {
        self.threshold_critical
    }

    pub(crate) fn label(&self) -> &str {
        &self.label
    }

    pub(crate) fn id(&self) -> Option<&str> {
        self.id.as_deref()
    }

    pub(crate) fn refresh(&mut self) {
        let current = self
            .input_file
            .as_ref()
            .and_then(|file| get_temperature_from_file(file.as_path()));
        // Try to read the kernel's highest value; otherwise, compute one from the temperature.
        let max = self
            .highest_file
            .as_ref()
            .and_then(|file| get_temperature_from_file(file.as_path()))
            .or(current);
        if let Some(new_max) = max {
            self.max = Some(self.max.map_or(new_max, |old_max| old_max.max(new_max)));
        }
        self.temperature = current;
    }
}

fn read_temp_dir<F: FnMut(PathBuf)>(path: &Path, starts_with: &str, mut f: F) {
    if let Ok(dir) = read_dir(path) {
        for entry in dir.flatten() {
            if !entry
                .file_name()
                .to_str()
                .unwrap_or("")
                .starts_with(starts_with)
            {
                continue;
            }
            let path = entry.path();
            if !path.is_file() {
                f(path);
            }
        }
    }
}

pub(crate) struct ComponentsInner {
    pub(crate) components: Vec<Component>,
}

impl ComponentsInner {
    pub(crate) fn new() -> Result<Self, Error> {
        Ok(Self {
            components: Vec::with_capacity(4),
        })
    }

    pub(crate) fn list(&self) -> &[Component] {
        &self.components
    }

    pub(crate) fn list_mut(&mut self) -> &mut [Component] {
        &mut self.components
    }

    pub(crate) fn refresh(&mut self) {
        self.refresh_from_sys_class_path(Path::new("/sys/class"));
    }

    fn refresh_from_sys_class_path(&mut self, path: &Path) {
        read_temp_dir(&path.join("hwmon"), "hwmon", |path| {
            ComponentInner::from_hwmon(&mut self.components, &path);
        });
        if self.components.iter().all(|c| !c.inner.updated) {
            // Normally used only by Raspberry Pi.
            read_temp_dir(&path.join("thermal"), "thermal_", |path| {
                let temp = path.join("temp");
                if temp.exists() {
                    let Some(name) = get_file_line(&path.join("type"), 16) else {
                        return;
                    };
                    let component_id = path.file_name().and_then(OsStr::to_str).map(str::to_string);
                    let mut component = ComponentInner {
                        name,
                        id: component_id,
                        ..Default::default()
                    };
                    fill_component(&mut component, "input", &path, "temp");
                    if let Some(comp) = self
                        .components
                        .iter_mut()
                        .find(|comp| comp.inner.id == component.id)
                    {
                        comp.inner.update_from(Component { inner: component });
                    } else {
                        component.updated = true;
                        self.components.push(Component { inner: component });
                    }
                }
            });
        }
    }
}