using serial port in python3 asyncio

time4tea picture time4tea · Feb 9, 2014 · Viewed 13.7k times · Source

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.

Cheers!

James

Answer

RodixPy picture RodixPy · Jan 13, 2015

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