1

目标是从串行端口读取数据,但由于这是一个 RFID 读取器,因此用户可能无法在另一个读取被缓冲之前及时移动。这会导致重复(或更多)条目。因此,我需要清除所有缓冲的条目并让它休眠几秒钟。

问题是实现睡眠功能和刷新输入缓冲区的“扭曲”方式是什么?

class ReaderProtocol(LineOnlyReceiver):

    def connectionMade(self):
        log.msg("Connected to serial port")

    def lineReceived(self, line):
        line = line.decode('utf-8')
        log.msg("%s" % str(line))
        time.sleep(2)  # pauses, but still prints whats in buffer

...
log.startLogging(sys.stdout)
serialPort = SerialPort(ReaderProtocol, "/dev/ttyAMA0", reactor, 2400)
reactor.run()

编辑

这是工作解决方案

class ReaderProtocol(LineOnlyReceiver):

    t, n = 0, 0

    def __init__(self):
        self.t = time.time()

    def connectionMade(self):
        log.msg("Connected to serial port")

    def lineReceived(self, line):
        self.n = time.time()
        if self.n > self.t + 2:
            line = line.decode('utf-8')
            log.msg("%s" % str(line))
            self.t = self.n

...
log.startLogging(sys.stdout)
serialPort = SerialPort(ReaderProtocol, "/dev/ttyAMA0", reactor, 2400)
reactor.run()
4

1 回答 1

2

您不能“刷新”输入缓冲区。刷新是您对写入(即输出缓冲区)执行的操作。您要做的是忽略在特定时间范围内到达的重复消息。

那么为什么不这样做呢?

不要尝试对“缓冲区”做任何奇怪的事情,只需根据收到最后一条消息的时间长短来改变处理消息的方式。

正如您已经注意到的那样,调用time.sleep()没有帮助,因为这只会导致您的整个程序停止一段时间:来自串行端口的消息仍然会备份。

于 2013-08-08T03:05:03.917 回答