Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - Read from two serial ports asynchronously

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.

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Consider using aioserial.

Here's an example:

import asyncio
import concurrent.futures
import queue

import aioserial


async def readline_and_put_to_queue(
        aioserial_instance: aioserial.AioSerial,
        q: queue.Queue):
    while True:
        q.put(await aioserial_instance.readline_async())


async def process_queue(q: queue.Queue):
    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
        while True:
            line: bytes = await asyncio.get_running_loop().run_in_executor(
                    executor, q.get)
            print(line.decode(errors='ignore'), end='', flush=True)
            q.task_done()


q: queue.Queue = queue.Queue()
aioserial_ttyUSB0: aioserial.AioSerial = 
        aioserial.AioSerial(port='/dev/ttyUSB0')
aioserial_ttyUSB1: aioserial.AioSerial = 
        aioserial.AioSerial(port='/dev/ttyUSB1', baudrate=115200)

asyncio.run(asyncio.wait([
    readline_and_put_to_queue(aioserial_ttyUSB0, q),
    readline_and_put_to_queue(aioserial_ttyUSB1, q),
    process_queue(q),
]))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...