Graph.py 5.05 KB
Newer Older
1
from datetime import datetime
2
from pathlib import Path
3
from PyQt5.QtCore import QTimer
Pedro Henrique Kopper's avatar
Pedro Henrique Kopper committed
4
from pyqtgraph import AxisItem, InfiniteLine, mkColor, mkPen, setConfigOption
5
from interfaces import *
6
from config import Config
7
from util.Logger import Logger
8
import pyqtgraph as pg
9

10
class Graph():
11
    def __init__(self, ui, interval, parent=None):
12
        self.running = True
13
        self.logger = Logger()
14
        self.interval = interval#/1000.0
15 16
        self.dataX = []
        self.dataY = []
17 18
        self.ui = ui
        self.graph = ui.mainGraph
19 20
        self.plots = []
        self.axis = []
21 22 23 24
        #try:
        self.config = Config().data
        #except FileNotFoundError:
        #    logger("[FATAL]", "Arquivo de configuração não encontrado!")
25
        self.device = self.config["device"]
26

27
        self._configurePlots()
28 29 30 31

        self.lastupdated = 0
        pg.setConfigOptions(useOpenGL=True)

32 33 34 35 36
        #try:
        self.interface = INTERFACES[self.device["type"]](self.device["location"], self.device["channels"])
        #except:
        #    self.running = False
        #    logger("[FATAL]", "Erro ao abrir a interface!")
37 38 39 40 41 42

        print(ui.samplingBox)
        ui.min_amostra.valueChanged.connect(self.updateScale)
        ui.min_pressao.valueChanged.connect(self.updateScale)
        ui.max_amostra.valueChanged.connect(self.updateScale)
        ui.max_pressao.valueChanged.connect(self.updateScale)
43

44
        self.graph.setBackground((240, 240, 240))
Pedro Henrique Kopper's avatar
Pedro Henrique Kopper committed
45

46 47 48 49
    def updateGraphs(self):
        for i, channel in enumerate(self.device["channels"]):
            self.dataX[i].append(self.dataX[i][-1] + self.interval/1000.0)
            self.dataY[i].append(self.interface.read(self.device["channels"][i]))
50
            self.plots[i].setData(self.dataX[i], self.dataY[i])
51
        self.combinedPlot.setData(self.dataY[1], self.dataY[0])
52 53 54

        dados = "{}, {}, {}".format(self.dataY[0][-1], self.dataY[1][-1], self.dataX[0][-1])
        self.logger.writeLog("acquisicao", dados, isCSV=True)
55

56 57
        self.ui.forceLabel.setText("{:.0f} bar".format(self.dataY[1][-1]))
        self.ui.calibratorLabel.setText("{:.2f} mV".format(self.dataY[0][-1] * 1000))
58
        pg.QtGui.QApplication.processEvents()
59

60 61 62 63 64
    def updateScale(self):
        minX = self.ui.min_pressao.value()
        minY = self.ui.min_amostra.value() / 1000.0
        maxX = self.ui.max_pressao.value()
        maxY = self.ui.max_amostra.value() / 1000.0
65

66 67
        self.combinedPlot.getViewBox().setRange(xRange=(minX, maxX), yRange=(minY, maxY))

68
    def setInterval(self, interval):
69
        self.interval = interval
70

71 72 73
    def restart(self):
        self.running = True

74
    def stop(self):
75 76 77 78 79
        self.running = False

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

    def _configurePlots(self):
82
        self.debugLayout = self.graph.addLayout()
83 84 85

        header = ""

86 87
        for i, channel in enumerate(self.device["channels"]):
            plotItem = self.debugLayout.addPlot(row=i, col=1)
88
            plotItem.setMenuEnabled(False) # Previne acesso ao menu do pyqtgraph pelos usuários
89
            plot = plotItem.plot(pen=mkPen(mkColor(channel["color"]), width=2), name=channel["id"])
90 91 92
            self.plots.append(plot)
            plotItem.setClipToView(True)
            plotItem.showGrid(True)
93 94
            self.dataX.append([0])
            self.dataY.append([0])
95
            plotItem.setLabel("left", text=channel["name"], units=channel["unit"])
96 97
            header += "{},".format(channel["name"])

98 99 100 101
        self.ui.min_amostra.setSuffix(self.device["channels"][0]["unit"])
        self.ui.min_pressao.setSuffix(self.device["channels"][1]["unit"])
        self.ui.max_amostra.setSuffix(self.device["channels"][0]["unit"])
        self.ui.max_pressao.setSuffix(self.device["channels"][1]["unit"])
102

103 104
        header += "timestamp"
        self.logger.writeLog("acquisicao", header, isCSV=True)
105

106 107 108
        # Faz com que ambos eixos X se movam juntos sempre
        # TODO: escrever de forma mais limpa
        self.plots[0].getViewBox().linkView(self.plots[0].getViewBox().XAxis, self.plots[1].getViewBox())
109

110
        self.combinedPlot = self.debugLayout.addPlot(row=0, col=2, rowspan=2)
111 112 113
        self.combinedPlot.setClipToView(True)
        self.combinedPlot.showGrid(True)
        self.combinedPlot.getViewBox().enableAutoRange(plotItem.getViewBox().YAxis)
114 115
        self.combinedPlot.setLabel("left", text=self.device["channels"][0]["name"], units=self.device["channels"][0]["unit"])
        self.combinedPlot.setLabel("bottom", text=self.device["channels"][1]["name"], units=self.device["channels"][1]["unit"])
116 117
        self.combinedPlot.getViewBox().setMouseEnabled(False, False) # Previne uso do mouse para controle do zoom
        self.combinedPlot.setMenuEnabled(False) # Previne acesso ao menu do pyqtgraph pelos usuários
118 119 120
        qGraphicsGridLayout = self.debugLayout.layout
        qGraphicsGridLayout.setColumnStretchFactor(1, 1)
        qGraphicsGridLayout.setColumnStretchFactor(2, 3)
121 122

        self.combinedPlot = self.combinedPlot.plot(pen=mkPen(mkColor("#FF0000"), width=2))