libmedium/hwmon/sync_hwmon/
helper_functions.rs1use super::Hwmon;
2
3use crate::parsing::{Error as ParsingError, Result as ParsingResult};
4use crate::sensors::{sync_sensors::SyncSensorExt, Error as SensorError};
5
6use std::{collections::BTreeMap, io::ErrorKind as IoErrorKind, path::Path};
7
8pub(crate) fn check_path(path: impl AsRef<Path>) -> ParsingResult<()> {
9 let path = path.as_ref();
10
11 if let Err(e) = path.metadata() {
12 return Err(ParsingError::hwmon_dir(e, path));
13 }
14
15 Ok(())
16}
17
18pub(crate) fn get_name(path: impl AsRef<Path>) -> ParsingResult<String> {
19 let name_path = path.as_ref().join("name");
20
21 std::fs::read_to_string(&name_path)
22 .map(|name| name.trim().to_string())
23 .map_err(|e| ParsingError::hwmon_name(e, name_path))
24}
25
26pub(crate) fn get_label(path: impl AsRef<Path>) -> ParsingResult<String> {
27 let label_path = path.as_ref().join("label");
28
29 std::fs::read_to_string(&label_path)
30 .map(|label| label.trim().to_string())
31 .map_err(|e| ParsingError::hwmon_label(e, label_path))
32}
33
34pub(crate) fn init_sensors<S>(hwmon: &Hwmon, start_index: u16) -> ParsingResult<BTreeMap<u16, S>>
35where
36 S: SyncSensorExt,
37{
38 let mut stop_index = start_index;
39
40 let dir = hwmon
41 .path()
42 .read_dir()
43 .map_err(|e| ParsingError::hwmon_dir(e, hwmon.path()))?;
44
45 for entry in dir {
46 let entry = entry.map_err(|e| SensorError::read(e, hwmon.path()))?;
47 let file_name = entry.file_name().to_string_lossy().to_string();
48
49 if !file_name.starts_with(S::static_base()) {
50 continue;
51 }
52
53 let index = file_name
54 .trim_matches(|ch: char| !ch.is_ascii_digit())
55 .parse()
56 .unwrap_or(0);
57
58 if index > stop_index {
59 stop_index = index;
60 }
61 }
62
63 let mut sensors = BTreeMap::new();
64
65 for index in start_index..=stop_index {
66 match S::parse(hwmon, index) {
67 Ok(sensor) => {
68 sensors.insert(index, sensor);
69 }
70 Err(e) => match &e {
71 SensorError::Read { source, .. } => {
72 if source.kind() != IoErrorKind::NotFound {
73 return Err(e.into());
74 }
75 }
76 _ => return Err(e.into()),
77 },
78 }
79 }
80
81 Ok(sensors)
82}