1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use crate::{
gpio,
powerstate::PowerState,
sensor::{SensorIO, SensorIOCtx, SensorType},
types::*,
};
pub const PLATFORM_DEVICE_DIR: &str = "/sys/bus/platform/devices";
pub async fn read_and_parse<T: std::str::FromStr>(fd: &mut tokio::fs::File) -> ErrResult<T> {
let mut buf = [0u8; 128];
fd.rewind().await?;
let n = fd.read(&mut buf).await?;
let s = std::str::from_utf8(&buf[..n])?;
if n == 0 || n >= buf.len() {
return Err(err_invalid_data(format!("invalid sysfs data: {}", s)))
}
s.trim().parse::<T>()
.map_err(|_| err_invalid_data(format!("invalid sysfs data: {}", s)))
}
pub fn get_single_glob_match(pattern: &str) -> ErrResult<PathBuf> {
let mut matches = glob::glob(pattern)?;
let first = match matches.next() {
Some(m) => m?,
None => return Err(err_not_found("no match found")),
};
if matches.next().is_some() {
Err(err_invalid_data("multiple matches found"))
} else {
Ok(first)
}
}
pub fn get_single_hwmon_dir(path: &Path) -> ErrResult<PathBuf> {
let pattern = path.join("hwmon/hwmon[0-9]*");
get_single_glob_match(&pattern.to_string_lossy())
}
pub struct HwmonFileInfo {
pub abspath: PathBuf,
pub base: String,
pub kind: SensorType,
pub idx: usize,
}
impl HwmonFileInfo {
pub fn from_abspath(abspath: PathBuf) -> ErrResult<Self> {
let mk_err = |msg| {
err_invalid_data(format!("{}: {}", abspath.display(), msg))
};
let base = match abspath.file_name().map(|p| p.to_string_lossy()) {
Some(s) => s.strip_suffix("_input")
.ok_or_else(|| mk_err("no \"_input\" suffix"))?
.to_string(),
_ => return Err(err_invalid_data("no file name")),
};
let typetag = base.trim_end_matches(|c: char| c.is_ascii_digit());
let Some(kind) = SensorType::from_hwmon_typetag(typetag) else {
let msg = format!("unrecognized hwmon type tag '{}'", typetag);
return Err(mk_err(&msg));
};
let Ok(idx) = base.strip_prefix(typetag).unwrap().parse::<usize>() else {
let msg = format!("couldn't parse index from '{}'", base);
return Err(mk_err(&msg));
};
Ok(HwmonFileInfo {
kind,
idx,
base,
abspath,
})
}
pub fn get_label(&self) -> ErrResult<String> {
let labelpath = self.abspath.with_file_name(format!("{}_label", self.base));
if labelpath.is_file() {
Ok(std::fs::read_to_string(&labelpath).map(|s| s.trim().to_string())?)
} else {
Ok(self.base.clone())
}
}
}
pub fn scan_hwmon_input_files(devdir: &Path, fileprefix: Option<&str>)
-> ErrResult<Vec<HwmonFileInfo>>
{
let hwmondir = get_single_hwmon_dir(devdir)?;
let pattern = hwmondir.join(format!("{}*_input", fileprefix.unwrap_or("")));
let mut info: Vec<_> = glob::glob(&pattern.to_string_lossy())?
.filter_map(|g| {
match g {
Ok(abspath) => match HwmonFileInfo::from_abspath(abspath) {
Ok(f) => Some(f),
Err(e) => {
eprintln!("Warning: {} (skipping)", e);
None
}
},
Err(e) => {
eprintln!("Warning: error scanning {}, skipping entry: {}",
hwmondir.display(), e);
None
},
}
})
.collect();
info.sort_by_key(|info| (info.kind, info.idx));
Ok(info)
}
pub async fn prepare_indexed_hwmon_ioctx(hwmondir: &Path, idx: u64, kind: SensorType,
power_state: PowerState,
bridge_gpio_cfg: &Option<Arc<gpio::BridgeGPIOConfig>>)
-> ErrResult<Option<SensorIOCtx>>
{
if !power_state.active_now() {
return Ok(None);
}
let path = hwmondir.join(format!("{}{}_input", kind.hwmon_typetag(), idx + 1));
let file = HwmonFileInfo::from_abspath(path)?;
let bridge_gpio = match bridge_gpio_cfg {
Some(c) => Some(gpio::BridgeGPIO::from_config(c.clone())?),
None => None,
};
let io = SensorIO::Sysfs(SysfsSensorIO::new(&file).await?);
Ok(Some(SensorIOCtx::new(io).with_bridge_gpio(bridge_gpio)))
}
pub struct SysfsSensorIO {
fd: tokio::fs::File,
scale: f64,
}
impl SysfsSensorIO {
pub async fn new(file: &HwmonFileInfo) -> ErrResult<Self> {
let fd = tokio::fs::File::open(&file.abspath).await?;
Ok(Self {
fd,
scale: file.kind.hwmon_scale(),
})
}
pub async fn read(&mut self) -> ErrResult<f64> {
let ival = read_and_parse::<i32>(&mut self.fd).await?;
Ok((ival as f64) * self.scale)
}
}