问题
The goal is to read from a serial port, which works, but because this is an RFID reader the user may not move in time before another read is buffered. This results in duplicate (or more) entries. Therefore I need to clear any buffered entries and let it sleep for a couple of seconds.
The question is what is the 'twisted' way of implementing a sleep function and flushing the input buffer?
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()
EDIT:
Here is the working solution
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()
回答1:
You can't "flush" an input buffer. Flushing is something you do to a write, i.e. output buffer. What you are trying to do is ignore repeated messages that arrive within a certain time frame.
So why not just do that?
Don't attempt to do anything odd with "buffers", just change how you handle your message depending on how long it has been since you received the last message.
Calling time.sleep()
isn't helpful, as you've noticed, since that just causes your whole program to stall for a little while: messages from the serial port will still back up.
来源:https://stackoverflow.com/questions/18116670/twisted-python-pausing-a-serial-port-read