Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using serial port in python3 asyncio

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

like image 698
time4tea Avatar asked Feb 09 '14 22:02

time4tea


2 Answers

Here is a working example using pyserial-asyncio:

from asyncio import get_event_loop
from serial_asyncio import open_serial_connection

async def run():
    reader, writer = await open_serial_connection(url='/dev/ttyS0', baudrate=115200)
    while True:
        line = await reader.readline()
        print(str(line, 'utf-8'))

loop = get_event_loop()
loop.run_until_complete(run())
like image 197
pdenes Avatar answered Oct 21 '22 23:10

pdenes


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()
like image 43
RodixPy Avatar answered Oct 22 '22 00:10

RodixPy