using serial port in python3 asyncio

后端 未结 8 2039
长情又很酷
长情又很酷 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:13

    pySerial is getting direct asyncio support. It's in experimental state now but is working as expected for me.

    Example taken from the documentation:

    class Output(asyncio.Protocol):
        def connection_made(self, transport):
            self.transport = transport
            print('port opened', transport)
            transport.serial.rts = False
            transport.write(b'hello world\n')
    
        def data_received(self, data):
            print('data received', repr(data))
            self.transport.close()
    
        def connection_lost(self, exc):
            print('port closed')
            asyncio.get_event_loop().stop()
    
    loop = asyncio.get_event_loop()
    coro = serial.aio.create_serial_connection(loop, Output, '/dev/ttyUSB0', baudrate=115200)
    loop.run_until_complete(coro)
    loop.run_forever()
    loop.close()
    

提交回复
热议问题