Graph.py 2.6 KB
Newer Older
1 2
from time import sleep
from PyQt5.QtCore import QThread
3
from pyqtgraph import AxisItem, InfiniteLine, mkColor, mkPen
4
from interfaces import *
5
from config import Config
6 7

class Graph(QThread):
8
    def __init__(self, graph, interval, logger, parent=None):
9 10
        super(Graph, self).__init__(parent)
        self.running = True
11
        self.logger = logger
12
        self.interval = interval/1000.0
13 14 15 16 17 18 19 20
        self.dataX = []
        self.dataY = []
        self.graph = graph
        self.plots = []
        self.axis = []

        self.config = Config().data
        self._configurePlots()
21
        device = self.config["device"]
22 23 24 25
        try:
            self.interface = INTERFACES[device["type"]](logger, device["location"], device["channels"])
        except FileNotFoundError:
            self.running = False
26 27 28

    def run(self):
        while self.running:
29
            data = self.interface.readAll()
30
            self.graph.getPlotItem().getViewBox().setRange(xRange=(self.dataX[0][-1] - 10, self.dataX[0][-1])) # Força atualização do range do x com span de 5 segundos
31 32
            for i, channel in enumerate(self.plots):
                self.dataX[i].append(self.dataX[i][-1] + self.interval)
33
                self.dataY[i].append(data[i])
34
                channel.setData(self.dataX[i], self.dataY[i])
35 36 37 38 39 40
            sleep(self.interval)

    def setInterval(self, interval):
        self.interval = interval/1000.0

    def stop(self):
41 42 43 44 45
        self.running = False

    def addMarker(self, label):
        marker = InfiniteLine(angle=90, pos=self.dataX[0][-1], label=label)
        self.graph.getPlotItem().addItem(marker)
46 47

    def _configurePlots(self):
48
        first = True
49 50 51 52 53 54
        pltItem = self.graph.getPlotItem()
        pltItem.setClipToView(True)
        pltItem.showGrid(True)
        pltItem.addLegend()
        pltItem.getViewBox().enableAutoRange()
        pltItem.getViewBox().setAutoPan(x=True)
55 56 57 58 59
        self.logger("[GRAPH]", "Found new device {}".format(self.config["device"]["type"]))
        for channel in self.config["device"]["channels"]:
            self.logger("[GRAPH]", "Added channel {}".format(channel["name"]))
            self.dataX.append([0])
            self.dataY.append([0])
60 61 62
            plot = self.graph.plot(pen=mkPen(mkColor(channel["color"]), width=2), name=channel["name"])
            self.plots.append(plot)
            if first:
63
                pltItem.setLabel("left", text=channel["name"], units=channel["unit"])
64 65
                first = False
            else:
66
                pltItem.setLabel("right", text=channel["name"], units=channel["unit"])
67
        
68
        pltItem.setLabel("bottom", text="Tempo", units="s")