Skip to content

Instantly share code, notes, and snippets.

@SpareSimian
Last active May 25, 2023 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpareSimian/257c0737f07d419c70338d1306238d0f to your computer and use it in GitHub Desktop.
Save SpareSimian/257c0737f07d419c70338d1306238d0f to your computer and use it in GitHub Desktop.
Display interface bit rates on Adafruit LCD display for eth0 and eth1
import copy
import time
import Adafruit_CharLCD as LCD
ifstats = {
"eth0": { "tx": 0, "rx": 0 },
"eth1": { "tx": 0, "rx": 0 }
}
ifnames = [ "eth0", "eth1" ]
ifstats_prev = copy.deepcopy(ifstats)
lastTime = time.time_ns()
deltaTime = 1;
def get_ifstats():
global deltaTime
global lastTime
global ifstats_prev
global ifstats
# find the time delta since last reading
now = time.time_ns()
deltaTime = now - lastTime
lastTime = now
# avoid divide by zero in rate calculation
if 0 == deltaTime:
deltaTime = 1
# save previous stats for delta computation
ifstats_prev = copy.deepcopy(ifstats)
# parse the current stats (pseudo-file has one line per interface, including lo and wlan0)
with open("/proc/net/dev", "r") as f:
for index, line in enumerate(f):
fields = line.split()
for ifname in ifnames:
if fields[0] == (ifname + ":"):
ifstats[ifname]["rx"] = int(fields[1])
ifstats[ifname]["tx"] = int(fields[9])
# we only have 8 characters for the number, so display up to 1 Gbps in kbps
def scale_bps(bytesNow, bytesPrev, deltaTimeNS):
deltaBits = 8 * (bytesNow - bytesPrev)
bytesPerNS = deltaBits / deltaTimeNS
kBitsPerSec = 1000000 * bytesPerNS
return int(kBitsPerSec)
try:
# Initialize the LCD using the pins
lcd = LCD.Adafruit_CharLCDBackpack(address=0x21)
# turn LCD backlight on
lcd.set_backlight(0)
lcd.clear()
get_ifstats()
while True:
time.sleep(1)
get_ifstats()
eth0_tx_bps = scale_bps(ifstats["eth0"]["tx"], ifstats_prev["eth0"]["tx"], deltaTime)
eth0_rx_bps = scale_bps(ifstats["eth0"]["rx"], ifstats_prev["eth0"]["rx"], deltaTime)
eth1_tx_bps = scale_bps(ifstats["eth1"]["tx"], ifstats_prev["eth1"]["tx"], deltaTime)
eth1_rx_bps = scale_bps(ifstats["eth1"]["rx"], ifstats_prev["eth1"]["rx"], deltaTime)
lcdline = "{:>8}{:>8}\n{:>8}{:>8}".format(eth0_rx_bps, eth0_tx_bps, eth1_rx_bps, eth1_tx_bps)
lcd.home()
lcd.message(lcdline)
#print(lcdline + "\n")
# hit control-C to exit quietly
except KeyboardInterrupt:
pass
finally:
# turn off the backlight on exit
lcd.set_backlight(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment