using serial port in python3 asyncio

后端 未结 8 2033
长情又很酷
长情又很酷 2021-02-08 09:39

i\'m trying and, so far, failing to use python asyncio to access a serial port.

i\'d really appreciate any tips on using the new python async framework on a simple fd.

相关标签:
8条回答
  • 2021-02-08 10:19

    It's other way using FD

    import asyncio
    import serial
    
    s = serial.Serial('/dev/pts/13', 9600)
    
    
    def test_serial():
        '''
        read a line and print.
        '''
        text = ""
        msg = s.read().decode()
        while (msg != '\n'):
            text += msg
            msg = s.read().decode()
        print(text)
        loop.call_soon(s.write, "ok\n".encode())
    
    loop = asyncio.get_event_loop()
    loop.add_reader(s, test_serial)
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        loop.close()
    
    0 讨论(0)
  • 2021-02-08 10:19

    Consider using aioserial.

    Here's an example:

    import aioserial
    import asyncio
    
    
    async def read_and_print(aioserial_instance: aioserial.AioSerial):
        while True:
            print((await aioserial_instance.read_async()).decode(errors='ignore'), end='', flush=True)
    
    
    aioserial_com1: aioserial.AioSerial = aioserial.AioSerial(port='COM1')
    
    asyncio.run(read_and_print(aioserial_com1))
    

    To the moderator,

    The answer is just similar to this one but not duplicated.

    0 讨论(0)
提交回复
热议问题