目标是从串行端口读取数据,但由于这是一个 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()