use std::error::Error; use std::time::Duration; use crate::api; use crate::hardware::network::NetworkMonitor; use crate::hardware::HardwareInfo; use crate::models::MetricDto; pub struct Collector { network_monitor: NetworkMonitor, server_id: i32, ip_address: String, } impl Collector { pub fn new(server_id: i32, ip_address: String) -> Self { Self { network_monitor: NetworkMonitor::new(), server_id, ip_address, } } pub async fn run(&mut self, base_url: &str) -> Result<(), Box> { loop { println!( "[{}] Starting metrics collection...", chrono::Local::now().format("%H:%M:%S") ); let metrics = match self.collect().await { Ok(metrics) => metrics, Err(e) => { eprintln!("Error collecting metrics: {}", e); tokio::time::sleep(Duration::from_secs(10)).await; continue; } }; api::send_metrics(base_url, &metrics).await?; tokio::time::sleep(Duration::from_secs(20)).await; } } pub async fn collect(&mut self) -> Result> { let hardware = match HardwareInfo::collect().await { Ok(hw) => hw, Err(e) => { eprintln!("Error collecting hardware-infos: {e}"); return Err(e); } }; // Collect network usage let (_, _) = self.network_monitor.update_usage().unwrap_or((0.0, 0.0)); Ok(MetricDto { server_id: self.server_id, ip_address: self.ip_address.clone(), cpu_load: hardware.cpu.current_load.unwrap_or_default(), cpu_temp: hardware.cpu.current_temp.unwrap_or_default(), gpu_load: hardware.gpu.current_load.unwrap_or_default(), gpu_temp: hardware.gpu.current_temp.unwrap_or_default(), gpu_vram_size: hardware.gpu.vram_total.unwrap_or_default(), gpu_vram_usage: hardware.gpu.vram_used.unwrap_or_default(), ram_load: hardware.memory.used.unwrap_or_default(), ram_size: hardware.memory.total.unwrap_or_default(), disk_size: hardware.disk.total.unwrap_or_default(), disk_usage: hardware.disk.used.unwrap_or_default(), disk_temp: 0.0, // not supported net_rx: hardware.network.rx_rate.unwrap_or_default(), net_tx: hardware.network.tx_rate.unwrap_or_default(), }) } }