aboutsummaryrefslogtreecommitdiff
path: root/src/utils/netspeed.rs
blob: 4181daaf666cd2ebb9d66eb8cc39dd93296f15ac (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
use crate::config::CONFIG;
use crate::types::ThreadsData;
use std::fs::read_to_string;
use async_std::task::sleep;
use std::time::Duration;

pub async fn get_netspeed() -> ThreadsData {
    let tx1: u64 = parse_speed_file("tx_bytes");
    let rx1: u64 = parse_speed_file("rx_bytes");
    sleep(Duration::from_secs(1)).await;
    let tx2: u64 = parse_speed_file("tx_bytes");
    let rx2: u64 = parse_speed_file("rx_bytes");

    let tx_bps = tx2 - tx1;
    let rx_bps = rx2 - rx1;

    let tx = calculate(tx_bps);
    let rx = calculate(rx_bps);

    let data = format!(
        " {}{} {}{} {}",
        rx, CONFIG.netspeed.recieve_icon, tx, CONFIG.netspeed.transmit_icon, CONFIG.seperator
    );
    ThreadsData::NetSpeed(data)
}

fn parse_speed_file(pth: &str) -> u64 {
    let base_path = format!("/sys/class/net/{}/statistics/", CONFIG.netspeed.interface);
    let x: u64 = read_to_string(base_path + pth)
        .unwrap()
        .trim()
        .parse::<u64>()
        .unwrap();

    x
}

fn calculate(speed: u64) -> String {
    let lookup = ["b", "kb", "Mb"];
    let mut speed = speed as f64;
    let mut idx = 0;
    while speed >= 1024.0 && idx < lookup.len() {
        speed /= 1024.0;
        idx += 1;
    }
    format!("{: >5.1}{: >2}", speed, lookup[idx])
}