summaryrefslogtreecommitdiff
path: root/contrib/net-speed
blob: 7f332b0a5950430934be0dffb193cfd2d9d31c2a (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/bin/sh

# Copyright © 2014 Zhong Jianxin <azuwis@gmail.com>
#
# See file LICENSE at the project root directory for license information.
#
# Thank Stefan Breunig for the original implementation, see
# contrib/measure-net-speed.bash.

# i3status.conf should contain:
# general {
#   output_format = i3bar
# }

# i3 config looks like this:
# bar {
#   status_command exec /usr/share/doc/i3status/contrib/net-speed
# }

# Single interface
#ifaces="eth0"

# Multiple interfaces
#ifaces="eth0 wlan0"

# Auto detect
ifaces=$(ls /sys/class/net | grep -E '^(eth|wlan)')

# Interval must be the same as in i3status.conf
#interval=5

if [ -z "$XDG_CONFIG_HOME" ]; then
  XDG_CONFIG_HOME="${HOME}/.config"
fi

# Auto detect
if [ -f "${XDG_CONFIG_HOME}/i3status/config" ]; then
  i3status_conf="${XDG_CONFIG_HOME}/i3status/config"
elif [ -f ~/.i3status.conf ]; then
  i3status_conf=~/.i3status.conf
else
  i3status_conf="/etc/i3status.conf"
fi

if [ -f "$i3status_conf" ]; then
  interval=$(grep -o '^[[:space:]]*interval[[:space:]]*=[[:space:]]*[[:digit:]]\+' $i3status_conf | grep -o '[[:digit:]]\+')
fi

if [ x"$interval" = x ]; then
  interval=5
fi

last_rx=0
last_tx=0
rate=""

readable() {
    local byte=$1
    local kib=$(( byte >> 10 ))
    if [ "$kib" -gt 1024 ]; then
        local mib_int=$(( kib >> 10 ))
        local mib_dec=$(( kib % 1024 * 976 / 10000 ))
        if [ "$mib_dec" -lt 10 ]; then
            mib_dec="0${mib_dec}"
        fi
        echo "${mib_int}.${mib_dec}M"
    else
        echo "${kib}K"
    fi
}

update_rate() {
    local rx=0
    local tx=0
    for iface in $ifaces; do
        local tmp_rx
        local tmp_tx
        local stat="/sys/class/net/${iface}/statistics"
        read tmp_rx < "${stat}/rx_bytes"
        read tmp_tx < "${stat}/tx_bytes"
        rx=$(( rx + tmp_rx ))
        tx=$(( tx + tmp_tx ))
    done
    rate="$(readable $(( (rx - last_rx) / interval )))↓ $(readable $(( (tx - last_tx) / interval )))↑"
    last_rx=$rx
    last_tx=$tx
}

# while :; do
#     update_rate
#     echo "$rate"
#     sleep "$interval"
# done

i3status | (read line && echo "$line" && read line && echo "$line" && read line && echo "$line" && update_rate && while :
do
    read line
    update_rate
    echo ",[{\"full_text\":\"${rate}\" },${line#,\[}" || exit 1
done)