aioserial.py icon indicating copy to clipboard operation
aioserial.py copied to clipboard

How to process incoming serial data

Open thisdavej opened this issue 3 years ago • 1 comments

aioserial is an excellent package for writing and reading data from serial ports. Thanks for creating it!

I have a serial device I am communicating with that can receive commands and respond to those commands. For example, I can write {get_temperature} to the serial port and the serial device will respond back with the current temperature. The aioserial package handles this task elegantly.

My serial device will also send back data to indicate that a button, for example, has been pushed on the device. This data is sent back asynchronously without being initiated by a command from the client computer. I think it's just my ignorance of asyncio, but I'm trying to figure out how to receive and process these button push events arriving from the serial device while still being able to send specific commands and receive responses from the serial device.

Here's the code I've written so far for getting temperature:

import asyncio
from aioserial import AioSerial

PORT = "COM4"
BAUDRATE = 115_200

serial = AioSerial(port=PORT, baudrate=BAUDRATE, timeout=5.0)

async def send_command_await_response(command):
    command_encoded = bytes(command, encoding='utf8')
    await serial.write_async(command_encoded)
    result = await serial.readline_async()
    return result.rstrip().decode()

async def main():
    command = "{get_temperature}"
    response = await send_command_await_response(command)
    print(f"{response=}")


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

Can you share some insights into how I could use aioserial to accomplish my objective?

thisdavej avatar Oct 09 '20 22:10 thisdavej

You are awaiting a readline. So long as your async button response is terminated as well, you could add a line after your result = await ... to handle the button push.

Personally, I would use the send_command_await_response and a dict of responses with handlers and maybe regex too depending on the responses (if it cannot be filtered with a simple starts_with).

Judging from the date, you probably solved this by now. I am really just probing to see how active this project is before using it in my own applications.

krister-ts avatar Feb 22 '21 19:02 krister-ts