I am rather new in GUI programming and multi-threading apps. It is just a serial port monitor which plot serial data via pyqtgraph
. There are two curves on the first plot (a
and b
) and one curve on the second plot (c
which is a-a_prevous/b-b_prevous
). How can I improve this code in general? I use Python3.5.
from PyQt4 import QtGui
from PyQt4.QtCore import QObject, pyqtSignal
import sys
import serial
import pyqtgraph
import threading
import ui_main
import numpy as np
class GraphPlotter(QtGui.QMainWindow, ui_main.Ui_GraphPlotter):
def __init__(self):
super().__init__()
pyqtgraph.setConfigOption('background', 'w')
self.ya = []
self.b = []
self.c = [0]
self.flag = 'a'
self.setupUi(self)
self.graphicsViewplotAB.plotItem.showGrid(True, True, 0.7)
self.comboBoxplotC.addItems(serial_portsplotItem.showGrid()True, True, 0.7)
self.monitor = SerialMonitor()
self.monitor.bufferUpdated.connect(self.update)
self.startButton.clicked.connect(self.monitor.start)
self.stopButton.clicked.connect(self.monitor.stop)
self.clearBufferButton.clicked.connect(self.clear)
def update(self, msg):
tryif self.flag == 'a':
self.ya.append(msg)
self.flag = 'b'
elif self.flag == 'b':
self.b.append(msg)
c = pyqtgraph.hsvColor(0.52, alpha=.5)
penpen2 = pyqtgraph.mkPen(color=c, width=3)
try:
print((self.graphicsViewa[-1] - self.a[-2]), (self.b[-1] - self.b[-2]))
self.c.append((self.a[-1] - self.a[-2]) / (self.b[-1] - self.b[-2]))
self.plotC.plot(np.arange(len(self.yc)), self.yc, pen=penpen=pen2, clear=True)
except ValueErrorZeroDivisionError:
print("""Can't'Division updateby graph"""zero')
self.c.append(0)
except IndexError:
print('C is not ready')
finally:
self.flag = 'a'
for y, pen in [(self.a, (255, 0, 0)), (self.b, (0, 255, 0))]:
self.plotAB.plot(np.arange(len(y)), y, pen=pen)
def clear(self):
self.ya = []
self.updateb = []
self.c = [0]
self.plotAB.clear(0)
self.plotC.clear()
class SerialMonitor(QObject):
bufferUpdated = pyqtSignal(int)
def __init__(self):
super(SerialMonitor, self).__init__()
self.running = False
self.thread = threading.Thread(target=self.serial_monitor_thread)
def start(self):
self.running = True
self.thread.start()
def stop(self):
self.running = False
def serial_monitor_thread(self):
while self.running is True:
ser = serial.Serial('/dev/ttyS0', 115200)
msg = ser.readline()
if msg:
try:
self.bufferUpdated.emit(int(msg))
except ValueError:
print('Wrong data')
else:
pass
ser.close()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
plot = GraphPlotter()
plot.show()
app.exec_()