title: twisted python: pausing a serial port read
body: <p>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.</p>
  
  <p>The question is what is the 'twisted' way of implementing a sleep function and flushing the input buffer? </p>
  
  <pre><code>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()
  </code></pre>
  
  <p><strong>EDIT</strong>:</p>
  
  <p>Here is the working solution</p>
  
  <pre><code>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 &gt; 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()
  </code></pre>