]> git.sur5r.net Git - i3/i3status/blob - contrib/measure-net-speed.bash
Import measure-net-speed bash scripts to contrib/
[i3/i3status] / contrib / measure-net-speed.bash
1 #!/bin/bash
2 # Public Domain
3 # (someone claimed the next lines would be useful for…
4 #  people. So here goes: © 2012 Stefan Breunig
5 #  stefan+measure-net-speed@mathphys.fsk.uni-heidelberg.de)
6
7
8 # path to store the old results in
9 path="/dev/shm/measure-net-speed"
10
11 # grabbing data for each adapter. 
12 # You can find the paths to your adapters using
13 #  find /sys/devices -name statistics
14 # If you have more (or less) than two adapters, simply adjust the script here
15 # and in the next block. 
16 eth0="/sys/devices/pci0000:00/0000:00:19.0/net/eth0/statistics"
17 wlan0="/sys/devices/pci0000:00/0000:00:1c.1/0000:03:00.0/net/wlan0/statistics"
18 read eth0_rx < "${eth0}/rx_bytes"
19 read eth0_tx < "${eth0}/tx_bytes"
20 read wlan0_rx < "${wlan0}/rx_bytes"
21 read wlan0_tx < "${wlan0}/tx_bytes"
22
23 # get time and sum of rx/tx for combined display
24 time=$(date +%s)
25 rx=$(( $eth0_rx + $wlan0_rx ))
26 tx=$(( $eth0_tx + $wlan0_tx ))
27
28 # write current data if file does not exist. Do not exit, this will cause
29 # problems if this file is sourced instead of executed as another process.
30 if ! [[ -f "${path}" ]]; then
31   echo "${time} ${rx} ${tx}" > "${path}"
32   chmod 0666 "${path}"
33 fi
34
35 # read previous state and update data storage
36 read old < "${path}"
37 echo "${time} ${rx} ${tx}" > "${path}"
38
39 # parse old data and calc time passed
40 old=(${old//;/ })
41 time_diff=$(( $time - ${old[0]} ))
42
43 # sanity check: has a positive amount of time passed
44 if [[ "${time_diff}" -gt 0 ]]; then
45   # calc bytes transferred, and their rate in byte/s
46   rx_diff=$(( $rx - ${old[1]} ))
47   tx_diff=$(( $tx - ${old[2]} ))
48   rx_rate=$(( $rx_diff / $time_diff ))
49   tx_rate=$(( $tx_diff / $time_diff ))
50
51   # shift by 10 bytes to get KiB/s. If the value is larger than
52   # 1024^2 = 1048576, then display MiB/s instead (simply cut off  
53   # the last two digits of KiB/s). Since the values only give an  
54   # rough estimate anyway, this improper rounding is negligible.
55
56   # incoming
57   rx_kib=$(( $rx_rate >> 10 ))
58   if [[ "$rx_rate" -gt 1048576 ]]; then
59     echo -n "${rx_kib:0:-3}.${rx_kib: -3:-2} M↓"
60   else
61     echo -n "${rx_kib} K↓"
62   fi
63
64   echo -n "  "
65
66   # outgoing
67   tx_kib=$(( $tx_rate >> 10 ))
68   if [[ "$tx_rate" -gt 1048576 ]]; then
69     echo -n "${tx_kib:0:-3}.${tx_kib: -3:-2} M↑"
70   else
71     echo -n "${tx_kib} K↑"
72   fi
73 else
74   echo -n " ? "
75 fi