dotfiles/.i3blocks/bandwidth

81 lines
2.0 KiB
Bash
Executable File
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
runtime="${XDG_RUNTIME_DIR}/i3blocks"
[[ ! -d "$runtime" ]] && mkdir -p "$runtime"
# Interface à utiliser (sinon, celle ayant la route par défaut)
if [[ -n "$instance" ]]
then
iface="$instance"
else
iface="$(ip route | awk '/^default/ { print $5 ; exit }')"
fi
# Si l'interface est inactive on quitte sans rien afficher
if [[ ! -e "/sys/class/net/${iface}/operstate" \
|| "$(</sys/class/net/${iface}/operstate)" != "up" ]]
then
exit 0
fi
rx="$(</sys/class/net/${iface}/statistics/rx_bytes)"
tx="$(</sys/class/net/${iface}/statistics/tx_bytes)"
time="$(date +%s)"
# Récupération de la précédente mesure et stockage de l'actuelle
if [[ -f "${runtime}/bw" ]]
then
old=($(<${runtime}/bw))
fi
echo "${time} ${rx} ${tx}" > ${runtime}/bw
# Calcul du débit en octets/seconde
time_diff="$(( $time - ${old[0]} ))"
[[ "$time_diff" -eq 0 ]] && exit
rx_rate="$(( ($rx - ${old[1]}) / $time_diff ))"
tx_rate="$(( ($tx - ${old[2]}) / $time_diff ))"
# Affichage
if [[ "$rx_rate" -lt 1048576 ]]
then
# Moins de 1 Mio/s : affichage en Kio/s précis à 1 kio
rx_value=$(bc -l <<<$rx_rate/1024)
rx_unit=K
tx_prec=0
elif [[ "$rx_rate" -lt 10485760 ]]
then
# Moins de 10 Mio/s : affichage en Mio/s précis à 10 kio
rx_value=$(bc -l <<<$rx_rate/1024/1024)
rx_unit=M
rx_prec=2
else
# Plus de 10 Mio/s : affichage en Mio/s précis à 100 kio
rx_value=$(bc -l <<<$rx_rate/1024/1024)
rx_unit=M
rx_prec=1
fi
if [[ "$tx_rate" -lt 1048576 ]]
then
# Moins de 1 Mio/s : affichage en Kio/s précis à 1 kio
tx_value=$(bc -l <<<$tx_rate/1024)
tx_unit=K
tx_prec=0
elif [[ "$tx_rate" -lt 10485760 ]]
then
# Moins de 10 Mio/s : affichage en Mio/s précis à 10 kio
tx_value=$(bc -l <<<$tx_rate/1024/1024)
tx_unit=M
tx_prec=2
else
# Plus de 10 Mio/s : affichage en Mio/s précis à 100 kio
tx_value=$(bc -l <<<$tx_rate/1024/1024)
tx_unit=M
tx_prec=1
fi
# Affichage du tout dans i3blocks
printf "↓ %4.*f%s ↑ %4.*f%s\n" "${rx_prec}" "${rx_value/./,}" "${rx_unit}" "${tx_prec}" "${tx_value/./,}" "${tx_unit}"