1

我有一个应用程序通过串行端口(使用pyserial)将数据发送到外部模块,该模块在接收时回复。我有一个线程来监视传入的数据,当有时,通过发射函数发送信号。然后,在插槽中,我根据简化的 hdlc 协议分析接收到的数据包。它工作正常,但唯一的问题是,如果帧包含零 (0x00),则插槽接收到的字符串将被截断。所以我假设发射函数将字符串传递到'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”,但我没有成功使用它(尽管我不确定我是否正确使用它)。

4

1 回答 1

0

嗯,好吧,看看QtSlot 装饰器,表单是:

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 的读取返回一个字节 python 类型

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))
    ....

看看这是否适合你。

于 2013-03-07T21:18:54.863 回答