1

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()
Andrew Sledge
  • 10,163
  • 2
  • 29
  • 30
  • Your second-to-last line should read ``serialPort = SerialPort(ReaderProtocol(), "/dev/ttyAMA0", reactor, 2400)``, i.e. instantiating the class, else this won't work at all – stff00 Jan 30 '16 at 09:02

1 Answers1

2

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.

Glyph
  • 31,152
  • 11
  • 87
  • 129
  • Good answer, but one nit pick is that some people feel you can flush an input buffer, eg `tcflush(..., TCIFLUSH)` :) – Jean-Paul Calderone Aug 08 '13 at 10:24
  • It looks like that I will have to take this strategy. I was just wondering if there was a way to clear out the queued up messages that are already in and to prevent any more from coming in. Thanks! – Andrew Sledge Aug 08 '13 at 12:07
  • Though, there still seems to be some race condition because if I change cards it's still picking up the previous. Can't tell if it's related to this. – Andrew Sledge Aug 08 '13 at 12:15
  • the `tcflush` thing was new to me. What the heck is the point of that API? Can't you just `read` and not pay attention to the result? :) – Glyph Aug 09 '13 at 21:44