Skip to content

Commit

Permalink
refactor: only process temp type in data eat step
Browse files Browse the repository at this point in the history
  • Loading branch information
ClementTsang committed Jan 25, 2025
1 parent a41142a commit c3365be
Show file tree
Hide file tree
Showing 15 changed files with 151 additions and 229 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ regex = "1.11.1"
serde = { version = "1.0.217", features = ["derive"] }
starship-battery = { version = "0.10.0", optional = true }
sysinfo = "=0.30.13"
timeless = "0.0.12-alpha"
timeless = "0.0.13-alpha"
toml_edit = { version = "0.22.22", features = ["serde"] }
tui = { version = "0.29.0", package = "ratatui" }
unicode-ellipsis = "0.3.0"
Expand Down
4 changes: 2 additions & 2 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use unicode_segmentation::{GraphemeCursor, UnicodeSegmentation};

use crate::{
canvas::components::time_chart::LegendPosition,
collection::{processes::Pid, temperature},
collection::processes::Pid,
constants,
utils::data_units::DataUnit,
widgets::{ProcWidgetColumn, ProcWidgetMode},
Expand All @@ -38,7 +38,7 @@ pub enum AxisScaling {
#[derive(Debug, Default, Eq, PartialEq)]
pub struct AppConfigFields {
pub update_rate: u64,
pub temperature_type: temperature::TemperatureType,
pub temperature_type: TemperatureType,
pub use_dot: bool,
pub cpu_left_legend: bool,
pub show_average_cpu: bool, // TODO: Unify this in CPU options
Expand Down
3 changes: 3 additions & 0 deletions src/app/data/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ pub use process::ProcessData;

mod store;
pub use store::*;

mod temperature;
pub use temperature::*;
30 changes: 12 additions & 18 deletions src/app/data/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{
#[cfg(feature = "battery")]
use crate::collection::batteries;
use crate::{
app::AppConfigFields,
collection::{cpu, disks, memory::MemHarvest, network, Data},
dec_bytes_per_second_string,
widgets::TempWidgetData,
Expand All @@ -18,7 +19,7 @@ use super::{ProcessData, TimeSeriesData};
/// TODO: Maybe reduce visibility of internal data, make it only accessible through DataStore?
#[derive(Debug, Clone)]
pub struct StoredData {
pub current_instant: Instant, // FIXME: (points_rework_v1) remove this?
pub last_update_time: Instant, // FIXME: (points_rework_v1) remove this?
pub timeseries_data: TimeSeriesData, // FIXME: (points_rework_v1) Skip in basic?
pub network_harvest: network::NetworkHarvest,
pub ram_harvest: MemHarvest,
Expand All @@ -44,7 +45,7 @@ pub struct StoredData {
impl Default for StoredData {
fn default() -> Self {
StoredData {
current_instant: Instant::now(),
last_update_time: Instant::now(),
timeseries_data: TimeSeriesData::default(),
network_harvest: network::NetworkHarvest::default(),
ram_harvest: MemHarvest::default(),
Expand Down Expand Up @@ -77,24 +78,21 @@ impl StoredData {
clippy::boxed_local,
reason = "This avoids warnings on certain platforms (e.g. 32-bit)."
)]
fn eat_data(&mut self, data: Box<Data>) {
fn eat_data(&mut self, data: Box<Data>, settings: &AppConfigFields) {
let harvested_time = data.collection_time;

self.timeseries_data.add(&data);

// Network
if let Some(network) = data.network {
self.network_harvest = network;
}

// Memory, Swap
if let Some(memory) = data.memory {
self.ram_harvest = memory;
}

self.swap_harvest = data.swap;

// Cache memory
#[cfg(not(target_os = "windows"))]
{
self.cache_harvest = data.cache;
Expand All @@ -110,17 +108,14 @@ impl StoredData {
self.gpu_harvest = gpu;
}

// CPU
if let Some(cpu) = data.cpu {
self.cpu_harvest = cpu;
}

// Load average
if let Some(load_avg) = data.load_avg {
self.load_avg_harvest = load_avg;
}

// Temp
// TODO: (points_rework_v1) the map might be redundant, the types are the same.
self.temp_data = data
.temperature_sensors
Expand All @@ -129,41 +124,40 @@ impl StoredData {
.into_iter()
.map(|temp| TempWidgetData {
sensor: temp.name,
temperature: temp.temperature.map(|v| v.into()),
temperature: temp
.temperature
.map(|c| settings.temperature_type.convert_temp_unit(c)),
})
.collect()
})
.unwrap_or_default();

// Disks
if let Some(disks) = data.disks {
if let Some(io) = data.io {
self.eat_disks(disks, io, harvested_time);
}
}

// Processes
if let Some(list_of_processes) = data.list_of_processes {
self.process_data.ingest(list_of_processes);
}

#[cfg(feature = "battery")]
{
// Battery
if let Some(list_of_batteries) = data.list_of_batteries {
self.battery_harvest = list_of_batteries;
}
}

// And we're done eating. Update time and push the new entry!
self.current_instant = harvested_time;
// And we're done eating. Update time and push the new entry!
self.last_update_time = harvested_time;
}

fn eat_disks(
&mut self, disks: Vec<disks::DiskHarvest>, io: disks::IoHarvest, harvested_time: Instant,
) {
let time_since_last_harvest = harvested_time
.duration_since(self.current_instant)
.duration_since(self.last_update_time)
.as_secs_f64();

for (itx, device) in disks.iter().enumerate() {
Expand Down Expand Up @@ -315,8 +309,8 @@ impl DataStore {
}

/// Eat data.
pub fn eat_data(&mut self, data: Box<Data>) {
self.main.eat_data(data);
pub fn eat_data(&mut self, data: Box<Data>, settings: &AppConfigFields) {
self.main.eat_data(data, settings);
}

/// Clean data.
Expand Down
83 changes: 83 additions & 0 deletions src/app/data/temperature.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
//! Code around temperature data.
use std::{fmt::Display, str::FromStr};

#[derive(Clone, Debug, Copy, PartialEq, Eq, Default)]
pub enum TemperatureType {
#[default]
Celsius,
Kelvin,
Fahrenheit,
}

impl FromStr for TemperatureType {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"fahrenheit" | "f" => Ok(TemperatureType::Fahrenheit),
"kelvin" | "k" => Ok(TemperatureType::Kelvin),
"celsius" | "c" => Ok(TemperatureType::Celsius),
_ => Err(format!(
"'{s}' is an invalid temperature type, use one of: [kelvin, k, celsius, c, fahrenheit, f]."
)),
}
}
}

impl TemperatureType {
/// Given a temperature in Celsius, covert it if necessary for a different
/// unit.
pub fn convert_temp_unit(&self, celsius: f32) -> TypedTemperature {
match self {
TemperatureType::Celsius => TypedTemperature::Celsius(celsius.ceil() as u32),
TemperatureType::Kelvin => TypedTemperature::Kelvin((celsius + 273.15).ceil() as u32),
TemperatureType::Fahrenheit => {
TypedTemperature::Fahrenheit(((celsius * (9.0 / 5.0)) + 32.0).ceil() as u32)
}
}
}
}

/// A temperature and its type.
#[derive(Debug, PartialEq, Clone, Eq, PartialOrd, Ord)]
pub enum TypedTemperature {
Celsius(u32),
Kelvin(u32),
Fahrenheit(u32),
}

impl Display for TypedTemperature {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TypedTemperature::Celsius(val) => write!(f, "{val}°C"),
TypedTemperature::Kelvin(val) => write!(f, "{val}K"),
TypedTemperature::Fahrenheit(val) => write!(f, "{val}°F"),
}
}
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn temp_conversions() {
const TEMP: f32 = 100.0;

assert_eq!(
TemperatureType::Celsius.convert_temp_unit(TEMP),
TypedTemperature::Celsius(TEMP as u32),
);

assert_eq!(
TemperatureType::Kelvin.convert_temp_unit(TEMP),
TypedTemperature::Kelvin(373.15_f32.ceil() as u32)
);

assert_eq!(
TemperatureType::Fahrenheit.convert_temp_unit(TEMP),
TypedTemperature::Fahrenheit(212)
);
}
}
30 changes: 8 additions & 22 deletions src/collection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ use processes::Pid;
#[cfg(feature = "battery")]
use starship_battery::{Battery, Manager};

use self::temperature::TemperatureType;
use super::DataFilters;
use crate::app::layout_manager::UsedWidgets;

Expand All @@ -40,7 +39,7 @@ pub struct Data {
#[cfg(not(target_os = "windows"))]
pub cache: Option<memory::MemHarvest>,
pub swap: Option<memory::MemHarvest>,
pub temperature_sensors: Option<Vec<temperature::TempHarvest>>,
pub temperature_sensors: Option<Vec<temperature::TempSensorData>>,
pub network: Option<network::NetworkHarvest>,
pub list_of_processes: Option<Vec<processes::ProcessHarvest>>,
pub disks: Option<Vec<disks::DiskHarvest>>,
Expand Down Expand Up @@ -145,7 +144,6 @@ impl Default for SysinfoSource {
pub struct DataCollector {
pub data: Data,
sys: SysinfoSource,
temperature_type: TemperatureType,
use_current_cpu_total: bool,
unnormalized_cpu: bool,
last_collection_time: Instant,
Expand Down Expand Up @@ -191,7 +189,6 @@ impl DataCollector {
prev_idle: 0_f64,
#[cfg(target_os = "linux")]
prev_non_idle: 0_f64,
temperature_type: TemperatureType::Celsius,
use_current_cpu_total: false,
unnormalized_cpu: false,
last_collection_time,
Expand Down Expand Up @@ -242,10 +239,6 @@ impl DataCollector {
self.widgets_to_harvest = used_widgets;
}

pub fn set_temperature_type(&mut self, temperature_type: TemperatureType) {
self.temperature_type = temperature_type;
}

pub fn set_use_current_cpu_total(&mut self, use_current_cpu_total: bool) {
self.use_current_cpu_total = use_current_cpu_total;
}
Expand Down Expand Up @@ -356,11 +349,9 @@ impl DataCollector {
let mut local_gpu_total_mem: u64 = 0;

#[cfg(feature = "nvidia")]
if let Some(data) = nvidia::get_nvidia_vecs(
&self.temperature_type,
&self.filters.temp_filter,
&self.widgets_to_harvest,
) {
if let Some(data) =
nvidia::get_nvidia_vecs(&self.filters.temp_filter, &self.widgets_to_harvest)
{
if let Some(mut temp) = data.temperature {
if let Some(sensors) = &mut self.data.temperature_sensors {
sensors.append(&mut temp);
Expand All @@ -379,7 +370,6 @@ impl DataCollector {

#[cfg(target_os = "linux")]
if let Some(data) = amd::get_amd_vecs(
&self.temperature_type,
&self.filters.temp_filter,
&self.widgets_to_harvest,
self.last_collection_time,
Expand Down Expand Up @@ -435,18 +425,14 @@ impl DataCollector {
fn update_temps(&mut self) {
if self.widgets_to_harvest.use_temp {
#[cfg(not(target_os = "linux"))]
if let Ok(data) = temperature::get_temperature_data(
&self.sys.temps,
&self.temperature_type,
&self.filters.temp_filter,
) {
if let Ok(data) =
temperature::get_temperature_data(&self.sys.temps, &self.filters.temp_filter)
{
self.data.temperature_sensors = data;
}

#[cfg(target_os = "linux")]
if let Ok(data) =
temperature::get_temperature_data(&self.temperature_type, &self.filters.temp_filter)
{
if let Ok(data) = temperature::get_temperature_data(&self.filters.temp_filter) {
self.data.temperature_sensors = data;
}
}
Expand Down
16 changes: 5 additions & 11 deletions src/collection/amd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ mod amdgpu_marketing;

use crate::{
app::{filter::Filter, layout_manager::UsedWidgets},
collection::{
memory::MemHarvest,
temperature::{TempHarvest, TemperatureType},
},
collection::{memory::MemHarvest, temperature::TempSensorData},
};
use hashbrown::{HashMap, HashSet};
use std::{
Expand All @@ -18,7 +15,7 @@ use std::{

pub struct AMDGPUData {
pub memory: Option<Vec<(String, MemHarvest)>>,
pub temperature: Option<Vec<TempHarvest>>,
pub temperature: Option<Vec<TempSensorData>>,
pub procs: Option<(u64, Vec<HashMap<u32, (u64, u32)>>)>,
}

Expand Down Expand Up @@ -402,8 +399,7 @@ fn get_amd_fdinfo(device_path: &Path) -> Option<HashMap<u32, AMDGPUProc>> {
}

pub fn get_amd_vecs(
temp_type: &TemperatureType, filter: &Option<Filter>, widgets_to_harvest: &UsedWidgets,
prev_time: Instant,
filter: &Option<Filter>, widgets_to_harvest: &UsedWidgets, prev_time: Instant,
) -> Option<AMDGPUData> {
let device_path_list = get_amd_devs()?;
let interval = Instant::now().duration_since(prev_time);
Expand Down Expand Up @@ -435,11 +431,9 @@ pub fn get_amd_vecs(
if widgets_to_harvest.use_temp && Filter::optional_should_keep(filter, &device_name) {
if let Some(temperatures) = get_amd_temp(&device_path) {
for info in temperatures {
let temperature = temp_type.convert_temp_unit(info.temperature);

temp_vec.push(TempHarvest {
temp_vec.push(TempSensorData {
name: format!("{} {}", device_name, info.name),
temperature: Some(temperature),
temperature: Some(info.temperature),
});
}
}
Expand Down
Loading

0 comments on commit c3365be

Please sign in to comment.