live.py 13.5 KB
Newer Older
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# -*- coding: utf-8 -*-

import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Button
import numpy as np

import time
from collections import deque

from .gui_base import GuiBase

VALUES_TO_PLOT = ['cwnd', 'sst', 'rtt', 'bw'] # (only values for Y-axis)
VALUES_TO_PROCESS = ['time']  + VALUES_TO_PLOT #helper to init all data structures

# Strings for UI-elements
FIGURE_TITLE = "TCPplot"
PLOT_TITLE = "Data from"
PAUSE = "Pause"
QUIT = "Quit"

# constants
CLEAR_GAP = 0.2 # gap in s
INFINITY_THRESHOLD = 1e8



class LiveGui(GuiBase):
    def __init__(self, options, infoRegistry):
        self.options = options
        self.infoRegistry = infoRegistry

    def tearDown(self):
        pass

    def startUp(self):
        pass

    def startupCheck(self):
        pass

    def pause(self, event):
        """Toggles pause flag."""
        self.__paused ^= True
        return

    def toggleVisibility(self, lineID):
        """Toggles visibility for given line."""
        for port in self.options.filterPorts:
            self.__plotLineConfigs[port][lineID] ^= True
            self.__plotLines[port][lineID].set_visible(self.__plotLineConfigs[port][lineID])
        self.drawPlotLegend()

    def drawPlotLegend(self):
        """(Re)draws legend with visible lines."""
        labelObjs  = []
        labelTexts = []
        for port in self.options.filterPorts:
            for val in VALUES_TO_PLOT:
                if(self.__plotLineConfigs[port][val]):
                    labelObjs.append(self.__plotLines[port][val])
                    labelTexts.append(self.__plotLines[port][val].get_label())
        if(len(labelObjs) > 0):
            self.__ax.legend(labelObjs, labelTexts, fontsize='small')
        else:
            self.__ax.legend_.remove()

    def plotKeyPressCallback(self, event):
        """Callback to handle key presses."""
        if(self.options.debug):
            print("Key pressed: '" + event.key + "'")

        # p pauses
        if(event.key == "p"):
            self.pause(event)
        # ctrl+{c,q,w} quits programm
        elif(event.key == "ctrl+c" or event.key == "ctrl+w" or event.key == "ctrl+q"):
            raise SystemExit
        else:
            try:
                index = int(event.key)
            except ValueError:
                pass
            else:
                # Numbers 1-N toggle visibility of lines
                if index in range(1, len(VALUES_TO_PLOT)+1):
                    self.toggleVisibility(VALUES_TO_PLOT[(index-1)])

    def stopPlotting(self, event):
        """Callback function to stop plotting and the programm."""
        self.__tmpTimestamp = time.perf_counter()
        plt.close()
        self.tearDown()

    def plotGraph(self):
        """Initializes plot configuration and starts the plotting."""
        self.__paused = False
        self.__minVal = 9999999999
        self.__maxVal = 0


        fig = plt.figure(FIGURE_TITLE)
        fig.canvas.mpl_connect('key_press_event', self.plotKeyPressCallback)
        self.__ax = plt.axes()
        self.__ax.set_autoscaley_on(False)
        self.__ax.set_xlim(0, self.options.xDelta)
        self.__ax.set_title(PLOT_TITLE + " :" + ', :'.join(map(str, self.options.filterPorts)))

        self.__plotLines = {}
        self.__plotValues = {}
        self.__plotLineConfigs = {}
        for port in self.options.filterPorts:
            self.__plotLines[port] = {}
            self.__plotValues[port] = {}
            self.__plotLineConfigs[port] = {}
            self.__plotLineConfigs[port]['lastTimestamp'] = 0
            for val in VALUES_TO_PROCESS:
                self.__plotValues[port][val] = deque(maxlen=(int(self.options.xDelta / self.options.plotResolution * 10)))
            index = 1
            for val in VALUES_TO_PLOT:
                self.__plotLines[port][val], = self.__ax.plot([])
                self.__plotLines[port][val].set_label("[" + str(index) + "] " + val + " - " + str(port) + "")
                self.__plotLineConfigs[port][val] = True
                self.__plotLines[port][val].set_visible(True)
                index += 1
        self.drawPlotLegend()

        # pause button
        pauseAx = plt.axes([0.8, 0.025, 0.1, 0.04])
        pauseButton = Button(pauseAx, PAUSE)
        pauseButton.on_clicked(self.pause)

        # quit button
        quitAx = plt.axes([0.125, 0.025, 0.1, 0.04])
        quitButton = Button(quitAx, QUIT)
        quitButton.on_clicked(self.stopPlotting)

        if(self.options.preloadBuffer > 0):
            self.__preloading = True
        else:
            self.__preloading = False

        self.__lastPlotTimestamp = {}
        for port in self.options.filterPorts:
            self.__lastPlotTimestamp[port] = 0
        self.__lastDrawTimestamp = 0
        self.__initRealtimeTimestamp = 0
        self.__initSampletimeTimestamp = -1

        self.__timeOffset = 0
        self.__bufferFactor = 1
        self.__apsFixFactor = 1

        # call update-routine
        animation.FuncAnimation(fig, self.plotGraphUpdate, init_func=self.plotInit,
                               frames=self.options.drawFps, interval=self.options.drawIntervall, blit=self.options.blitting, repeat=True)
        if self.__stopped.isSet():
            return
        else:
            plt.show()

    def returnAllLines(self):
        """Macro to return all lines as they are."""
        allPlotLines = []
        for port in self.options.filterPorts:
            for val in VALUES_TO_PLOT:
                allPlotLines.append(self.__plotLines[port][val])
        return tuple(allPlotLines)

    def returnNanSample(self, time):
        """Macro to return NaN-Samples (to fill plot)."""
        data = {}
        data['time'] = time - self.options.plotResolution
        for val in VALUES_TO_PLOT:
            data[val] = np.nan
        return data

    def plotGraphUpdate(self, i):
        """Animation loop - does the actual plot update."""
        if(self.__initSampletimeTimestamp == -1):
            self.__initSampletimeTimestamp = 0
            return self.returnAllLines()
        elif(self.__initSampletimeTimestamp == 0):
            self.calculateSampleTimeOffset()
            return self.returnAllLines()

        # fill playback-buffer
        if(self.__preloading):
            bufferLength = -1
            for port in self.options.filterPorts:
                bufferLength = max(bufferLength, len(self.__connectionBuffer[port]))

            if(bufferLength > 0):
                bufferedTime = bufferLength * self.options.plotResolution
                bufferTarget = self.options.preloadBuffer * self.__bufferFactor
                if(bufferedTime >= bufferTarget):
                    self.__preloading = False
                    # reduce buffer-target to half size after initial buffering
                    self.__bufferFactor = 0.5
                    print("Buffer filled.")
            if(self.__preloading):
                print("Buffering... " + str(format(bufferedTime, ".2f")) + "/" + str(format(bufferTarget, ".2f")))
                return self.returnAllLines()

        if(self.__paused == True):
            return self.returnAllLines()
        else:
            while(True):
                currentTimestamp = time.perf_counter()
                if(self.__initRealtimeTimestamp == 0):
                    self.__initRealtimeTimestamp = currentTimestamp
                timestampDelta = (currentTimestamp - self.__lastDrawTimestamp) * self.options.playbackSpeed * self.__apsFixFactor

                currentXmin, currentXmax = self.__ax.get_xlim()
                currentYmin, currentYmax = self.__ax.get_ylim()
                newXmax = currentTimestamp - self.options.preloadBuffer
                newXmin = newXmax - self.options.xDelta
                self.__ax.set_xlim(newXmin, newXmax)

                maxYval = 0
                minYval = 9999999
                connectionsData = {}

                # skip this cycle, plot resolution not yet reached
                if(timestampDelta < self.options.plotResolution):
                    return self.returnAllLines()

                for port in self.options.filterPorts:
                    connectionsData[port] = deque()
                    whileRun = True
                    while(len(self.__connectionBuffer[port]) > 0 and whileRun):
                        try:
                            data = self.__connectionBuffer[port].popleft()
                        except IndexError:
                            whileRun = False
                            pass
                        else:
                            lineTime = self.__initRealtimeTimestamp  + (data['time'] - self.__initSampletimeTimestamp)
                            # time in past
                            if(lineTime < newXmin):
                                continue
                            # time older than newst timestamp
                            elif(lineTime < self.__lastPlotTimestamp[port]):
                                continue
                            # skip this sample due plot plotResolution
                            elif((lineTime - self.__lastPlotTimestamp[port]) < self.options.plotResolution):
                                continue
                            else:
                                if(self.__lastPlotTimestamp[port] > 0 and ((lineTime - self.__lastPlotTimestamp[port]) > CLEAR_GAP)):
                                    self.__lastPlotTimestamp[port] = lineTime
                                    nanSample = self.returnNanSample(lineTime)
                                    connectionsData[port].append(nanSample)
                                infinityReached = False
                                for val in VALUES_TO_PLOT:
                                    if(data[val] > INFINITY_THRESHOLD):
                                        data[val] = np.nan
                                        # nanSample = self.returnNanSample(lineTime)
                                        # connectionsData[port].append(nanSample)
                                        # infinityReached = True

                                if(not infinityReached):
                                    self.__lastPlotTimestamp[port] = lineTime
                                    connectionsData[port].append(data)

                data = 0
                for port in connectionsData:
                    if(len(connectionsData[port]) > 0):
                        data += 1

                for port in self.options.filterPorts:
                    if(data < 1 and currentTimestamp > self.__lastPlotTimestamp[port] ):
                        if(self.options.debug):
                            print("No data for any connection.")
                        if(self.options.interimBuffering):
                            self.__preloading = True
                        return self.returnAllLines()



                for connection in connectionsData:
                    while(len(connectionsData[connection]) > 0):
                        data = connectionsData[connection].popleft()

                        lineTime = self.__initRealtimeTimestamp  + (data['time'] - self.__initSampletimeTimestamp)
                        self.__plotLineConfigs[connection]['lastTimestamp'] = data['time']

                        for val in VALUES_TO_PROCESS:
                            if(val == 'time'):
                                self.__plotValues[connection][val].append(lineTime)
                            else:
                                self.__plotValues[connection][val].append(data[val])

                    for val in VALUES_TO_PLOT:
                        self.__plotLines[connection][val].set_data(self.__plotValues[connection]['time'], self.__plotValues[connection][val])


                for port in self.options.filterPorts:
                    for val in VALUES_TO_PLOT:
                        if(self.__plotLineConfigs[port][val]):
                            if(len(self.__plotValues[port][val]) > 0):
                                maxYval = max(maxYval, max(self.__plotValues[port][val]))
                                minYval = min(minYval, min(self.__plotValues[port][val]))

                if(maxYval > 0):
                    newYmin = minYval - 50
                    newYmin = max(newYmin, 0)
                    newYmax = maxYval * 2
                    self.__ax.set_ylim(newYmin, newYmax)

                self.__lastDrawTimestamp = time.perf_counter()
                return self.returnAllLines()

    def plotInit(self):
        """Helper to initialize plot."""
        for port in self.options.filterPorts:
            for val in VALUES_TO_PLOT:
                self.__plotLines[port][val].set_data([], [])

                # hide "invisible" lines
                if(val not in self.options.linesToShow):
                    self.__plotLineConfigs[port][val] = False
                    self.__plotLines[port][val].set_visible(False)



        newXmin = 0
        newXmax = newXmin + self.options.xDelta
        self.__ax.set_xlim(newXmin, newXmax)

        if(self.options.debug):
            print("Plot init done.")

        return self.returnAllLines()

    def calculateSampleTimeOffset(self):
        """Calculate SampleTime difference at start"""
        for port in self.options.filterPorts:
            try:
                data = self.__connectionBuffer[port].popleft()
            except IndexError:
                pass
            else:
                #re-add first sample (to head of dequeue)
                self.__connectionBuffer[port].appendleft(data)
                self.__initSampletimeTimestamp = float(data['time'])
                return