rsiot/components/cmp_system_info/
fn_process.rs1use sysinfo::{Components, Disks, Networks, System};
2use tokio::time::sleep;
3
4use crate::{executor::CmpInOut, message::MsgDataBound};
5
6use super::{Config, Error, SystemInfo, SystemInfoDisk, SystemInfoNetwork};
7
8const B_IN_MB: f32 = 1048576.0;
9
10const B_IN_GB: f32 = 1073741824.0;
11
12pub async fn fn_process<TMsg>(config: Config<TMsg>, in_out: CmpInOut<TMsg>) -> super::Result<()>
13where
14 TMsg: MsgDataBound,
15{
16 let mut sys = System::new_all();
17 let mut system_info = SystemInfo::default();
18
19 system_info.os_version = match System::long_os_version() {
20 Some(value) => value.to_string(),
21 None => return raise_error("os_version"),
22 };
23
24 system_info.host_name = match System::host_name() {
25 Some(value) => value.to_string(),
26 None => return raise_error("host_name"),
27 };
28
29 let networks = Networks::new_with_refreshed_list();
30 for (interface_name, data) in &networks {
31 system_info.networks.insert(
32 interface_name.to_string(),
33 SystemInfoNetwork {
34 name: interface_name.to_string(),
35 mac_address: data.mac_address().to_string(),
36 },
37 );
38 }
39
40 loop {
41 sys.refresh_all();
42
43 system_info.memory.total_memory_mb = sys.total_memory() as f32 / B_IN_MB;
45 system_info.memory.used_memory_mb = sys.used_memory() as f32 / B_IN_MB;
46 system_info.memory.total_swap_mb = sys.total_swap() as f32 / B_IN_MB;
47 system_info.memory.used_swap_mb = sys.used_swap() as f32 / B_IN_MB;
48
49 let cpus = sys
51 .cpus()
52 .iter()
53 .map(|c| c.cpu_usage())
54 .collect::<Vec<f32>>();
55 system_info.cpu_usage = cpus;
56
57 for disk in Disks::new_with_refreshed_list().iter() {
58 let used_space_gb = (disk.total_space() - disk.available_space()) as f32 / B_IN_GB;
59 let total_space_gb = disk.total_space() as f32 / B_IN_GB;
60 let name = disk.name().to_str().unwrap().to_string();
61 system_info.disks.insert(
62 name.clone(),
63 SystemInfoDisk {
64 name,
65 used_space_gb,
66 total_space_gb,
67 },
68 );
69 }
70
71 system_info.temperatures = Components::new_with_refreshed_list()
73 .iter()
74 .map(|c| (c.label().to_string(), c.temperature()))
75 .collect();
76
77 let msgs = (config.fn_output)(&system_info);
78 for msg in msgs {
79 in_out.send_output(msg).await.unwrap();
80 }
81
82 sleep(config.period).await;
83 }
84}
85
86fn raise_error(field: &str) -> super::Result<()> {
87 let err = Error::CannotDefine {
88 field: field.into(),
89 };
90 Err(err)
91}