Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import copy
- import time
- import Adafruit_CharLCD as LCD
- ifstats = {
- "eth0": { "tx": 0, "rx": 0 },
- "eth1": { "tx": 0, "rx": 0 }
- }
- ifstats_prev = copy.deepcopy(ifstats)
- def get_ifstats(line, ifname):
- """if ifname found on this line, insert counters into dict"""
- fields = line.split()
- 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
- kbytesPerSec = 1000000 * bytesPerNS
- return int(kbytesPerSec)
- try:
- # Initialize the LCD using the pins
- lcd = LCD.Adafruit_CharLCDBackpack(address=0x21)
- # turn LCD backlight on
- lcd.set_backlight(0)
- lastTime = time.time_ns()
- while True:
- lcd.clear()
- # 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
- # 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):
- get_ifstats(line, "eth0")
- get_ifstats(line, "eth1")
- 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)
- ifstats_prev = copy.deepcopy(ifstats)
- lcdline = "{:>8}{:>8}\n{:>8}{:>8}".format(eth0_rx_bps, eth0_tx_bps, eth1_rx_bps, eth1_tx_bps)
- lcd.message(lcdline)
- print(lcdline + "\n")
- time.sleep(2)
- except KeyboardInterrupt:
- pass
- finally:
- lcd.set_backlight(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement