Advertisement
ScratchMonkey

netstats2lcd.py

May 22nd, 2023
920
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | Source Code | 0 0
  1. import copy
  2. import time
  3. import Adafruit_CharLCD as LCD
  4.  
  5. ifstats = {
  6.     "eth0": { "tx": 0, "rx": 0 },
  7.     "eth1": { "tx": 0, "rx": 0 }
  8. }
  9.  
  10. ifstats_prev = copy.deepcopy(ifstats)
  11.  
  12. def get_ifstats(line, ifname):
  13.     """if ifname found on this line, insert counters into dict"""
  14.     fields = line.split()
  15.     if fields[0] == (ifname + ":"):
  16.         ifstats[ifname]["rx"] = int(fields[1])
  17.         ifstats[ifname]["tx"] = int(fields[9])
  18.  
  19. # we only have 8 characters for the number, so display up to 1 Gbps in kbps
  20.  
  21. def scale_bps(bytesNow, bytesPrev, deltaTimeNS):
  22.     deltaBits = 8 * (bytesNow - bytesPrev)
  23.     bytesPerNS = deltaBits / deltaTimeNS
  24.     kbytesPerSec = 1000000 * bytesPerNS
  25.     return int(kbytesPerSec)
  26.  
  27. try:
  28.     # Initialize the LCD using the pins
  29.     lcd = LCD.Adafruit_CharLCDBackpack(address=0x21)
  30.     # turn LCD backlight on
  31.     lcd.set_backlight(0)
  32.     lastTime = time.time_ns()
  33.    
  34.     while True:
  35.         lcd.clear()
  36.         # find the time delta since last reading
  37.         now = time.time_ns()
  38.         deltaTime = now - lastTime
  39.         lastTime = now
  40.         # avoid divide by zero in rate calculation
  41.         if 0 == deltaTime:
  42.             deltaTime = 1
  43.         # parse the current stats (pseudo-file has one line per interface, including lo and wlan0)
  44.         with open("/proc/net/dev", "r") as f:
  45.             for index, line in enumerate(f):
  46.                 get_ifstats(line, "eth0")
  47.                 get_ifstats(line, "eth1")
  48.         eth0_tx_bps = scale_bps(ifstats["eth0"]["tx"], ifstats_prev["eth0"]["tx"], deltaTime)
  49.         eth0_rx_bps = scale_bps(ifstats["eth0"]["rx"], ifstats_prev["eth0"]["rx"], deltaTime)
  50.         eth1_tx_bps = scale_bps(ifstats["eth1"]["tx"], ifstats_prev["eth1"]["tx"], deltaTime)
  51.         eth1_rx_bps = scale_bps(ifstats["eth1"]["rx"], ifstats_prev["eth1"]["rx"], deltaTime)
  52.         ifstats_prev = copy.deepcopy(ifstats)
  53.         lcdline = "{:>8}{:>8}\n{:>8}{:>8}".format(eth0_rx_bps, eth0_tx_bps, eth1_rx_bps, eth1_tx_bps)
  54.         lcd.message(lcdline)
  55.         print(lcdline + "\n")
  56.         time.sleep(2)
  57. except KeyboardInterrupt:
  58.     pass
  59. finally:
  60.     lcd.set_backlight(1)
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement