Show current traffic in the XFCE panel

Posted on Wed 21 August 2024 in linux • 2 min read

The XFCE panel has some monitoring plugins one can enable, but theese are always displaying a graph, not the current value. I was looking for something which will display the network traffic in a compact form, which was not available. As it is possible to apply css to the generic monitor texts, I came up with the following script which will display the traffic of the default device.

This looks something like this:

Image showing some sample traffic data

#!/bin/bash

DEVICE=$(ip route show default | awk '/dev/ {print $5}')
RUNP=${XDG_RUNTIME_DIR}/xfce-genmon-traffic/${DEVICE}

mkdir -p "${RUNP}"

rx2=$(cat "/sys/class/net/${DEVICE}/statistics/rx_bytes")
tx2=$(cat "/sys/class/net/${DEVICE}/statistics/tx_bytes")
dt2=$EPOCHREALTIME

if [ -f "${RUNP}/timestamp" ]
then
    rx1=$(cat "${RUNP}/rx_bytes")
    tx1=$(cat "${RUNP}/tx_bytes")
    dt1=$(cat "${RUNP}/timestamp")
    dt=$(echo "$dt2 - $dt1" | bc )

    rx=$(echo "($rx2 - $rx1) / $dt * 8" | bc)
    tx=$(echo "($tx2 - $tx1) / $dt * 8" | bc)
    rxk=$(( rx / 1000 ))
    txk=$(( tx / 1000 ))
    rxm=$(( rxk / 1000 ))
    txm=$(( txk / 1000 ))
    rxg=$(( rxm / 1000 ))
    txg=$(( txm / 1000 ))

    rxt="${rxk} k"
    txt="${txk} k"
    [ $rxm -gt 5 ] && rxt="${rxm} M"
    [ $txm -gt 5 ] && txt="${txm} M"
    [ $rxg -gt 5 ] && rxt="${rxg} G"
    [ $txg -gt 5 ] && txt="${txg} G"
else
    rxt="- k"
    txt="- k"
    rxk=0
    txk=0
fi

echo -n "<txt><tt><span size='75%' line_height='0.9'>"
echo -n " In: "
if [ "$rxk" -gt 2 ]
then
    echo "$(printf "%6s" "${rxt}")bit/s"
else
    echo "           "
fi
echo -n "Out: "
if [ "$txk" -gt 2 ]
then
    echo -n "$(printf "%6s" "${txt}")bit/s"
else
    echo -n "           "
fi
echo "</span></tt></txt>"
echo "<tool></tool>"
echo "<css>.genmon_value { padding-left: 10px; padding-right: 7px}</css>"

echo "$rx2" > "${RUNP}/rx_bytes"
echo "$tx2" > "${RUNP}/tx_bytes"
echo "$dt2" > "${RUNP}/timestamp"

The first version simply used a sleep, but this will make the whole panel unresponsive. It is important that the scripts exits quickly, thus the solution with the temporary files. They should end up on a tmpfs, so nothing is saved to a disk.

If there is less than 2kbit/s of traffic, it will display a blank value. Prefixes range from k to G by default.