no hashmap for temparatures

This commit is contained in:
Robin Appelman 2021-03-28 22:31:21 +02:00
commit 90dbaf071d
3 changed files with 54 additions and 88 deletions

37
Cargo.lock generated
View file

@ -15,15 +15,6 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]]
name = "aho-corasick"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7404febffaa47dac81aa44dba71523c9d069b1bdc50a77db41195149e17f68e5"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "autocfg" name = "autocfg"
version = "1.0.1" version = "1.0.1"
@ -630,37 +621,11 @@ dependencies = [
"iai", "iai",
"libc", "libc",
"once_cell", "once_cell",
"parse-display",
"regex", "regex",
"tokio", "tokio",
"warp", "warp",
] ]
[[package]]
name = "parse-display"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7271152b3c46c07c729698e7a5248e2744466b3446d222c97a0b1315925a97b1"
dependencies = [
"once_cell",
"parse-display-derive",
"regex",
]
[[package]]
name = "parse-display-derive"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6a9f3e41b237b77c99c09686481c235964ff5878229412b226c451f3e809f4f"
dependencies = [
"once_cell",
"proc-macro2",
"quote",
"regex",
"regex-syntax",
"syn",
]
[[package]] [[package]]
name = "percent-encoding" name = "percent-encoding"
version = "2.1.0" version = "2.1.0"
@ -825,8 +790,6 @@ version = "1.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "957056ecddbeba1b26965114e191d2e8589ce74db242b6ea25fc4062427a5c19" checksum = "957056ecddbeba1b26965114e191d2e8589ce74db242b6ea25fc4062427a5c19"
dependencies = [ dependencies = [
"aho-corasick",
"memchr",
"regex-syntax", "regex-syntax",
] ]

View file

@ -10,8 +10,7 @@ warp = "0.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] } tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
ctrlc = { version = "3", features = ["termination"] } ctrlc = { version = "3", features = ["termination"] }
dotenv = "0.15" dotenv = "0.15"
parse-display = "0.4" regex = { version = "1", default-features = false, features = ["std"] }
regex = { version = "1", default-features = false }
once_cell = "1" once_cell = "1"
hostname = "0.3" hostname = "0.3"
libc = "0.2" libc = "0.2"

View file

@ -1,18 +1,25 @@
use color_eyre::{Report, Result}; use color_eyre::{Report, Result};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use parse_display::Display;
use regex::Regex; use regex::Regex;
use std::collections::HashMap; use std::array::IntoIter;
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
use std::fs::{read, read_dir, read_to_string, DirEntry, File}; use std::fs::{read, read_dir, read_to_string, File};
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader};
use std::mem::MaybeUninit; use std::mem::MaybeUninit;
use std::os::unix::ffi::OsStrExt; use std::os::unix::ffi::OsStrExt;
#[derive(Debug, Clone, Hash, Eq, PartialEq, Display)] #[derive(Debug, Clone, Default)]
#[display(style = "lowercase")] pub struct Temperatures {
pub enum TemperatureLabel { cpu: f32,
Cpu, }
impl IntoIterator for Temperatures {
type Item = (&'static str, f32);
type IntoIter = IntoIter<Self::Item, 1>;
fn into_iter(self) -> Self::IntoIter {
IntoIter::new([("cpu", self.cpu)])
}
} }
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
@ -36,50 +43,47 @@ pub struct DiskUsage {
pub free: u64, pub free: u64,
} }
pub fn temperatures() -> Result<HashMap<TemperatureLabel, f32>> { pub fn temperatures() -> Result<Temperatures> {
Ok(read_dir("/sys/class/hwmon")? let mut temps = Temperatures::default();
.filter_map(Result::ok)
.filter_map(|dir: DirEntry| { const DESIRED_HW_MON: &[&[u8]] = &[b"k10temp\n"];
let name = read(dir.path().join("name")).ok()?; const DESIRED_SENSORS: &[&[u8]] = &[b"Tdie\n"];
match name.as_slice() {
b"k10temp\n" => Some((name, dir)), for hwmon in read_dir("/sys/class/hwmon")? {
_ => None, let hwmon = hwmon?;
let hwmon_name = read(hwmon.path().join("name"))?;
if !DESIRED_HW_MON.contains(&hwmon_name.as_slice()) {
continue;
} }
}) for file in read_dir(hwmon.path())? {
.flat_map(|(name, dir)| { let file = file?;
read_dir(dir.path()) let path = file.path();
.into_iter() let file_name = file.file_name();
.flatten()
.filter_map(Result::ok)
.filter_map(move |item: DirEntry| {
let file_name = item.file_name();
let bytes = file_name.as_bytes(); let bytes = file_name.as_bytes();
if bytes.starts_with(b"temp") && bytes.ends_with(b"_label") { let label = if bytes.starts_with(b"temp") && bytes.ends_with(b"_label") {
let label = read(item.path()).ok()?; read(&path)?
Some((name.clone(), label, item))
} else { } else {
None continue;
};
if !DESIRED_SENSORS.contains(&label.as_slice()) {
continue;
} }
}) let mut path = path
}) .into_os_string()
.filter_map( .into_string()
|(name, label, item)| match (name.as_slice(), label.as_slice()) { .map_err(|_| Report::msg("Invalid hwmon path"))?;
(b"k10temp\n", b"Tdie\n") => Some((TemperatureLabel::Cpu, item)),
_ => None,
},
)
.filter_map(|(label, item)| {
let path = item.path().into_os_string();
Some((label, path.into_string().ok()?))
})
.filter_map(|(label, mut path)| {
path.truncate(path.len() - "label".len()); path.truncate(path.len() - "label".len());
path.push_str("input"); path.push_str("input");
let value = read_to_string(path).ok()?; let value = read_to_string(path)?;
let parsed: u32 = value.trim().parse().ok()?; let parsed: u32 = value.trim().parse()?;
Some((label, parsed as f32 / 1000.0)) match (hwmon_name.as_slice(), label.as_slice()) {
}) (b"k10temp\n", b"Tdie\n") => temps.cpu = parsed as f32 / 100.0,
.collect()) _ => {}
}
}
}
Ok(temps)
} }
pub fn memory() -> Result<Memory> { pub fn memory() -> Result<Memory> {
@ -173,7 +177,7 @@ pub fn hostname() -> Result<String> {
pub fn disk_stats() -> Result<impl Iterator<Item = IoStats>> { pub fn disk_stats() -> Result<impl Iterator<Item = IoStats>> {
static DISK_REGEX: Lazy<Regex> = static DISK_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(r" ([sv]d[a-z]+|nvme\dn\d) ").unwrap()); Lazy::new(|| Regex::new(r" ([sv]d[a-z]+|nvme[0-9]n[0-9]) ").unwrap());
let stat = BufReader::new(File::open("/proc/diskstats")?); let stat = BufReader::new(File::open("/proc/diskstats")?);
Ok(stat Ok(stat