-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathping.py
More file actions
95 lines (72 loc) · 2.94 KB
/
ping.py
File metadata and controls
95 lines (72 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import argparse
import datetime as dt
import matplotlib as mpl
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from pythonping import ping
# disables default toolbar
# comment out this line if you wanna show them.
mpl.rcParams['toolbar'] = 'None'
plt.style.use('dark_background')
class Pinger:
TIMEOUT = 2000 # default timeout (in ms)
def __init__(self, host: str, timeout: int = TIMEOUT):
self.host = host
self.timeout = timeout
def call(self) -> float:
try:
resp = ping(self.host, count=1, timeout=self.timeout/1000)
rtt = resp.rtt_avg_ms
except Exception as e:
rtt = self.timeout
return rtt
class PingPlotter:
LIMIT = 100 # default limit of data points to display
INTERVAL = 100 # default interval between pings (in ms)
def __init__(self, pinger: Pinger, limit: int = LIMIT, interval: int = INTERVAL):
self.pinger = pinger
self.limit = limit
self.interval = interval
# Initialize data points
self.timestamps = []
self.rtts = []
# init plot
self.fig, self.ax = plt.subplots()
def __update_data(self):
rtt = self.pinger.call()
self.timestamps.append(dt.datetime.now())
self.timestamps = self.timestamps[-self.limit:]
self.rtts.append(rtt)
self.rtts = self.rtts[-self.limit:]
def __render_frame(self, i: int):
self.__update_data()
self.ax.clear()
self.ax.grid(True, ls='--', lw=0.25)
self.ax.plot_date(self.timestamps, self.rtts,
linestyle='solid', ds='steps', marker='None')
host = self.pinger.host
plt.title('Latency over time to {}'.format(host))
plt.ylabel('Round-trip time (ms)')
def start(self):
# assign to variable to avoid garbage collection.
a = animation.FuncAnimation(
fig=self.fig,
func=self.__render_frame,
interval=self.interval,
)
plt.show()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Plots a real-time graph of ping latency.")
parser.add_argument('-H', '--host', dest='host',
default='8.8.8.8', type=str, help='the host to ping')
parser.add_argument('-i', '--interval', dest='interval', default=PingPlotter.INTERVAL,
type=int, help='the interval (in ms) between consecutive ping calls')
parser.add_argument('-l', '--limit', dest='limit', default=PingPlotter.LIMIT,
type=int, help='max number of data points to display')
parser.add_argument('-t', '--timeout', dest='timeout',
default=Pinger.TIMEOUT, type=int, help='max ping timeout (in ms)')
args = parser.parse_args()
pinger = Pinger(args.host, timeout=args.timeout)
plotter = PingPlotter(pinger, limit=args.limit, interval=args.interval)
plotter.start()