implement cpu temperature

This commit is contained in:
csehviktor
2025-07-22 19:55:59 +02:00
parent 00f7be0d25
commit 114b0ee55d
7 changed files with 46 additions and 9 deletions

View File

@@ -1,4 +1,4 @@
use common::metrics::{CPU, Disk, Memory, Metrics, Network, SystemInfo};
use common::metrics::{Disk, Memory, Metrics, Network, SystemInfo, CPU};
use sysinfo::{Disks, Networks, System};
use crate::cpu::CpuStatReader;
@@ -54,7 +54,8 @@ impl Collector {
CPU {
usage: self.sys.global_cpu_usage(),
threads: self.sys.cpus().len(),
breakdown: self.cpu_reader.read_global_cpu_stats().unwrap_or_default(),
breakdown: self.cpu_reader.cpu_breakdown().unwrap_or_default(),
temperature: self.cpu_reader.cpu_temperature().unwrap_or_default(),
}
}

View File

@@ -31,10 +31,14 @@ impl CpuValues {
}
}
#[cfg_attr(not(target_os = "linux"), derive(Default))]
pub struct CpuStatReader {
previous_stats: HashMap<String, CpuValues>,
}
const CPU_LINE_PATH: &str = "/proc/stat";
const CPU_TEMP_PATH: &str = "/sys/class/thermal/thermal_zone0/temp";
impl CpuStatReader {
pub fn new() -> Self {
Self {
@@ -42,8 +46,9 @@ impl CpuStatReader {
}
}
pub fn read_global_cpu_stats(&mut self) -> anyhow::Result<CpuBreakdown> {
let content = std::fs::read_to_string("/proc/stat").unwrap();
#[cfg(target_os = "linux")]
pub fn cpu_breakdown(&mut self) -> anyhow::Result<CpuBreakdown> {
let content = std::fs::read_to_string(CPU_LINE_PATH)?;
let cpu_line = content
.lines()
@@ -53,6 +58,16 @@ impl CpuStatReader {
self.parse_cpu_line(cpu_line)
}
#[cfg(target_os = "linux")]
pub fn cpu_temperature(&mut self) -> anyhow::Result<f32> {
let content = std::fs::read_to_string(CPU_TEMP_PATH)?;
let temp_millicelsius = content.trim().parse::<f32>()?;
let temp_celsius = temp_millicelsius / 1000.0;
Ok(temp_celsius)
}
fn parse_cpu_line(&mut self, line: &str) -> anyhow::Result<CpuBreakdown> {
let mut parts = line.split_whitespace();