Skip to content

Commit

Permalink
Merge branch 'dev' into unix-build
Browse files Browse the repository at this point in the history
  • Loading branch information
Levminer committed Oct 4, 2024
2 parents 9997084 + db20512 commit 33540a4
Show file tree
Hide file tree
Showing 8 changed files with 163 additions and 50 deletions.
25 changes: 10 additions & 15 deletions Cargo.lock

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

17 changes: 10 additions & 7 deletions platforms/unix/daemon/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use axum::{
use ezrtc::host::EzRTCHost;
use ezrtc::socket::DataChannelHandler;
use futures::{sink::SinkExt, stream::StreamExt};
use hardwareinfo::settings::get_settings;
use hardwareinfo::settings::{get_settings, Settings};
use hardwareinfo::{refresh_hardware_info, Data, HardwareInfo, Networks, Nvml, System};
use log::{error, info, warn, LevelFilter};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -41,6 +41,7 @@ pub struct AppState {
hardware_info_receiver: async_channel::Receiver<HardwareInfo>,
last_60s_hardware_info: Mutex<Vec<HardwareInfo>>,
last_60m_hardware_info: Mutex<Vec<HardwareInfo>>,
settings: Settings,
}

#[tokio::main]
Expand All @@ -54,6 +55,10 @@ async fn main() {
)])
.unwrap();

// Get settings
let settings = get_settings();
info!("Connection code: {:?}", settings.connection_code);

// Hardware info channel
let (s, r) = async_channel::unbounded();

Expand All @@ -64,12 +69,14 @@ async fn main() {
hw_info: HardwareInfo::default(),
nvml: Nvml::init(),
nvml_available: true,
interval: settings.interval as f64,
};

let app_state = Arc::new(AppState {
hardware_info_receiver: r.clone(),
last_60s_hardware_info: Mutex::new(Vec::new()),
last_60m_hardware_info: Mutex::new(Vec::new()),
settings: settings.clone(),
});

// Setup HTTP server routes
Expand Down Expand Up @@ -127,7 +134,7 @@ async fn main() {
.push(data.hw_info.clone());
}

tokio::time::sleep(std::time::Duration::from_secs(5)).await;
tokio::time::sleep(std::time::Duration::from_secs(settings.interval as u64)).await;
}
});

Expand Down Expand Up @@ -347,10 +354,6 @@ async fn main() {
}
}

// Get settings
let settings = get_settings();
info!("Connection code: {:?}", settings.connection_code);

// Start the connection
let _host = EzRTCHost::new(
"wss://rtc-usw.levminer.com/one-to-many".to_string(),
Expand Down Expand Up @@ -485,7 +488,7 @@ async fn handle_socket(mut socket: WebSocket, addr: SocketAddr, state: Arc<AppSt
break;
}

tokio::time::sleep(std::time::Duration::from_secs(5)).await;
tokio::time::sleep(std::time::Duration::from_secs(state.settings.interval as u64)).await;
}

match sender
Expand Down
2 changes: 1 addition & 1 deletion platforms/unix/hardwareinfo/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition = "2021"
[dependencies]
netdev = "0.29.0"
sysinfo = "0.30.12"
starship-battery = "0.8.3"
starship-battery = "0.10.0"
indexmap = "2.2.6"
nvml-wrapper = "0.10.0"
serde = { version = "1", features = ["derive"] }
Expand Down
95 changes: 92 additions & 3 deletions platforms/unix/hardwareinfo/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use netdev::{get_default_interface, ip::Ipv4Net, mac::MacAddr, NetworkDevice};
use nvml_wrapper::enum_wrappers::device::{Clock, TemperatureSensor};
use nvml_wrapper::struct_wrappers::device::{MemoryInfo, Utilization};
use serde::{Deserialize, Serialize};
use starship_battery::units::energy::milliwatt_hour;
use starship_battery::units::ratio::percent;
use std::time::SystemTime;
use std::{
env,
Expand Down Expand Up @@ -42,6 +44,7 @@ pub struct Data {
pub first_run: bool,
pub nvml: Result<Nvml, nvml_wrapper::error::NvmlError>,
pub nvml_available: bool,
pub interval: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -173,6 +176,15 @@ pub struct CoresMotherboard {
pub name: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CoresBattery {
pub cycle_count: String,
pub level: Vec<CoresSensor>,
pub remaining_time: CoresSensor,
pub capacity: Vec<CoresSensor>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CoresBIOS {
pub vendor: String,
Expand All @@ -198,6 +210,7 @@ pub struct CoresSystem {
pub bios: CoresBIOS,
pub superIO: CoresSuperIO,
pub monitor: CoresMonitor,
pub battery: CoresBattery,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
Expand Down Expand Up @@ -267,6 +280,12 @@ impl HardwareInfo {
monitor: CoresMonitor {
monitors: Vec::new(),
},
battery: CoresBattery {
cycle_count: "N/A".to_string(),
level: Vec::new(),
remaining_time: CoresSensor::default(),
capacity: Vec::new(),
},
},
}
}
Expand Down Expand Up @@ -303,7 +322,6 @@ fn compare_sensor(prev_sensor: &CoresSensor, value: f64) -> CoresSensor {
pub fn refresh_hardware_info(data: &mut Data) {
let gb = 1024_f64.powi(3);
let _mb = 1024_f64.powi(2);
let interval = 5.0;

// OS Info
if data.first_run {
Expand Down Expand Up @@ -605,8 +623,8 @@ pub fn refresh_hardware_info(data: &mut Data) {
let download_data = (net_data.total_received() as f64 / gb).fmt_num();
let upload_data = (net_data.total_transmitted() as f64 / gb).fmt_num();

let throughput_download = net_data.received() as f64 / interval;
let throughput_upload = net_data.transmitted() as f64 / interval;
let throughput_download = net_data.received() as f64 / data.interval;
let throughput_upload = net_data.transmitted() as f64 / data.interval;

data.hw_info.system.network.interfaces[0].download_data = download_data;
data.hw_info.system.network.interfaces[0].upload_data = upload_data;
Expand Down Expand Up @@ -665,6 +683,77 @@ pub fn refresh_hardware_info(data: &mut Data) {
}
}

// Battery
if data.first_run {
let manager = starship_battery::Manager::new();

match manager {
Ok(manager) => {
if let Ok(batteries) = manager.batteries() {
for battery in batteries {
if let Ok(battery) = battery {
let cycle_count = battery.cycle_count().unwrap_or(0);
let charge_level = battery.state_of_charge().get::<percent>();
let design_capacity =
battery.energy_full_design().get::<milliwatt_hour>();
let full_charge_capacity =
battery.energy_full().get::<milliwatt_hour>();
let remaining_capacity = battery.energy().get::<milliwatt_hour>();
let health = battery.state_of_health().get::<percent>();

data.hw_info.system.battery = CoresBattery {
cycle_count: cycle_count.to_string(),
level: Vec::new(),
remaining_time: CoresSensor::default(),
capacity: Vec::new(),
};

data.hw_info.system.battery.level.push(CoresSensor {
name: "Charge level".to_string(),
value: charge_level as f64,
min: charge_level as f64,
max: charge_level as f64,
});

data.hw_info.system.battery.level.push(CoresSensor {
name: "Health".to_string(),
value: 100.0 - health as f64,
min: 100.0 - health as f64,
max: 100.0 - health as f64,
});

data.hw_info.system.battery.capacity.push(CoresSensor {
name: "Design capacity".to_string(),
value: design_capacity as f64,
min: design_capacity as f64,
max: design_capacity as f64,
});

data.hw_info.system.battery.capacity.push(CoresSensor {
name: "Full charge capacity".to_string(),
value: full_charge_capacity as f64,
min: full_charge_capacity as f64,
max: full_charge_capacity as f64,
});

data.hw_info.system.battery.capacity.push(CoresSensor {
name: "Remaining capacity".to_string(),
value: remaining_capacity as f64,
min: remaining_capacity as f64,
max: remaining_capacity as f64,
});
} else {
error!("Error getting specific battery info");
}
}
}
}
Err(_err) => {
error!("Error getting battery info");
}
};
}

// END
data.first_run = false;
}
28 changes: 28 additions & 0 deletions platforms/unix/hardwareinfo/src/linux/drive.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use anyhow::{Context, Result};
use core::str;
use regex::Regex;
use std::{
collections::HashMap,
fmt::Display,
path::{Path, PathBuf},
process::Command,
sync::LazyLock,
};

Expand Down Expand Up @@ -289,3 +291,29 @@ impl Drive {
}
}
}

pub fn get_free_space(path: &PathBuf) -> u64 {
// Define the device path as a variable
let path_str = path.to_str().unwrap_or("").replace("/sys/block/", "/dev/");

// Construct the command string
let command = format!(
"lsblk -bno FSAVAIL,MOUNTPOINT {} | awk '{{sum += $1}} END {{print sum / (1024^3) \"\"}}'",
path_str
);

// Execute the command
let output = Command::new("sh").arg("-c").arg(&command).output();

// Check if the command was successful
if let Ok(output) = output {
// Print the command's standard output
if let Ok(result) = str::from_utf8(&output.stdout) {
return (result.trim().parse::<f64>().unwrap_or(0.0) * 1.074) as u64;
} else {
return 0;
}
} else {
return 0;
}
}
Loading

0 comments on commit 33540a4

Please sign in to comment.