异步读取两个串口 [英] Read from two serial ports asynchronously

查看:94
本文介绍了异步读取两个串口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Linux 上的 python 中同时从两个(或更多)串行端口(/dev/ttyUSB0 等)读取数据.我想从每个端口读取完整的行(以有数据为准)并按收到的顺序处理结果(没有竞争条件).作为一个简单的例子,可以将行写入单个合并文件.

I'd like to read from two (or more) serial ports (/dev/ttyUSB0 etc) at the same time in python on Linux. I want to read complete lines from each port (whichever has data) and process the results in the order received (without race conditions). As a simple example could just write the lines to a single merged file.

我认为这样做的方法是基于 pyserial,但我不太清楚如何去做.Pyserial 使用 asyncio 和使用 线程.Asyncio 被标记为实验性的.如果处理在 asyncio.Protocol.data_received() 中完成,我认为不会有任何竞争条件.在线程的情况下,处理可能必须由互斥锁保护.

I assume the way to do this is based on pyserial, but I can't quite figure out how to do it. Pyserial has non-blocking reads using asyncio and using threads. Asyncio is marked as experimental. I assume there wouldn't be any race conditions if the processing is done in asyncio.Protocol.data_received(). In the case of threads, the processing would probably have to be protected by a mutex.

也许这也可以在 pyserial 中完成.这两个串行端口可以作为文件打开,然后在数据可用时使用 select() 读取.

Perhaps this can also be done not in pyserial. The two serial ports can be opened as files and then read from when data is available using select().

推荐答案

正如@AlexHall 在评论中所建议的,这里是一个解决方案,每个串口使用一个线程和一个队列来同步访问:

As suggested by @AlexHall in a comment, here is a solution that uses one thread for each serial port and a queue to synchronize access:

import serial
import Queue
import threading

queue = Queue.Queue(1000)

def serial_read(s):
    while True:
        line = s.readline()
        queue.put(line)

serial0 = serial.Serial('/dev/ttyUSB0')
serial1 = serial.Serial('/dev/ttyUSB1')

thread1 = threading.Thread(target=serial_read, args=(serial0,),).start()
thread2 = threading.Thread(target=serial_read, args=(serial1,),).start()

while True:
    line = queue.get(True, 1)
    print line

也许可以更优雅地编写此代码,但它确实有效.

It may be possible to write this more elegantly, but it works.

这篇关于异步读取两个串口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆