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 = "*"
pyqt5 = "*"
pyyaml = "*"
protobuf = "*"
sacada-python = "*"
# Este arquivo define a interface a ser utilizada
device:
type: mock
location: "/dev/ttyUSB0"
type: sacada
location: "/dev/ttyACM0"
channels:
- id: 0
name: "Tensão"
- id: "A0"
name: "Canal A0"
color: "#FF0000"
unit: "mV"
- id: 1
name: "Corrente"
unit: "V"
- id: "TC"
name: "Temperatura"
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
class Arduino(object):
def __init__(self, logger, location, channels):
logger("[ARDUINO]", "Opening serial port...")
try:
self.ser = Serial(location, 115200)
self.ser = Serial(location, 115200, timeout=0.1)
except Exception as e:
logger("[ARDUINO]", "ERROR: Could not open serial port")
raise FileNotFoundError("Serial port not found") from e
logger("[ARDUINO]", "Starting board...")
self._reset() # Reset do arduino para reinicio da leitura
self.ser.readline() # Espera o Arduino inicializar
self.ser.write(bytes("press",'utf-8'))
self.ser.readline()
#self._reset() # Reset do arduino para reinicio da leitura
#self.ser.readline() # Espera o Arduino inicializar
#self.ser.write(bytes("press",'utf-8'))
#self.ser.readline()
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):
pass
def readAll(self):
print("Reading:")
self.ser.flushInput() # Limpeza do buffer de entrada
data = self.ser.readline().split(bytes(" ", "utf-8")) # Leitura de todos os valores em uma linha
return [int(x) for x in data]
val = []
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):
self.ser.setDTR(False)
......
......@@ -4,7 +4,11 @@ class Mock(object):
def __init__(self, logger, location, channels):
self.channels = len(channels)
logger("[MOCK]", "Generating fake data...")
self.reading = 10
def read(self, channel):
return random() * 20
self.reading += (random() - 0.5)
return self.reading
def readAll(self):
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
from interfaces.Mock import *
from interfaces.Arduino import *
from interfaces.InstrumentInterface import *
from .Mock import *
from .SACADA import *
from .Arduino import *
from .InstrumentInterface import *
INTERFACES = {
'mock': Mock,
'sacada': SACADA,
'arduino': Arduino,
'instrument-interface': InstrumentInterface,
}
This diff is collapsed.
......@@ -5,40 +5,42 @@ from interfaces import *
from config import Config
class Graph(QThread):
def __init__(self, graph, interval, logger, parent=None):
def __init__(self, ui, interval, logger, parent=None):
super(Graph, self).__init__(parent)
self.running = True
self.logger = logger
self.interval = interval/1000.0
self.dataX = []
self.dataY = []
self.graph = graph
self.ui = ui
self.graph = ui.mainGraph
self.plots = []
self.axis = []
self.config = Config().data
self.device = self.config["device"]
self._configurePlots()
device = self.config["device"]
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:
self.running = False
graph.setBackground((240, 240, 240))
self.graph.setBackground((240, 240, 240))
def run(self):
while self.running:
data = self.interface.readAll()
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.plots):
while True:
if self.running:
for i, channel in enumerate(self.device["channels"]):
self.dataX[i].append(self.dataX[i][-1] + self.interval)
self.dataY[i].append(data[i])
channel.setData(self.dataX[i], self.dataY[i])
self.dataY[i].append(self.interface.read(self.device["channels"][i]))
self.plots[i].setData(self.dataX[i], self.dataY[i])
sleep(self.interval)
def setInterval(self, interval):
self.interval = interval/1000.0
def restart(self):
self.running = True
def stop(self):
self.running = False
......@@ -47,24 +49,18 @@ class Graph(QThread):
self.graph.getPlotItem().addItem(marker)
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"]))
for channel in self.config["device"]["channels"]:
self.logger("[GRAPH]", "Added channel {}".format(channel["name"]))
self.dataX.append([0])
self.dataY.append([0])
plot = self.graph.plot(pen=mkPen(mkColor(channel["color"]), width=2), name=channel["name"])
for channel in self.device["channels"]:
plotItem = self.graph.addPlot()
plot = plotItem.plot(pen=mkPen(mkColor(channel["color"]), width=3), name=channel["id"])
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):
super(MainThread, self).__init__(parent)
self.ui = ui
self.data = []
self.graph = Graph(self.ui.mainGraph, 100, self._log)
self.graph = Graph(self.ui, 100, self._log)
self.upTimer = Timer()
self.downTimer = Timer(delay=10)
try:
......@@ -26,6 +26,9 @@ class MainThread(QThread):
#self.ui.stopTimerButton.pressed.connect(self._stopTimer)
#self.ui.startRegTimerButton.pressed.connect(self._startTimer)
#self.ui.stopRegTimerButton.pressed.connect(self._stopTimer)
self.ui.playPauseButton.aboutToShow.connect(self._playPause)
self.ui.finalizeButton.aboutToShow.connect(self._finalize)
self.graph.start()
while True:
......@@ -47,6 +50,15 @@ class MainThread(QThread):
def _log(self, tag, msg):
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):
if self.upTimer.active:
self.upTimer.update()
......
......@@ -231,7 +231,7 @@ class Ui_CalibracaoPressaoW(object):
self.samplingCBox.addItem("")
self.verticalLayout_3.addWidget(self.samplingCBox)
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.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
......@@ -410,4 +410,4 @@ class Ui_CalibracaoPressaoW(object):
self.selectPortaUSB.setText(_translate("CalibracaoPressaoW", "Selecionar porta USB"))
from pyqtgraph import PlotWidget
from pyqtgraph import GraphicsLayoutWidget
This diff is collapsed.
import sys
from PyQt5 import QtWidgets, QtCore
from ui.CalibracaoPressaoW import Ui_CalibracaoPressaoW
from .GenericoW import Ui_Generico
from threads.MainThread import MainThread
class Ui_MainWindow(object):
def __init__(self):
# 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.dialog = QtWidgets.QMainWindow()
self.ui = Ui_CalibracaoPressaoW()
self.ui = Ui_Generico()
self.ui.setupUi(self.dialog)
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