PyQt5串口threadevent

时间:2017-08-29 16:55:35

标签: python multithreading pyqt pyqt5

每次收到串口数据包时,我都试图发送事件emit()消息。 串口正在通过线程系统工作并收集数据。 我的问题是我无法触发事件从串行线程调用我的函数。

以下是代码:

from PyQt5.QtCore import *

import serial as pyserial
import threading

class Com_port(QThread):
    rcv_data_event = pyqtSignal()

    def __init__(self, *args, **kwds):
        super(Com_port, self).__init__()
        self.serial = pyserial.Serial()
        self.serial.port=kwds.pop('port')
        self.serial.baudrate=kwds.pop('baudrate')
        self.serial.bytesize=pyserial.EIGHTBITS
        self.serial.parity=pyserial.PARITY_NONE
        self.serial.stopbits=pyserial.STOPBITS_ONE
        self.serial.timeout=None
        self.serial.xonxoff=0
        self.serial.rtscts=0
        self.serial.interCharTimeout=None
        self.thread = None
        self.alive = threading.Event()
        self.buffer = kwds.pop('buffer')
        self.rcv_data_event.connect(self.rcvData_signal)
        self.rcv_data_event.emit()  # This is working
        pass

        try:
            self.serial.open()
        except pyserial.SerialException:
            print ('Failed to connect com port !')

    def StartThread(self):
        """Start the receiver thread"""
        self.thread = threading.Thread(target=self.ComPortThread)
        self.thread.setDaemon(1)
        self.alive.set()
        self.thread.start()

    def StopThread(self):
        """Stop the receiver thread, wait util it's finished."""
        if self.thread is not None:
            self.alive.clear()          # clear alive event for thread
            self.thread.join()          # wait until thread has finished
            self.thread = None

    def CloseSerialPort(self):
        self.serial.flushInput()
        self.serial.flushOutput()
        self.serial.close()

    def ComPortThread(self):
        while self.alive.isSet():               #loop while alive event is true
            try:
                if self.serial.inWaiting() and self.serial.is_open:
                    self.bajt = self.serial.read(self.buffer)
                    print(self.bajt, sep='', end='\n')
                    self.rcv_data_event.emit()  #This is not working :(
                    pass
            except:
                # PRIKAZATI GRESKU !!!!
                print ('Failed to connect com port !')
                self.StopThread()
                ok = False

    def rcvData_signal(self):
        print("Start serial port data event")
        print("Not reveiving any data  from serial thread :( :( :( WHY")

rcvData_Signal仅从 def __init __ 函数调用一次,但从ComPortThread()调用永远不会。

我预览了很多问题,但无法找到 pyQT5 的解决方案。

:(

0 个答案:

没有答案