使用PySide从插槽接收的字符串不完整

时间:2013-03-07 19:23:38

标签: python pyqt pyside pyserial

我有一个应用程序通过串口(使用pyserial)将数据发送到外部模块,外部模块在接收时回复。我有一个监视传入数据的线程,当有,通过emit函数发送信号。在插槽中,然后我根据简化的hdlc协议分析收到的数据包。它工作正常,但唯一的问题是,如果帧包含零(0x00),则插槽接收的字符串将被截断。所以我假设emit函数将字符串传递给'0'。这是信号和插槽的代码。

def ComPortThread(self):
    """Thread that handles the incoming traffic. Does the basic input
       transformation (newlines) and generates an event"""
    while self.alive.isSet():               #loop while alive event is true
        text = self.serial.read(1)          #read one, with timeout
        if text:                            #check if not timeout
            n = self.serial.inWaiting()     #look if there is more to read
            if n:
                text = text + self.serial.read(n) #get it
            self.incomingData.event.emit(text)

@QtCore.Slot(str)
def processIncoming(self, dataIn):
    """Handle input from the serial port."""
    for byte in dataIn:
        self.hexData.append(int(binascii.hexlify(byte),16))
    ....

例如,如果我在ComPortThread中打印变量“text”的内容,我可以得到:

  

7e000a0300030005

如果我为“dataIn”做同样的事情,我得到:

  

7E

我已经读过QByteArray会保持'0'但我没有成功使用它(虽然我不确定我是否正确使用它。)

1 个答案:

答案 0 :(得分:0)

嗯好的,查看QtSlot decorator表单是:

PyQt4.QtCore.pyqtSlot(types[, name][, result])
Decorate a Python method to create a Qt slot.

Parameters: 
types – the types that define the C++ signature of the slot. Each type may be a Python type object or a string that is the name of a C++ type.
name – the name of the slot that will be seen by C++. If omitted the name of the Python method being decorated will be used. This may only be given as a keyword argument.
result – the type of the result and may be a Python type object or a string that specifies a C++ type. This may only be given as a keyword argument.

看起来好像pyserial的读取会返回bytes python type

read(size=1)¶
Parameters: 
size – Number of bytes to read.
Returns:    
Bytes read from the port.
Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.

Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and str otherwise.

尽管如2.5和python 2.6所述。考虑到这一点,我会考虑确保你完成所提到的两个版本并尝试:

@QtCore.Slot(bytes)
def processIncoming(self, dataIn):
    """Handle input from the serial port."""
    for byte in dataIn:
        self.hexData.append(int(binascii.hexlify(byte),16))
    ....

看看它是否适合你。