#!/usr/bin/env python

from time import time, sleep
from math import log

def main():
    dev = "eno1"
    sleep_interval = 1.0
    bw_max = 100e6 # 100Mbit/s

    rx_bytes_file = "/sys/class/net/{}/statistics/rx_bytes".format(dev)
    tx_bytes_file = "/sys/class/net/{}/statistics/tx_bytes".format(dev)

    time_last = time()
    with open(rx_bytes_file) as fd:
        rx_bytes_last = int(fd.read())
    with open(tx_bytes_file) as fd:
        tx_bytes_last = int(fd.read())
    sleep_next = sleep_interval

    while True:
        sleep(sleep_next)

        time_now = time()
        with open(rx_bytes_file) as fd:
            rx_bytes_now = int(fd.read())
        with open(tx_bytes_file) as fd:
            tx_bytes_now = int(fd.read())

        rx_bytes_diff = rx_bytes_now - rx_bytes_last
        tx_bytes_diff = tx_bytes_now - tx_bytes_last
        time_diff = time_now - time_last

        rx_bw = rx_bytes_diff / time_diff
        tx_bw = tx_bytes_diff / time_diff

        print "RX: {:15.0f} B, {:10.0f} B/s {:>30s} | {:<30s} TX: {:15.0f} B, {:10.0f} B/s".format(
                rx_bytes_now,
                rx_bw,

                "#" * int(log(rx_bw)),
                "#" * int(log(tx_bw)),

                #"#" * int(rx_bw * 30. / bw_max),
                #"#" * int(tx_bw * 30. / bw_max),

                tx_bytes_now,
                tx_bw)

        sleep_next = (sleep_interval * 1.5) + (time_diff * -0.5)
        if sleep_next < 0:
            sleep_next = 0

        rx_bytes_last = rx_bytes_now
        tx_bytes_last = tx_bytes_now
        time_last = time_now

if __name__ == "__main__":
    main()
