a serial port thread in pyQT5 - python-3.x

The following is my code. I am trying to create a serial port thread in my pyQt5 GUI. I checked many examples. This is very helpful one Background thread with QThread in PyQt
I think I made a successful connection but I am confused about the signature.
SelectedItem is the selected port. The GUI is still freezing because of while loop.
I need some help. Thanks!
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# vim:fileencoding=utf-8
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from TTP_Monitor_GUI import Ui_MainWindow
import serial
import serial.tools.list_ports
import binascii
import glob
class SerialPort(QObject):
def __init__(self, parent = None):
super(SerialPort, self).__init__(parent)
# Explicit signal
newParams = pyqtSignal(str)
#pyqtSlot(str)
def ReadSerialPort(self, port):
#initialization and open the port
with serial.Serial(port, 115200, timeout=1) as ser:
print ("Starting up")
while True:
readOut = 0 #chars waiting from laser range finder
#readOut = ser.readline().decode('ascii')
readOut = ser.read(268) # Reads # Bytes
r = binascii.hexlify(readOut).decode('ascii')
print(r)
self.newParams.emit(r)
#ser.flush() #flush the buffer
if ser.isOpen() == False:
print("Serial Port is Close")
class Main(QMainWindow):
# Explicit Signal
#ser = pyqtSignal(str)
def __init__(self, parent=None):
super(QMainWindow, self).__init__(parent)
#QMainWindow.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.btnRefresh.clicked.connect(self.Refresh)
self.ui.btnConnect.clicked.connect(self.Connect)
self.ListFunction(self.SerialPorts())
# Implicit Slot
def Connect(self):
Items = self.ui.listMain.selectedItems()
if len(Items) != 1:
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setWindowTitle("BE CAREFULL!")
msg.setText("SELECT ONLY 1 ITEM!...")
msg.exec_()
else:
SelectedItem = Items[0].text()
SelectedItem = SelectedItem.split(" ")[0]
if sys.platform.startswith('win') and SelectedItem[:3] != 'COM':
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setWindowTitle("BE CAREFULL!")
msg.setText("THERE IS A MISTAKE!...")
msg.exec_()
return
# Read Selected Serial Port
self.serialThread = QThread()
self.ser = SerialPort()
self.ser.moveToThread(self.serialThread)
self.ser.newParams.connect(self.serialThread.quit)
#self.serialThread.started.connect(self.ser.ReadSerialPort(SelectedItem))
self.serialThread.started.connect(lambda port=SelectedItem: self.ser.ReadSerialPort(port))
self.serialThread.start()
def Refresh(self):
""" Refresh List Widget """
self.ui.listMain.clear()
if self.ui.radioSerialPorts.isChecked() == True:
self.ListFunction(self.SerialPorts())
elif self.ui.radioTCP.isChecked() == True:
pass
def ListFunction(self, items):
""" Lists items into List Widget """
if type(items) == list and type(items[0]) == str:
#qApp.processEvents() # See Changes on GUI
self.ui.listMain.addItems(items)
else:
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setWindowTitle("BE CAREFULL!")
msg.setText("ITEMS ARE WRONG!...")
msg.exec_()
def SerialPorts(self):
""" Lists serial port names """
device = []
description = []
result = []
for port in serial.tools.list_ports.comports():
device.append(port.device)
description.append(port.description)
result.append(port.device + ' - ' + port.description)
return result
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
myapp = Main()
myapp.show()
sys.exit(app.exec_())

provide delay function time.sleep(1) at thread function ReadSerialPort(self, port) inside the while loop äfter the function self.newParams.emit(r).
pyqt UI does not gets sufficient time to execute. so provide delay. it will work.

Related

I wonder why pyqtSignal() is used. (pyqt, QThread, signal, slot)

This is the test code about QThread and Signal.
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import time
import sys
class Thread1(QThread):
set_signal = pyqtSignal(int) # (1) ##
def __init__(self, parent):
super().__init__(parent)
def run(self):
for i in range(10):
time.sleep(1)
self.set_signal.emit(i) # (3) ##
class MainWidget(QWidget):
def __init__(self):
super().__init__()
thread_start = QPushButton("시 작!")
thread_start.clicked.connect(self.increaseNumber)
vbox = QVBoxLayout()
vbox.addWidget(thread_start)
self.resize(200,200)
self.setLayout(vbox)
def increaseNumber(self):
x = Thread1(self)
x.set_signal.connect(self.print) # (2) ##
x.start()
def print(self, number):
print(number)
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = MainWidget()
widget.show()
sys.exit(app.exec_())
In the example of QThread I searched for, a pyqtSignal()(step 1) object was created, the desired slot function was connected(step 2) by connect, and then called by emit()(step 3).
I don't know the difference from calling the desired method immediately without connecting the connect().
So, the goal of codes is triggering a desired function every second. You are right about it.
But if you create multiple objects, you can connect it to different desired functions. Or connect multiple function to one signal.
x = Thread1(self)
x.set_signal.connect(self.print) # (2) ##
x.start()
y = Thread1(self)
y.set_signal.connect(self.print2)
time.sleep(0.5)
y.start()

PySide2 works not efficient

from PySide2.QtWidgets import QApplication, QMainWindow,QDialog,QLineEdit,QPushButton
from PySide2.QtCore import Qt
import sys
from ui618 import Ui_MainWindow
from numpad import Ui_Dialog
class MyWindow:
def __init__(self) -> None:
self.lastSelectedEditLine = None
# main ui
self.MainWindow = QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.MainWindow)
# numpad
self.QDialog = QDialog(self.MainWindow)
self.numpad = Ui_Dialog()
self.numpad.setupUi(self.QDialog)
self.QDialog.setWindowFlags(Qt.Popup)
# bind editline with numpad
self.lineEdits = self.MainWindow.findChildren(QLineEdit)
for item in self.lineEdits:
item.focusInEvent = lambda e,item=item:self.test(e,item)
def save_quit(self):
sys.exit()
def bindbtn(self):
self.ui.quit.clicked.connect(self.save_quit)
def numpad_btn(self,a,item):
if item.text() != '←':
self.lastSelectedEditLine.setText(self.lastSelectedEditLine.text()+item.text())
else:
self.lastSelectedEditLine.setText(self.lastSelectedEditLine.text()[:-1])
def bindNumpad(self):
numpad_btns = self.QDialog.findChildren(QPushButton)
for item in numpad_btns:
item.clicked.connect(lambda ignore='ignore',item=item : self.numpad_btn(ignore,item))
def test(self,e,item):
self.lastSelectedEditLine = item
this = item
x = self.MainWindow.x()
y = self.MainWindow.y() + self.ui.selectX.rect().bottom()
while this.parentWidget().objectName() != 'MainWindow':
x += this.x()
y += this.y()
this = this.parentWidget()
self.QDialog.move(x, y)
self.QDialog.show()
item.clearFocus()
def show(self):
self.MainWindow.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
myWindow = MyWindow()
myWindow.show()
myWindow.bindbtn()
myWindow.bindNumpad()
sys.exit(app.exec_())
The code works as expected, the numpad shows while focusing in a qlineedit. and can write and delete to target input line.
I am new to pyside2. Is there a better way to implement the numpad? I this way, the cursor is disable, I have to edit at the end of each editline.
It take several seconds while starting, Some one know how to improve it?

How to link an Analog Var with Qt Lcd Number

i am working on a small project
I have a potentiometer witch provide analog data via a serial com (like it's shown on the Com_Serial file )
so I want to read the data on the variable 'f' and show it on the QT lcd number
the interface File :
import sys
from PyQt5.QtWidgets import*
from PyQt5 import uic
from PyQt5 import*
from Com_Serial import f
class AppDemo(QWidget):
def __init__(self):
super().__init__()
uic.loadUi('app.ui', self)
self.Motor_Speed_Lcd.display(f)
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = AppDemo()
demo.show()
try:
sys.exit(app.exec_())
except SystemExit:
print('Closing Window…')
the Com_Serial File :
import serial
ser= serial.Serial(port='com4', baudrate=115200, timeout=1)
while 1:
value = '1'
ser.write(value.encode())
Data = ser.readline()
x = ((Data))
f= (x[1:5])
f = x.decode()
The solution is to execute the infinite loop in a thread and send the information through signals.
import threading
import time
from PyQt5.QtCore import pyqtSignal, QObject
class SerialManager(QObject):
value_changed = pyqtSignal(str)
def start(self):
threading.Thread(target=self.run, daemon=True).start()
def run(self):
ser= serial.Serial(port='com4', baudrate=115200, timeout=1)
while ser.is_open:
value = '1'
ser.write(value.encode())
data = ser.readline()
f = data[1:5].decode()
self.value_changed.emit(f)
time.sleep(.1)
class AppDemo(QWidget):
def __init__(self):
super().__init__()
uic.loadUi('app.ui', self)
self.serial_manager = SerialManager()
self.serial_manager.value_changed.connect(self.Motor_Speed_Lcd.display)
self.serial_manager.start()

PyQt5 add second function to thread but not work

Previously I have tried to use Flask for doing the followings simultaneously:
Display live video streaming
Display real-time data streaming
Control the robot car
As the above is just for demonstration, with the video streaming performance not good enough, I decided to change the whole application to PyQt5 for further development and production. Now I can create the GUI for displaying live video streaming well, while the real-time data streaming cannot be done well. The error is
QObject::startTimer: Timers can only be used with threads started with QThread
The following is the whole program. Please help to see what's wrong in the adding thread issue. Thanks!
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
import cv2
from vidgear.gears import CamGear
from random import random
data_list=[]
fps=60
options_cam={"CAP_PROP_FRAME_WIDTH":640,"CAP_PROP_FRAME_HEIGHT":480,"CAP_PROP_FPS":fps}
stream=CamGear(source=0,logging=False,**options_cam).start()
class MainWindow(QtWidgets.QWidget):
def __init__(self,*args):
super(MainWindow, self).__init__()
self.setWindowTitle('Vehicle control')
self.grid_layout=QtWidgets.QGridLayout()
self.video_label = QtWidgets.QLabel('Video streaming',self)
self.video_frame = QtWidgets.QLabel(self)
self.grid_layout.addWidget(self.video_label,0,0)
self.grid_layout.addWidget(self.video_frame,1,0)
self.data_label = QtWidgets.QLabel('Data streaming',self)
self.data_frame = QtWidgets.QListWidget(self)
self.grid_layout.addWidget(self.data_label,0,1)
self.grid_layout.addWidget(self.data_frame,1,1)
self.setLayout(self.grid_layout)
#self.thread=QtCore.QThread()
#self.thread.started.connect(self.nextFrameSlot)
#self.thread.start()
self.timer=QtCore.QTimer()
self.timer.timeout.connect(self.video_stream)
self.timer.start(0)
self.thread=QtCore.QThread()
self.thread.start()
self.timer2=QtCore.QTimer()
self.timer2.moveToThread(self.thread)
self.timer2.timeout.connect(self.data_stream)
self.timer2.start(0)
def video_stream(self):
frame = stream.read()
# My webcam yields frames in BGR format
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = QtGui.QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888)
pix = QtGui.QPixmap.fromImage(img)
self.video_frame.setPixmap(pix)
QtCore.QThread.sleep(0)
def data_stream(self):
print("data stream")
stream_data=round(random()*10,3)
data_list.insert(0,str(stream_data)+'\n')
if len(data_list)>10:
del data_list[-1]
for i in range(len(data_list)):
self.data_frame.addItem(data_list[i])
self.data_frame.show()
QtCore.QThread.sleep(1000)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Edit:
Thanks #musicamante's answer. I have updated the code as follows but still have the error "segmentation fault" for the video streaming, while if I run for data stream only, the updated list can be shown. So what's wrong with the setPixmap function? Thanks again!
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
import cv2
from vidgear.gears import CamGear
from random import random
fps=60
options_cam={"CAP_PROP_FRAME_WIDTH":480,"CAP_PROP_FRAME_HEIGHT":480,"CAP_PROP_FPS":fps}
stream=CamGear(source=0,logging=False,**options_cam).start()
class CamGrabber(QtCore.QThread):
frame = QtCore.pyqtSignal(QtGui.QImage)
def run(self):
while True:
new_frame = stream.read()
new_frame = cv2.cvtColor(new_frame, cv2.COLOR_BGR2RGB)
img = QtGui.QImage(new_frame, new_frame.shape[1], new_frame.shape[0], QtGui.QImage.Format_RGB888)
self.frame.emit(img)
class DataProvider(QtCore.QThread):
data = QtCore.pyqtSignal(object)
def run(self):
while True:
newData = round(random()*10,3)
self.data.emit(newData)
QtCore.QThread.sleep(1)
class MainWindow(QtWidgets.QWidget):
def __init__(self,*args):
super(MainWindow, self).__init__()
self.setWindowTitle('Vehicle control')
self.grid_layout=QtWidgets.QGridLayout()
self.video_label = QtWidgets.QLabel('Video streaming',self)
self.video_frame = QtWidgets.QLabel(self)
self.grid_layout.addWidget(self.video_label,0,0)
self.grid_layout.addWidget(self.video_frame,1,0)
self.data_label = QtWidgets.QLabel('Data streaming',self)
self.data_frame = QtWidgets.QListWidget(self)
self.grid_layout.addWidget(self.data_label,0,1)
self.grid_layout.addWidget(self.data_frame,1,1)
self.setLayout(self.grid_layout)
self.camObject = CamGrabber()
self.camObject.frame.connect(self.newFrame)
self.camObject.start()
self.dataProvider = DataProvider()
self.dataProvider.data.connect(self.newData)
self.dataProvider.start()
def newFrame(self, img):
self.video_frame.setPixmap(QtGui.QPixmap.fromImage(img))
def newData(self, data):
self.data_frame.insertItem(0,str(data))
if self.data_frame.count() > 10:
self.data_frame.takeItem(9)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())```
The QTimer error basically means that the a QTimer can only be started from the thread it exists.
Besides that, GUI element should always be directly accessed or modified from the main thread, not from another one.
In order to accomplish that, you'll need to create a separate "worker" thread, and communicate with the main one by taking advantage of the signal/slot mechanism.
class CamGrabber(QtCore.QThread):
frame = QtCore.pyqtSignal(QtGui.QImage)
def run(self):
while True:
frame = stream.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = QtGui.QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888)
self.frame.emit(img)
class DataProvider(QtCore.QThread):
data = QtCore.pyqtSignal(object)
def run(self):
while True:
newData = round(random()*10,3)
self.data.emit(newData)
# note that QThread.sleep unit is seconds, not milliseconds
QtCore.QThread.sleep(1)
class MainWindow(QtWidgets.QWidget):
def __init__(self,*args):
super(MainWindow, self).__init__()
self.setWindowTitle('Vehicle control')
self.grid_layout=QtWidgets.QGridLayout()
self.video_label = QtWidgets.QLabel('Video streaming',self)
self.video_frame = QtWidgets.QLabel(self)
self.grid_layout.addWidget(self.video_label,0,0)
self.grid_layout.addWidget(self.video_frame,1,0)
self.data_label = QtWidgets.QLabel('Data streaming',self)
self.data_frame = QtWidgets.QListWidget(self)
self.grid_layout.addWidget(self.data_label,0,1)
self.grid_layout.addWidget(self.data_frame,1,1)
self.setLayout(self.grid_layout)
self.camObject = CamGrabber()
self.camObject.frame.connect(self.newFrame)
self.camObject.start()
self.dataProvider = DataProvider()
self.dataProvider.data.connect(self.newData)
self.dataProvider.start()
def newFrame(self, img):
self.video_frame.setPixmap(QtGui.QPixmap.fromImage(img))
def newData(self, data):
self.data_frame.addItem(str(data))
if self.data_frame.count() > 10:
self.data_frame.takeItem(0)
If, for any reason, you want to control the data fetching from the main thread via a QTimer, you could use a Queue:
from queue import Queue
class DataProvider(QtCore.QObject):
data = QtCore.pyqtSignal(object)
def __init__(self):
super().__init__()
self.queue = Queue()
def run(self):
while True:
multi = self.queue.get()
# simulate a time consuming process
QtCore.QThread.sleep(5)
newData = round(multi * 10, 3)
self.data.emit(newData)
def pushData(self, data):
self.queue.put(data)
class MainWindow(QtWidgets.QWidget):
def __init__(self,*args):
# ...
self.requestTimer = QtCore.QTimer()
self.requestTimer.setInterval(1000)
self.requestTimer.timeout.connect(self.requestData)
# this will cause the timer to be executed only once after each time
# start() is called, so no new requests will overlap
self.requestTimer.setSingleShot(True)
self.requestTimer.start()
def requestData(self):
value = random()
print('requesting data with value {}'.format(value))
self.dataProvider.pushData(value)
print('waiting for result')
def newFrame(self, img):
self.video_frame.setPixmap(QtGui.QPixmap.fromImage(img))
def newData(self, data):
print('data received')
self.data_frame.addItem(str(data))
if self.data_frame.count() > 10:
self.data_frame.takeItem(0)
# restart the timer
self.requestTimer.start()

Howto change progress by worker thread

I'm new to PyQt4 so maybe it is a bagatelle. I try to show a progress in my GUI, which will be updated by an worker thread.The QProgressBar is with other memory's in a QTableWidget.
The worker thread starts in the init function of my GUI.
self.st = ServerThread()
self.st.start()
Here is the thread class
_exportedMethods = {
'changes': signal_when_changes,
}
class ServerThread(QtCore.QThread):
def __init__(self):
super(ServerThread,self).__init__()
st = self
#threading.Thread.__init__(self)
def run(self):
HOST = '' # local host
PORT = 50000
SERVER_ADDRESS = HOST, PORT
# set up server socket
s = socket.socket()
s.bind(SERVER_ADDRESS)
s.listen(1)
while True:
conn, addr = s.accept()
connFile = conn.makefile()
name = cPickle.load(connFile)
args = cPickle.load(connFile)
kwargs = cPickle.load(connFile)
res = _exportedMethods[name](*args,**kwargs)
cPickle.dump(res,connFile) ; connFile.flush()
conn.close()
If my Server changes values in the database he will call the following method which will captured with a remote prozedure call in the thread.
def signal_when_changes():
s = Subject()
s.advise()
The pattern is a simple observer, which updated my GUI. To update the table in my gui is the following method called.
def refresh(self,table):
clients = self.db.get_clients()
if(self.ui.mainTable.rowCount() != len(clients)):
self.search_add_client
allRows = table.rowCount()
for row in xrange(0,allRows):
for c in clients:
if table.item(row,0).text() == c.get_macaddr().text():
self.refresh_line(table,row,c)
This method checks wheter there were changes in a row if the needs a update the following method will do this.
def refresh_line(self,table,rowNumber,client):
table.item(rowNumber, 0).setText(client.get_macaddr().text())
table.item(rowNumber, 1).setText(client.get_product().text())
table.item(rowNumber, 2).setText(client.get_site().text())
table.item(rowNumber, 3).setText(client.get_hostname().text())
table.item(rowNumber, 4).setText(client.get_priv_data().text())
table.cellWidget(rowNumber, 5).setValue(client.get_progress_value())
table.item(rowNumber, 6).setText(client.get_stage().text())
The other memory's can be updated but not the progress, here the line in which i want to update the progress
self.ui.mainTable.setCellWidget(appendRowIndex,5,c.get_progress())
After this line the GUI crashes and i get the following message
QPixmap: It is not safe to use pixmaps outside the GUI thread
My conjecture is that i can't change QPixmaps outside the "Main/Gui" thread. I don't know how i can solve this problem, so I welcome all suggestions for resolution.
Thanks in advance.
Don't try to update the progress bar from within the thread: use a signal instead.
from PyQt4 import QtCore, QtGui
class Thread(QtCore.QThread):
def __init__(self,parent):
QtCore.QThread.__init__(self, parent)
def run (self):
for step in range(5):
self.sleep(1)
self.emit(QtCore.SIGNAL('taskUpdated'))
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.button = QtGui.QPushButton('Start', self)
self.progress = QtGui.QProgressBar(self)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.button)
layout.addWidget(self.progress)
self.connect(self.button, QtCore.SIGNAL('clicked()'),
self.handleButton)
self.thread = Thread(self)
self.connect(self.thread, QtCore.SIGNAL('taskUpdated'),
self.handleTaskUpdated)
def handleButton(self):
self.progress.setRange(0, 4)
self.progress.setValue(0)
self.thread.quit()
self.thread.start()
def handleTaskUpdated(self):
self.progress.setValue(self.progress.value() + 1)
def closeEvent(self, event):
self.thread.wait()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())

Resources