1
0
mirror of https://github.com/dcarrillo/dotfiles.git synced 2024-12-23 18:26:48 +00:00
dotfiles/.config/polybar/scripts/network_usage

61 lines
1.6 KiB
Plaintext
Raw Normal View History

#!/usr/bin/env bash
COUNTER_FILE=/dev/shm/polybar_network_usage
REFRESH=2
get_icon_by_device()
{
device=$1
device_type=$(nmcli -t device status | grep -E -m 1 "^$device" | cut -f 2 -d ":")
case "$device_type" in
ethernet)
icon=""
;;
wifi)
ssid=$(nmcli -t device status | grep -E -m 1 "^$device" | cut -f 4 -d ":")
icon=" $ssid"
;;
*)
icon=""
;;
esac
echo $icon
}
while true; do
default_device=$(ip route list | grep -Fm 1 default | cut -d " " -f 5)
icon=$(get_icon_by_device "$default_device")
now=$(date +%s)
counter_age=$(stat --format %Z $COUNTER_FILE 2>/dev/null)
if [ -f $COUNTER_FILE ] && [ $((now-counter_age)) -lt $((REFRESH+1)) ]; then
last_value_in=$(cut -f 1 -d " " $COUNTER_FILE)
last_value_out=$(cut -f 2 -d " " $COUNTER_FILE)
fi
current_values=$(awk -v dev="${default_device}:" '{
if ($1 == dev) print $2,$10
}' < /proc/net/dev)
current_bytes_in=$(echo "$current_values" | cut -f 1 -d " ")
current_bytes_out=$(echo "$current_values" | cut -f 2 -d " ")
if [ -n "$last_value_in" ]; then
bits_in=$((((current_bytes_in-last_value_in) / REFRESH) * 8))
bits_out=$((((current_bytes_out-last_value_out) / REFRESH) * 8))
output=$(numfmt --to iec --format "%8.2f" -z "$bits_in" "$bits_out" 2>/dev/null)
echo "$icon $output"
else
echo "$icon -- --"
fi
echo "$current_values">$COUNTER_FILE
unset last_value
sleep $REFRESH
done