Implement ascii graph with max width

This commit is contained in:
Will Bradley 2015-03-27 20:59:21 +00:00
parent b68b4cd401
commit fa1ee61731

View File

@ -14,11 +14,14 @@ from gi.repository import GLib, GObject
import subprocess import subprocess
# Regex # Regex
import re import re
# Unicode
import locale
locale.setlocale(locale.LC_ALL, '')
encoding = locale.getpreferredencoding()
# Variables # Variables
host = "8.8.8.8" host = "8.8.8.8"
ping_frequency = 5 ping_frequency = 5
ping_log_max_size = 40
class Pinger: class Pinger:
ping_log = [] ping_log = []
@ -40,30 +43,45 @@ class Pinger:
else: else:
latency = "%.2f" % float(m.group(1)) latency = "%.2f" % float(m.group(1))
self.log_ping(latency) self.log_ping(latency)
if float(latency) == -1:
self.stdscr.addstr(self.count,1,"Ping: FAIL", curses.color_pair(1))
else:
self.stdscr.addstr(self.count,1,"Ping: "+latency, curses.color_pair(2))
self.count += 1 self.count += 1
GObject.timeout_add_seconds(self.timeout, self.ping) GObject.timeout_add_seconds(self.timeout, self.ping)
self.stdscr.addstr(0,0,"Internet: "+str(latency), curses.color_pair(3))
self.draw() self.draw()
def draw(self): def draw(self):
# for index, ping in enumerate(self.ping_log): for i,p in enumerate(self.ping_log):
if float(p) == -1:
graph = "E "#u'\u2847' # Error
color = curses.color_pair(1)
elif float(p) < 30:
graph = u'\u2840'
color = curses.color_pair(2)
elif float(p) < 100:
graph = u'\u2844'
color = curses.color_pair(2)
elif float(p) < 200:
graph = u'\u2846'
color = curses.color_pair(1)
else:
graph = u'\u2847'
color = curses.color_pair(1)
self.stdscr.addstr(1,i,graph.encode(encoding), color)
self.stdscr.refresh() self.stdscr.refresh()
def log_ping(self, value): def log_ping(self, value):
self.ping_log.append(float(value)) self.ping_log.append(float(value))
#self.update_log_menu() #self.update_log_menu()
# limit the size of the log # limit the size of the log
if len(self.ping_log) >= ping_log_max_size: if len(self.ping_log) >= self.ping_log_max_size:
# remove the earliest ping, not the latest # remove the earliest ping, not the latest
self.ping_log.pop(0) self.ping_log.pop(0)
def __init__(self, stdscr): def __init__(self, stdscr):
# start the ping process # start the ping process
self.stdscr = stdscr self.stdscr = stdscr
self.window_size = stdscr.getmaxyx() # returns an array [height,width]
self.ping_log_max_size = self.window_size[1] # max width
self.timeout = ping_frequency self.timeout = ping_frequency
self.count = 1 self.count = 1
self.ping() self.ping()
@ -73,6 +91,7 @@ class Pinger:
def main(stdscr): def main(stdscr):
curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLACK);
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK); curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK);
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK); curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK);