summaryrefslogtreecommitdiffstats
path: root/src/app/data_harvester/network.rs
blob: 2c2dba7dbef57f6665f54dc74e5d5786d7f74b9a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use std::time::Instant;

use futures::StreamExt;
use heim::net;
use heim::units::information::byte;
use sysinfo::{NetworkExt, System, SystemExt};

#[derive(Default, Clone, Debug)]
pub struct NetworkHarvest {
    pub rx: u64,
    pub tx: u64,
    pub total_rx: u64,
    pub total_tx: u64,
}

impl NetworkHarvest {
    pub fn first_run_cleanup(&mut self) {
        self.rx = 0;
        self.tx = 0;
    }
}

pub async fn get_network_data(
    sys: &System, prev_net_access_time: Instant, prev_net_rx: &mut u64, prev_net_tx: &mut u64,
    curr_time: Instant,
) -> NetworkHarvest {
    let mut io_data = net::io_counters();
    let mut total_rx: u64 = 0;
    let mut total_tx: u64 = 0;

    if cfg!(target_os = "windows") {
        let networks = sys.get_networks();
        for (_, network) in networks {
            total_rx += network.get_total_income();
            total_tx += network.get_total_outcome();
        }
    } else {
        while let Some(io) = io_data.next().await {
            if let Ok(io) = io {
                total_rx += io.bytes_recv().get::<byte>();
                total_tx += io.bytes_sent().get::<byte>();
            }
        }
    }

    let elapsed_time = curr_time.duration_since(prev_net_access_time).as_secs_f64();

    let rx = ((total_rx - *prev_net_rx) as f64 / elapsed_time) as u64;
    let tx = ((total_tx - *prev_net_tx) as f64 / elapsed_time) as u64;

    *prev_net_rx = total_rx;
    *prev_net_tx = total_tx;
    NetworkHarvest {
        rx,
        tx,
        total_rx,
        total_tx,
    }
}