libmedium/sensors/
mod.rs

1//! Module containing the sensors and their functionality.
2
3#[cfg(feature = "sync")]
4pub mod sync_sensors;
5
6#[cfg(feature = "async")]
7pub mod async_sensors;
8
9mod error;
10mod subfunction_type;
11
12use std::path::{Path, PathBuf};
13
14pub use error::Error;
15pub use subfunction_type::SensorSubFunctionType;
16
17/// Base trait that all sensors must implement.
18/// It contains the functionality to get a sensor's base, index or supported subfunctions.
19pub trait Sensor {
20    /// Returns this sensor's base like "temp" or "fan".
21    fn static_base() -> &'static str where Self: Sized;
22
23    /// Returns this sensor's base like "temp" or "fan".
24    fn base(&self) -> &'static str;
25
26    /// Returns this sensor's index.
27    fn index(&self) -> u16;
28
29    /// Returns this sensor's hwmon's path.
30    fn hwmon_path(&self) -> &Path;
31
32    /// Returns a list of all readable subfunction types supported by this sensor.
33    fn supported_read_sub_functions(&self) -> Vec<SensorSubFunctionType> {
34        SensorSubFunctionType::read_list()
35            .filter(|&s| {
36                std::fs::OpenOptions::new()
37                    .read(true)
38                    .open(self.subfunction_path(s))
39                    .is_ok()
40            })
41            .collect()
42    }
43
44    /// Returns the path this sensor's subfunction of the given type would have.
45    fn subfunction_path(&self, sub_type: SensorSubFunctionType) -> PathBuf {
46        self.hwmon_path().join(format!(
47            "{}{}{}",
48            self.base(),
49            self.index(),
50            sub_type.to_suffix()
51        ))
52    }
53}
54
55/// A struct that represents the state of all writeable subfunctions of a sensor.
56/// It can be used to reset a sensor to a previous state or copy its settings to another sensor.
57#[derive(Debug, Clone, PartialEq)]
58pub struct SensorState {
59    pub(crate) states: std::collections::HashMap<SensorSubFunctionType, String>,
60}
61
62impl SensorState {
63    /// Returns an iterator over all subfunction types that this state contains.
64    pub fn sub_types(&self) -> impl Iterator<Item = SensorSubFunctionType> + '_ {
65        self.states.keys().copied()
66    }
67
68    /// Returns the value of a given `SensorSubFunctionType` if present in this `SensorState`
69    pub fn value(&self, sub_type: SensorSubFunctionType) -> Option<&str> {
70        self.states.get(&sub_type).map(String::as_str)
71    }
72}