pySerial读取丢失的位

时间:2015-01-21 06:44:12

标签: python pyserial

我有以下串行端口的写入和读取代码。但是当我经常运行它们,说100次写入和读取时,总是有时读取错误的字节数,它应该得到9个字节,但有时它只有8个字节。

例如,通常当我发送[1,88,0,27,192]时,它应该返回9个字节,如[1,88,4,0,0,3,35,182,49]。但是在写入和读取的次数为89次时总是错误的,它返回如[1,88,4,0,1,209,107,180],少1个字节。在我检测到这是1个字节丢失后,我再次写入和读取相同的发送消息,如[1,88,0,27,192],此后的读取数据总是丢失一个字节。然而,在其他一些陈述之后,每次都不会出现1字节缺失问题。

我还有另外一个问题,设备有时无法接收我的写入特定命令,具体而言,在应该发送命令后没有返回,并且因为我的串行设备没有&#39 ; t接收所以它不会执行。所以我必须关闭()并打开()这样的端口并再次发送命令几次,使得返回也就是执行命令,这样的重试需要花费很多时间,这让我很难等待。

我的配置,FT232RL USB转串口芯片,9600波特率,8字节大小,超时为1秒,停止位1,奇偶校验无。

def SendData(self, portID, cmd):
        """
        cmd is the pre-defined variables , they are the lists in front of this file.
        After send data, there is a delay.
        """
        global command_count
        if (self.isOpen(portID)):
            command_count += 1
            lock = threading.RLock()
            with lock:
                try:
                    COMlogger.debug("SendData command count %d" % (command_count))
                    writereturn = self.serdict[portID].write(list2bytestr(cmd))
                    # wait for output buffer to drain, reference from the miniterm example
                    self.serdict[portID].flush()
                    self.lastcmd = cmd
                    COMlogger.debug("SendData sent out %s" % (str(cmd)))
                    COMlogger.debug("SendData write returns %d bytes." % writereturn)
                except:
                    COMlogger.error("Sending data to %s with ID %d failed." % (self.portaddresslist[portID], portID))
                    return False
                finally:
                    time.sleep(0.2)

            return True
        return False

    def GetData(self, portID):
        """
        It take times to let the device respond, so remember to wait a bit after sending data.
        Before get data, there is a deley
        """
        time.sleep(0.2)
        global command_count
        if (self.isOpen(portID)):
            lock = threading.RLock()
            with lock:
                try:
                    # possibly time out here
                    #receivedmsg = self.serdict[portID].readline() # stop using readline since it wait for the \n or time out.
                    text = self.serdict[portID].read(1)
                    if text:
                        time.sleep(0.2)
                        n = self.serdict[portID].inWaiting()
                        if n:
                            text += self.serdict[portID].read(n)
                    receivedmsg = text
                    COMlogger.debug("GetData from ID %d returned %s" %(portID, str(bytestr2list(receivedmsg))))
                    return receivedmsg
                except:
                    COMlogger.error( "Receiving data from %s with ID %d failed." % (self.portaddresslist[portID], portID))
                    return None
        else:
            COMlogger.error("Error in GetData, port %d is not open." % portID)
        return None

0 个答案:

没有答案