Graph.py 5.53 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
import pyqtgraph as pg
8

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

        today = datetime.now().strftime("%Y-%m-%d-%H:%M:%S")
27 28 29
        home = str(Path.home())
        self.logFile = open("{}/logs/{}-calib.csv".format(home, today), "w")
        logger("[LOGS]", "Salvando dados em: {}/logs/{}-calib.csv".format(home, today))
30
        self._configurePlots()
31 32 33 34

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

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

        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)
46

47
        self.graph.setBackground((240, 240, 240))
Pedro Henrique Kopper's avatar
Pedro Henrique Kopper committed
48

49
    def updateGraphs(self):
50
        self.logFile.write("\n")
51 52 53
        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]))
54 55 56
            #self.plots[i].getViewBox().setRange(xRange=(self.dataX[0][-1] - 10, self.dataX[0][-1]))
            self.plots[i].setData(self.dataX[i], self.dataY[i])
            self.logFile.write("{},".format(self.dataY[i][-1]))
57
        self.combinedPlot.setData(self.dataY[1], self.dataY[0])
58 59
        self.logFile.write("{}".format(self.dataX[0][-1]))
        self.logFile.flush()
60

61 62
        self.ui.forceLabel.setText("{:.0f} bar".format(self.dataY[1][-1]))
        self.ui.calibratorLabel.setText("{:.2f} mV".format(self.dataY[0][-1] * 1000))
63
        pg.QtGui.QApplication.processEvents()
64

65 66 67 68 69 70 71 72
    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
        
        self.combinedPlot.getViewBox().setRange(xRange=(minX, maxX), yRange=(minY, maxY))

73
    def setInterval(self, interval):
74
        self.interval = interval
75

76 77 78
    def restart(self):
        self.running = True

79
    def stop(self):
80 81 82 83 84
        self.running = False

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

    def _configurePlots(self):
        self.logger("[GRAPH]", "Found new device {}".format(self.config["device"]["type"]))
88 89 90
        self.debugLayout = self.graph.addLayout()
        for i, channel in enumerate(self.device["channels"]):
            plotItem = self.debugLayout.addPlot(row=i, col=1)
91
            plotItem.setMenuEnabled(False) # Previne acesso ao menu do pyqtgraph pelos usuários
92
            plot = plotItem.plot(pen=mkPen(mkColor(channel["color"]), width=2), name=channel["id"])
93 94 95
            self.plots.append(plot)
            plotItem.setClipToView(True)
            plotItem.showGrid(True)
96 97
            self.dataX.append([0])
            self.dataY.append([0])
98 99
            plotItem.setLabel("left", text=channel["name"], units=channel["unit"])
            self.logger("[GRAPH]", "Added channel {}".format(channel["name"]))
100
            self.logFile.write("{},".format(channel["name"]))
101 102 103 104 105
        
        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"])
106

107
        self.logFile.write("timestamp")
108

109 110 111
        # 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())
112

113
        self.combinedPlot = self.debugLayout.addPlot(row=0, col=2, rowspan=2)
114 115 116
        self.combinedPlot.setClipToView(True)
        self.combinedPlot.showGrid(True)
        self.combinedPlot.getViewBox().enableAutoRange(plotItem.getViewBox().YAxis)
117 118
        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"])
119 120
        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
121 122 123
        qGraphicsGridLayout = self.debugLayout.layout
        qGraphicsGridLayout.setColumnStretchFactor(1, 1)
        qGraphicsGridLayout.setColumnStretchFactor(2, 3)
124 125

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