From 99116694d7f5c77b61b0f1b60afe66ba270ec9a3 Mon Sep 17 00:00:00 2001 From: Luca Bilke <luca@bil.ke> Date: Fri, 27 Sep 2024 11:23:58 +0200 Subject: [PATCH] sb-nettraf: rewrite --- common/.local/libexec/statusbar/sb-nettraf | 50 ++++++++++++++++------ 1 file changed, 36 insertions(+), 14 deletions(-) diff --git a/common/.local/libexec/statusbar/sb-nettraf b/common/.local/libexec/statusbar/sb-nettraf index 0efd3c10..cda3cdd3 100755 --- a/common/.local/libexec/statusbar/sb-nettraf +++ b/common/.local/libexec/statusbar/sb-nettraf @@ -1,20 +1,42 @@ #!/bin/sh . libsb -# TODO: Coloring based on speed -update() { - sum=0 - for arg; do - read -r i <"$arg" - sum=$((sum + i)) - done - cache=$XDG_RUNTIME_DIR/${1##*/} - [ -f "$cache" ] && read -r old <"$cache" || old=0 - printf "%b" "$sum\n" >"$cache" - printf "%b" "$((sum - old))\n" +# NOTE: This should be executed once per second to get bps + +CACHE=$XDG_RUNTIME_DIR/nettrafcache + +get_physical_devices() { + nmcli -t -f STATE,DEVICE device | awk -F: '$1=="connected" { print $2 }' } -rx=$(update /sys/class/net/[ew]*/statistics/rx_bytes) -tx=$(update /sys/class/net/[ew]*/statistics/tx_bytes) +get_bytes() { + cat "/sys/class/net/${1}/statistics/${2}_bytes" || echo 0 +} -printf "%b%5sB %b%5sB%b" "" "$(numfmt --to=iec "$rx")" "" "$(numfmt --to=iec "$tx")" "\n" +update() { + device=$1 cache=$2 + + rx_old=$(awk '$1=="rx" { print $2 }' "$cache" || echo 0) + tx_old=$(awk '$1=="tx" { print $2 }' "$cache" || echo 0) + + rx_new=$(get_bytes "$device" rx) + tx_new=$(get_bytes "$device" tx) + + printf "rx %s\n" "$rx_new" >"$cache" + printf "tx %s\n" "$tx_new" >>"$cache" + + printf "rx=%s tx=%s" "$((rx_new - rx_old))" "$((tx_new - tx_old))" +} + +rx_sum=0 tx_sum=0 +for device in $(get_physical_devices); do + cache=${CACHE}-${device} + + rx=0 tx=0 + eval "$(update "$device" "$cache")" + + rx_sum=$((rx_sum + rx)) + tx_sum=$((tx_sum + tx)) +done + +printf " %5sB %5sB%b" "$(numfmt --to=iec "$rx_sum")" "$(numfmt --to=iec "$tx_sum")" "\n"