Commit 48ed1371 authored by Pedro Henrique Kopper's avatar Pedro Henrique Kopper

Remodelar a aplicação para torná-la ainda mais genérica

parent e54d68f9
Pipeline #30 failed with stages
...@@ -12,3 +12,4 @@ pyserial = "*" ...@@ -12,3 +12,4 @@ pyserial = "*"
pyqt5 = "*" pyqt5 = "*"
pyyaml = "*" pyyaml = "*"
protobuf = "*" protobuf = "*"
sacada-python = "*"
# Este arquivo define a interface a ser utilizada # Este arquivo define a interface a ser utilizada
device: device:
type: mock type: sacada
location: "/dev/ttyUSB0" location: "/dev/ttyACM0"
channels: channels:
- id: 0 - id: "A0"
name: "Tensão" name: "Canal A0"
color: "#FF0000" color: "#FF0000"
unit: "mV" unit: "V"
- id: 1 - id: "TC"
name: "Corrente" name: "Temperatura"
color: "#0000FF" color: "#0000FF"
unit: "mA" unit: "ºC"
tc: 25
type: "R"
from time import sleep from datetime import datetime
from time import sleep, time
from serial import Serial from serial import Serial
class Arduino(object): class Arduino(object):
def __init__(self, logger, location, channels): def __init__(self, logger, location, channels):
logger("[ARDUINO]", "Opening serial port...") logger("[ARDUINO]", "Opening serial port...")
try: try:
self.ser = Serial(location, 115200) self.ser = Serial(location, 115200, timeout=0.1)
except Exception as e: except Exception as e:
logger("[ARDUINO]", "ERROR: Could not open serial port") logger("[ARDUINO]", "ERROR: Could not open serial port")
raise FileNotFoundError("Serial port not found") from e raise FileNotFoundError("Serial port not found") from e
logger("[ARDUINO]", "Starting board...") logger("[ARDUINO]", "Starting board...")
self._reset() # Reset do arduino para reinicio da leitura #self._reset() # Reset do arduino para reinicio da leitura
self.ser.readline() # Espera o Arduino inicializar #self.ser.readline() # Espera o Arduino inicializar
self.ser.write(bytes("press",'utf-8')) #self.ser.write(bytes("press",'utf-8'))
self.ser.readline() #self.ser.readline()
logger("[ARDUINO]", "Board started, good luck!") logger("[ARDUINO]", "Board started, good luck!")
today = datetime.now().strftime("%Y-%m-%d-%H:%M:%S")
self.logFile = open("/home/phckopper/logs/{}-calib.csv".format(today), "w")
self.logFile.write("Tempo (Unix), Calibrante (V), Pressão (bar)\n")
def read(self): def read(self):
pass pass
def readAll(self): def readAll(self):
print("Reading:")
self.ser.flushInput() # Limpeza do buffer de entrada self.ser.flushInput() # Limpeza do buffer de entrada
data = self.ser.readline().split(bytes(" ", "utf-8")) # Leitura de todos os valores em uma linha val = []
return [int(x) for x in data] self.ser.write(bytes(":MEAS:VOLT:DC? A0\r\n", "utf-8")) # Trigga leitura
reading = self.ser.readline().strip()
print(reading)
val.append(float(reading))
self.ser.write(bytes(":MEAS:VOLT:DC? A3\r\n", "utf-8")) # Trigga leitura
reading = self.ser.readline().strip()
print(reading)
val.append(float(reading) * (250.0/10.0))
self.logFile.write("{},{},{}\n".format(time(), val[0], val[1]))
self.logFile.flush()
#data = self.ser.readline().split(bytes(" ", "utf-8")) # Leitura de todos os valores em uma linha
#return [int(x) for x in data]
return val
def _reset(self): def _reset(self):
self.ser.setDTR(False) self.ser.setDTR(False)
......
...@@ -4,7 +4,11 @@ class Mock(object): ...@@ -4,7 +4,11 @@ class Mock(object):
def __init__(self, logger, location, channels): def __init__(self, logger, location, channels):
self.channels = len(channels) self.channels = len(channels)
logger("[MOCK]", "Generating fake data...") logger("[MOCK]", "Generating fake data...")
self.reading = 10
def read(self, channel): def read(self, channel):
return random() * 20 self.reading += (random() - 0.5)
return self.reading
def readAll(self): def readAll(self):
return [self.read(0) for i in range(self.channels)] return [self.read(0) for i in range(self.channels)]
from random import random
from sacada import SACADA as _SACADA
class SACADA(object):
def __init__(self, logger, location, channels):
self.channels = channels
self.s = _SACADA(location)
logger("[SACADA]", "Opening SACADA at {}".format(location))
logger("[SACADA]", str(self.s.identify()))
logger("[SACADA]", "Valor do zero: {}".format(self.s.zero()))
def read(self, channel):
if channel["id"] == "TC":
return self.s.readTemperature(channel["tc"], channel["type"])
return self.s.readVoltage(channel["id"])
def readAll(self):
return [self.read("TC")]
# Comente fora as interfaces não utilizadas para reduzir o tamanho do programa # Comente fora as interfaces não utilizadas para reduzir o tamanho do programa
from interfaces.Mock import * from .Mock import *
from interfaces.Arduino import * from .SACADA import *
from interfaces.InstrumentInterface import * from .Arduino import *
from .InstrumentInterface import *
INTERFACES = { INTERFACES = {
'mock': Mock, 'mock': Mock,
'sacada': SACADA,
'arduino': Arduino, 'arduino': Arduino,
'instrument-interface': InstrumentInterface, 'instrument-interface': InstrumentInterface,
} }
This diff is collapsed.
...@@ -5,40 +5,42 @@ from interfaces import * ...@@ -5,40 +5,42 @@ from interfaces import *
from config import Config from config import Config
class Graph(QThread): class Graph(QThread):
def __init__(self, graph, interval, logger, parent=None): def __init__(self, ui, interval, logger, parent=None):
super(Graph, self).__init__(parent) super(Graph, self).__init__(parent)
self.running = True self.running = True
self.logger = logger self.logger = logger
self.interval = interval/1000.0 self.interval = interval/1000.0
self.dataX = [] self.dataX = []
self.dataY = [] self.dataY = []
self.graph = graph self.ui = ui
self.graph = ui.mainGraph
self.plots = [] self.plots = []
self.axis = [] self.axis = []
self.config = Config().data self.config = Config().data
self.device = self.config["device"]
self._configurePlots() self._configurePlots()
device = self.config["device"]
try: try:
self.interface = INTERFACES[device["type"]](logger, device["location"], device["channels"]) self.interface = INTERFACES[self.device["type"]](logger, self.device["location"], self.device["channels"])
except FileNotFoundError: except FileNotFoundError:
self.running = False self.running = False
graph.setBackground((240, 240, 240)) self.graph.setBackground((240, 240, 240))
def run(self): def run(self):
while self.running: while True:
data = self.interface.readAll() if self.running:
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 for i, channel in enumerate(self.device["channels"]):
for i, channel in enumerate(self.plots):
self.dataX[i].append(self.dataX[i][-1] + self.interval) self.dataX[i].append(self.dataX[i][-1] + self.interval)
self.dataY[i].append(data[i]) self.dataY[i].append(self.interface.read(self.device["channels"][i]))
channel.setData(self.dataX[i], self.dataY[i]) self.plots[i].setData(self.dataX[i], self.dataY[i])
sleep(self.interval) sleep(self.interval)
def setInterval(self, interval): def setInterval(self, interval):
self.interval = interval/1000.0 self.interval = interval/1000.0
def restart(self):
self.running = True
def stop(self): def stop(self):
self.running = False self.running = False
...@@ -47,24 +49,18 @@ class Graph(QThread): ...@@ -47,24 +49,18 @@ class Graph(QThread):
self.graph.getPlotItem().addItem(marker) self.graph.getPlotItem().addItem(marker)
def _configurePlots(self): def _configurePlots(self):
first = True
pltItem = self.graph.getPlotItem()
pltItem.setClipToView(True)
pltItem.showGrid(True)
pltItem.addLegend()
pltItem.getViewBox().enableAutoRange()
pltItem.getViewBox().setAutoPan(x=True)
self.logger("[GRAPH]", "Found new device {}".format(self.config["device"]["type"])) 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"])) for channel in self.device["channels"]:
self.dataX.append([0]) plotItem = self.graph.addPlot()
self.dataY.append([0]) plot = plotItem.plot(pen=mkPen(mkColor(channel["color"]), width=3), name=channel["id"])
plot = self.graph.plot(pen=mkPen(mkColor(channel["color"]), width=2), name=channel["name"])
self.plots.append(plot) self.plots.append(plot)
if first:
pltItem.setLabel("left", text=channel["name"], units=channel["unit"])
first = False
else:
pltItem.setLabel("right", text=channel["name"], units=channel["unit"])
pltItem.setLabel("bottom", text="Tempo", units="s") plotItem.setClipToView(True)
plotItem.showGrid(True)
plotItem.getViewBox().enableAutoRange()
plotItem.getViewBox().setAutoPan(x=True)
self.dataX.append([0])
self.dataY.append([0])
plotItem.setLabel("left", text=channel["name"], units=channel["unit"])
self.logger("[GRAPH]", "Added channel {}".format(channel["name"]))
...@@ -12,7 +12,7 @@ class MainThread(QThread): ...@@ -12,7 +12,7 @@ class MainThread(QThread):
super(MainThread, self).__init__(parent) super(MainThread, self).__init__(parent)
self.ui = ui self.ui = ui
self.data = [] self.data = []
self.graph = Graph(self.ui.mainGraph, 100, self._log) self.graph = Graph(self.ui, 100, self._log)
self.upTimer = Timer() self.upTimer = Timer()
self.downTimer = Timer(delay=10) self.downTimer = Timer(delay=10)
try: try:
...@@ -26,6 +26,9 @@ class MainThread(QThread): ...@@ -26,6 +26,9 @@ class MainThread(QThread):
#self.ui.stopTimerButton.pressed.connect(self._stopTimer) #self.ui.stopTimerButton.pressed.connect(self._stopTimer)
#self.ui.startRegTimerButton.pressed.connect(self._startTimer) #self.ui.startRegTimerButton.pressed.connect(self._startTimer)
#self.ui.stopRegTimerButton.pressed.connect(self._stopTimer) #self.ui.stopRegTimerButton.pressed.connect(self._stopTimer)
self.ui.playPauseButton.aboutToShow.connect(self._playPause)
self.ui.finalizeButton.aboutToShow.connect(self._finalize)
self.graph.start() self.graph.start()
while True: while True:
...@@ -47,6 +50,15 @@ class MainThread(QThread): ...@@ -47,6 +50,15 @@ class MainThread(QThread):
def _log(self, tag, msg): def _log(self, tag, msg):
self.ui.consoleView.setText("{} {}\n{}".format(tag, msg, self.ui.consoleView.text())) self.ui.consoleView.setText("{} {}\n{}".format(tag, msg, self.ui.consoleView.text()))
def _playPause(self):
if self.graph.running:
self.graph.stop()
else:
self.graph.restart()
def _finalize(self):
pass
def _updateTimers(self): def _updateTimers(self):
if self.upTimer.active: if self.upTimer.active:
self.upTimer.update() self.upTimer.update()
......
...@@ -231,7 +231,7 @@ class Ui_CalibracaoPressaoW(object): ...@@ -231,7 +231,7 @@ class Ui_CalibracaoPressaoW(object):
self.samplingCBox.addItem("") self.samplingCBox.addItem("")
self.verticalLayout_3.addWidget(self.samplingCBox) self.verticalLayout_3.addWidget(self.samplingCBox)
self.gridLayout_2.addWidget(self.samplingBox, 1, 0, 1, 1) self.gridLayout_2.addWidget(self.samplingBox, 1, 0, 1, 1)
self.mainGraph = PlotWidget(self.widget) self.mainGraph = GraphicsLayoutWidget(self.widget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0) sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0) sizePolicy.setVerticalStretch(0)
...@@ -410,4 +410,4 @@ class Ui_CalibracaoPressaoW(object): ...@@ -410,4 +410,4 @@ class Ui_CalibracaoPressaoW(object):
self.selectPortaUSB.setText(_translate("CalibracaoPressaoW", "Selecionar porta USB")) self.selectPortaUSB.setText(_translate("CalibracaoPressaoW", "Selecionar porta USB"))
from pyqtgraph import PlotWidget from pyqtgraph import GraphicsLayoutWidget
This diff is collapsed.
import sys import sys
from PyQt5 import QtWidgets, QtCore from PyQt5 import QtWidgets, QtCore
from ui.CalibracaoPressaoW import Ui_CalibracaoPressaoW from .GenericoW import Ui_Generico
from threads.MainThread import MainThread from threads.MainThread import MainThread
class Ui_MainWindow(object): class Ui_MainWindow(object):
def __init__(self): def __init__(self):
# Faz o app funcionar em telas burguesas safadas com DPI alto # Faz o app funcionar em telas burguesas safadas com DPI alto
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) #enable highdpi scaling
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True) #use highdpi icons
self.app = QtWidgets.QApplication(sys.argv) self.app = QtWidgets.QApplication(sys.argv)
self.dialog = QtWidgets.QMainWindow() self.dialog = QtWidgets.QMainWindow()
self.ui = Ui_CalibracaoPressaoW() self.ui = Ui_Generico()
self.ui.setupUi(self.dialog) self.ui.setupUi(self.dialog)
print(self.ui) print(self.ui)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment