pySerial-asyncio is an asynchronous I/O extension for the Python Serial Port package (pySerial). It provides support for working with serial ports through asyncio Transports, Protocols, and Streams. Compatible with Python 3.5 and later, it depends on pySerial. The current version is 0.6. The project appears to be in maintenance mode, with no new releases since 2021, and a fork `pyserial-asyncio-fast` addressing some critical issues.
pip install pyserial-asyncioVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to open an asynchronous serial connection using `open_serial_connection`, send data, and read a response. It uses environment variables for port and baudrate to allow easy testing with virtual or real serial ports. The `writer.drain()` call is essential to ensure buffered data is transmitted.
Consider migrating to `pyserial-asyncio-fast` (from the Home Assistant project), which is a drop-in replacement designed to address the event loop blocking issues and improve performance. It is a separate package and requires `pip install pyserial-asyncio-fast` and changing `import serial_asyncio` to `import serial_asyncio_fast as serial_asyncio`.
Always follow `writer.write(data)` with `await writer.drain()` to ensure reliable data transmission.
Be aware of potential performance implications on Windows. If performance is critical, thoroughly test your application on Windows or consider alternative approaches.
Ensure that `asyncio.Lock` and other event-loop-dependent objects are initialized within the context of the `asyncio` event loop where they will be used, ideally within an `async` function that is scheduled by `asyncio.run()` or `loop.run_until_complete()`.
pip install pyserial-asyncio
Verify the correct serial port name (e.g., check Device Manager on Windows or `ls /dev/tty*` on Linux), and ensure the device is physically connected.
On Linux, add your user to the `dialout` group (e.g., `sudo usermod -a -G dialout $USER` and then log out/in); on Windows, ensure no other program is holding the port open and check security permissions.
Add error handling around `await pyserial_asyncio.open_serial_connection(...)` to check if `transport` or `protocol` are `None` before attempting to use them, and handle potential `SerialException` during connection setup.
Wrap `await` calls that might be cancelled in `try...except asyncio.CancelledError` blocks, and ensure graceful task shutdown before closing the event loop.