| 1 | //! Gets network data via sysinfo. |
| 2 | |
| 3 | use std::time::Instant; |
| 4 | |
| 5 | use sysinfo::Networks; |
| 6 | |
| 7 | use super::NetworkHarvest; |
| 8 | use crate::app::filter::Filter; |
| 9 | |
| 10 | // TODO: Eventually make it so that this thing also takes individual usage into |
| 11 | // account, so we can show per-interface! |
| 12 | pub fn get_network_data( |
| 13 | networks: &Networks, prev_net_access_time: Instant, prev_net_rx: &mut u64, |
| 14 | prev_net_tx: &mut u64, prev_net_rx_packets: &mut u64, prev_net_tx_packets: &mut u64, |
| 15 | curr_time: Instant, filter: &Option<Filter>, |
| 16 | ) -> NetworkHarvest { |
| 17 | let mut total_rx: u64 = 0; |
| 18 | let mut total_tx: u64 = 0; |
| 19 | let mut total_rx_packets: u64 = 0; |
| 20 | let mut total_tx_packets: u64 = 0; |
| 21 | |
| 22 | for (name, network) in networks { |
| 23 | let to_keep = if let Some(filter) = filter { |
| 24 | filter.should_keep(name) |
| 25 | } else { |
| 26 | true |
| 27 | }; |
| 28 | |
| 29 | if to_keep { |
| 30 | total_rx += network.total_received() * 8; |
| 31 | total_tx += network.total_transmitted() * 8; |
| 32 | total_rx_packets += network.total_packets_received(); |
| 33 | total_tx_packets += network.total_packets_transmitted(); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | let elapsed_time = curr_time.duration_since(prev_net_access_time).as_secs_f64(); |
| 38 | |
| 39 | let (rx, tx, rx_packets, tx_packets) = if elapsed_time == 0.0 { |
| 40 | (0, 0, 0, 0) |
| 41 | } else { |
| 42 | ( |
| 43 | ((total_rx.saturating_sub(*prev_net_rx)) as f64 / elapsed_time) as u64, |
| 44 | ((total_tx.saturating_sub(*prev_net_tx)) as f64 / elapsed_time) as u64, |
| 45 | ((total_rx_packets.saturating_sub(*prev_net_rx_packets)) as f64 / elapsed_time) as u64, |
| 46 | ((total_tx_packets.saturating_sub(*prev_net_tx_packets)) as f64 / elapsed_time) as u64, |
| 47 | ) |
| 48 | }; |
| 49 | |
| 50 | *prev_net_rx = total_rx; |
| 51 | *prev_net_tx = total_tx; |
| 52 | *prev_net_rx_packets = total_rx_packets; |
| 53 | *prev_net_tx_packets = total_tx_packets; |
| 54 | NetworkHarvest { |
| 55 | rx, |
| 56 | tx, |
| 57 | total_rx, |
| 58 | total_tx, |
| 59 | rx_packets, |
| 60 | tx_packets, |
| 61 | total_rx_packets, |
| 62 | total_tx_packets, |
| 63 | } |
| 64 | } |