Commit 7ee0c7fe authored by Pedro Henrique Kopper's avatar Pedro Henrique Kopper
Browse files

Voltar a trabalhar no SADAPMAP/Interface

parent 48ed1371
*.pyc *.pyc
Pipfile.lock Pipfile.lock
logs/
# Este arquivo define a interface a ser utilizada # Este arquivo define a interface a ser utilizada
device: device:
type: sacada type: mock
location: "/dev/ttyACM0" location: "/dev/ttyACM0"
channels: channels:
- id: "A0" - id: "PWR"
name: "Canal A0" name: "Potência"
color: "#FF0000" color: "#FF0000"
unit: "V" unit: "W"
- id: "TC" - id: "TC"
name: "Temperatura" name: "Temperatura"
color: "#0000FF" color: "#0000FF"
unit: "ºC" unit: "ºC"
tc: 25 tc: 18
type: "R" type: "R"
...@@ -11,7 +11,13 @@ class SACADA(object): ...@@ -11,7 +11,13 @@ class SACADA(object):
def read(self, channel): def read(self, channel):
if channel["id"] == "TC": if channel["id"] == "TC":
return self.s.readTemperature(channel["tc"], channel["type"]) try:
return self.s.readTemperature(channel["tc"], channel["type"])
except:
# Should handle value errors better
return 0
if channel["id"] == "PWR":
return self.s.readVoltage("A3") * self.s.readVoltage("A4")
return self.s.readVoltage(channel["id"]) return self.s.readVoltage(channel["id"])
def readAll(self): def readAll(self):
......
...@@ -258,7 +258,7 @@ font: 10pt &quot;Liberation Mono&quot;;</string> ...@@ -258,7 +258,7 @@ font: 10pt &quot;Liberation Mono&quot;;</string>
<string notr="true"/> <string notr="true"/>
</property> </property>
<property name="title"> <property name="title">
<string>Tensão no Calibrante</string> <string>Temperatura</string>
</property> </property>
<property name="alignment"> <property name="alignment">
<set>Qt::AlignBottom|Qt::AlignRight|Qt::AlignTrailing</set> <set>Qt::AlignBottom|Qt::AlignRight|Qt::AlignTrailing</set>
...@@ -298,7 +298,7 @@ font: 10pt &quot;Liberation Mono&quot;;</string> ...@@ -298,7 +298,7 @@ font: 10pt &quot;Liberation Mono&quot;;</string>
<string notr="true"/> <string notr="true"/>
</property> </property>
<property name="title"> <property name="title">
<string>Força</string> <string>Potência</string>
</property> </property>
<layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0"> <layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0">
<item alignment="Qt::AlignRight"> <item alignment="Qt::AlignRight">
......
#!/usr/bin/env python
from PyQt5 import QtCore, QtWidgets
import pyqtgraph as pg
import numpy as np
class MyWidget(pg.GraphicsWindow):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.mainLayout = QtWidgets.QVBoxLayout()
self.setLayout(self.mainLayout)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(100) # in milliseconds
self.timer.start()
self.timer.timeout.connect(self.onNewData)
self.plotItem = self.addPlot(title="Lidar points")
self.plotDataItem = self.plotItem.plot([], pen=None,
symbolBrush=(255,0,0), symbolSize=5, symbolPen=None)
def setData(self, x, y):
self.plotDataItem.setData(x, y)
def onNewData(self):
numPoints = 1000
x = np.random.normal(size=numPoints)
y = np.random.normal(size=numPoints)
self.setData(x, y)
def main():
app = QtWidgets.QApplication([])
pg.setConfigOptions(antialias=False) # True seems to work as well
win = MyWidget()
win.show()
win.resize(800,600)
win.raise_()
app.exec_()
if __name__ == "__main__":
main()
from time import sleep from PyQt5.QtCore import QTimer
from PyQt5.QtCore import QThread
from pyqtgraph import AxisItem, InfiniteLine, mkColor, mkPen, setConfigOption from pyqtgraph import AxisItem, InfiniteLine, mkColor, mkPen, setConfigOption
from interfaces import * from interfaces import *
from config import Config from config import Config
import pyqtgraph as pg
class Graph(QThread): class Graph():
def __init__(self, ui, interval, logger, parent=None): def __init__(self, ui, interval, logger, parent=None):
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.ui = ui self.ui = ui
...@@ -19,6 +18,10 @@ class Graph(QThread): ...@@ -19,6 +18,10 @@ class Graph(QThread):
self.config = Config().data self.config = Config().data
self.device = self.config["device"] self.device = self.config["device"]
self._configurePlots() self._configurePlots()
self.lastupdated = 0
pg.setConfigOptions(useOpenGL=True)
try: try:
self.interface = INTERFACES[self.device["type"]](logger, self.device["location"], self.device["channels"]) self.interface = INTERFACES[self.device["type"]](logger, self.device["location"], self.device["channels"])
except FileNotFoundError: except FileNotFoundError:
...@@ -26,17 +29,19 @@ class Graph(QThread): ...@@ -26,17 +29,19 @@ class Graph(QThread):
self.graph.setBackground((240, 240, 240)) self.graph.setBackground((240, 240, 240))
def run(self): def updateGraphs(self):
while True: for i, channel in enumerate(self.device["channels"]):
if self.running: self.dataX[i].append(self.dataX[i][-1] + self.interval/1000.0)
for i, channel in enumerate(self.device["channels"]): self.dataY[i].append(self.interface.read(self.device["channels"][i]))
self.dataX[i].append(self.dataX[i][-1] + self.interval) self.plots[i].getViewBox().setRange(xRange=(self.dataX[0][-1] - 10, self.dataX[0][-1]))
self.dataY[i].append(self.interface.read(self.device["channels"][i])) self.plots[i].setData(self.dataX[i], self.dataY[i], clear=True)
self.plots[i].setData(self.dataX[i], self.dataY[i])
sleep(self.interval) self.ui.forceLabel.setText("{:.4f} U".format(self.dataY[0][-1]))
self.ui.calibratorLabel.setText("{:.2f} ºC".format(self.dataY[1][-1]))
pg.QtGui.QApplication.processEvents()
def setInterval(self, interval): def setInterval(self, interval):
self.interval = interval/1000.0 self.interval = interval
def restart(self): def restart(self):
self.running = True self.running = True
...@@ -53,13 +58,13 @@ class Graph(QThread): ...@@ -53,13 +58,13 @@ class Graph(QThread):
for channel in self.device["channels"]: for channel in self.device["channels"]:
plotItem = self.graph.addPlot() plotItem = self.graph.addPlot()
plot = plotItem.plot(pen=mkPen(mkColor(channel["color"]), width=3), name=channel["id"]) plot = plotItem.plot(pen=mkPen(mkColor(channel["color"]), width=2), name=channel["id"])
self.plots.append(plot) self.plots.append(plot)
plotItem.setClipToView(True) plotItem.setClipToView(True)
plotItem.showGrid(True) plotItem.showGrid(True)
plotItem.getViewBox().enableAutoRange() plotItem.getViewBox().setMouseEnabled(False, False)
plotItem.getViewBox().setAutoPan(x=True) plotItem.getViewBox().enableAutoRange(plotItem.getViewBox().YAxis)
#plotItem.getViewBox().setAutoPan(x=True)
self.dataX.append([0]) self.dataX.append([0])
self.dataY.append([0]) self.dataY.append([0])
plotItem.setLabel("left", text=channel["name"], units=channel["unit"]) plotItem.setLabel("left", text=channel["name"], units=channel["unit"])
......
...@@ -2,38 +2,42 @@ from datetime import datetime ...@@ -2,38 +2,42 @@ from datetime import datetime
from time import sleep from time import sleep
from sys import exit from sys import exit
from PyQt5.QtCore import QThread, QTimer from PyQt5.QtCore import QThread, QTimer
from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QMessageBox, QApplication
from threads.Graph import Graph from threads.Graph import Graph
from config import Config from config import Config
from util.Timer import Timer from util.Timer import Timer
class MainThread(QThread): class MainThread():
def __init__(self, ui, parent=None): def __init__(self, ui, parent=None):
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, 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:
self.config = Config() self.config = Config()
except FileNotFoundError: except FileNotFoundError:
self._fatal("Arquivo de configuração não encontrado!") self._fatal("Arquivo de configuração não encontrado!")
self.graphTimer = QTimer(ui.mainGraph)
self.graphTimer.timeout.connect(self.graph.updateGraphs)
self.graphTimer.start(self.graph.interval)
self.ui.samplingCBox.currentIndexChanged.connect(self._updateSamplingRate)
def run(self): def run(self):
self.ui.samplingCBox.currentIndexChanged.connect(self._updateSamplingRate) pass
#self.ui.startTimerButton.pressed.connect(self._startTimer) #self.ui.startTimerButton.pressed.connect(self._startTimer)
#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.playPauseButton.aboutToShow.connect(self._playPause)
self.ui.finalizeButton.aboutToShow.connect(self._finalize) #self.ui.finalizeButton.aboutToShow.connect(self._finalize)
#while True:
self.graph.start() #self._updateTimers()
#if self.graph.running:
while True: # self.graph.updateGraphs()
self._updateTimers() #QApplication.processEvents()
sleep(1/30.0) # Updates at 30FPS #sleep(self.graph.interval/1000.0) # Updates at 30FPS
def _updateSamplingRate(self): def _updateSamplingRate(self):
MAP = [100, 200, 500, 1000, 1500, 2000, 2500, 5000, 10000] MAP = [100, 200, 500, 1000, 1500, 2000, 2500, 5000, 10000]
......
...@@ -2,14 +2,12 @@ ...@@ -2,14 +2,12 @@
# Form implementation generated from reading ui file 'resources/UI/Generico.ui' # Form implementation generated from reading ui file 'resources/UI/Generico.ui'
# #
# Created by: PyQt5 UI code generator 5.13.1 # Created by: PyQt5 UI code generator 5.11.2
# #
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Generico(object): class Ui_Generico(object):
def setupUi(self, Generico): def setupUi(self, Generico):
Generico.setObjectName("Generico") Generico.setObjectName("Generico")
...@@ -271,9 +269,9 @@ class Ui_Generico(object): ...@@ -271,9 +269,9 @@ class Ui_Generico(object):
self.samplingCBox.setItemText(7, _translate("Generico", "5 seg")) self.samplingCBox.setItemText(7, _translate("Generico", "5 seg"))
self.samplingCBox.setItemText(8, _translate("Generico", "10 seg")) self.samplingCBox.setItemText(8, _translate("Generico", "10 seg"))
self.absValGBox.setTitle(_translate("Generico", "Valores Absolutos")) self.absValGBox.setTitle(_translate("Generico", "Valores Absolutos"))
self.calibratorGBox.setTitle(_translate("Generico", "Tensão no Calibrante")) self.calibratorGBox.setTitle(_translate("Generico", "Temperatura"))
self.calibratorLabel.setText(_translate("Generico", "0 mV")) self.calibratorLabel.setText(_translate("Generico", "0 mV"))
self.forceGBox.setTitle(_translate("Generico", "Força")) self.forceGBox.setTitle(_translate("Generico", "Potência"))
self.forceLabel.setText(_translate("Generico", "0 Tonf")) self.forceLabel.setText(_translate("Generico", "0 Tonf"))
self.fileMenu.setTitle(_translate("Generico", "Arquivo")) self.fileMenu.setTitle(_translate("Generico", "Arquivo"))
self.stageMenu.setTitle(_translate("Generico", "Etapa")) self.stageMenu.setTitle(_translate("Generico", "Etapa"))
...@@ -289,4 +287,5 @@ class Ui_Generico(object): ...@@ -289,4 +287,5 @@ class Ui_Generico(object):
self.saveButton.setText(_translate("Generico", "Salvar")) self.saveButton.setText(_translate("Generico", "Salvar"))
self.saveAsButton.setText(_translate("Generico", "Salvar Como")) self.saveAsButton.setText(_translate("Generico", "Salvar Como"))
self.selectPortaUSB.setText(_translate("Generico", "Selecionar porta USB")) self.selectPortaUSB.setText(_translate("Generico", "Selecionar porta USB"))
from pyqtgraph import GraphicsLayoutWidget from pyqtgraph import GraphicsLayoutWidget
...@@ -18,7 +18,7 @@ class Ui_MainWindow(object): ...@@ -18,7 +18,7 @@ class Ui_MainWindow(object):
print(self.ui) print(self.ui)
main_thread = MainThread(self.ui) main_thread = MainThread(self.ui)
main_thread.finished.connect(self.app.exit) #main_thread.finished.connect(self.app.exit)
main_thread.start() #main_thread.start()
self.dialog.showMaximized() self.dialog.showMaximized()
...@@ -10,10 +10,10 @@ class Timer(object): ...@@ -10,10 +10,10 @@ class Timer(object):
self.active = False self.active = False
self.direction = self.DOWN if delay else self.UP self.direction = self.DOWN if delay else self.UP
self.lastUpdate = 0 self.lastUpdate = 0
def update(self): def update(self):
if not self.lastUpdate: if not self.lastUpdate:
self.stop() self.stop()
now = time() now = time()
delta = now - self.lastUpdate delta = now - self.lastUpdate
self.lastUpdate = now self.lastUpdate = now
...@@ -42,4 +42,4 @@ class Timer(object): ...@@ -42,4 +42,4 @@ class Timer(object):
self.lastUpdate = time() self.lastUpdate = time()
def stop(self): def stop(self):
self.active = False self.active = False
\ No newline at end of file
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