python - 扭曲的 python : pausing a serial port read

标签 python twisted

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

问题是实现 sleep 函数和刷新输入缓冲区的“扭曲”方式是什么?

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()

最佳答案

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

那么为什么不这样做呢?

不要尝试对“缓冲区”做任何奇怪的事情,只需根据自收到上一条消息以来的时间长度来更改处理消息的方式即可。

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

关于python - 扭曲的 python : pausing a serial port read,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18116670/

相关文章:

python - 如何从FFT中提取特征?

python - 类型错误 : unbound method sprites()

python - 在python中查找大量列表的交集

Python Twisted 多客户端

python - 无法在 Miniconda 中激活虚拟环境

Python - 按日期透视日志数据

python - 如何使用装饰器使蜘蛛能够区分 scrapy 管道

Python、Asyncore 和 fork

通过 socks(代理)的 Python ssh 客户端

python - 将收到的数据(从 Twisted)写入 tkinter 文本框