Registry / http-networking / pyserial-asyncio

pyserial-asyncio

JSON →
library0.6pypypi✓ verified 24d ago

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-asyncio
INSTALL
IMPORT
SIG · PYSERIAL-ASYNCIO
P
pyserial-asyncio
http-networkingpythonv0.6
Install
1.7s avg
Import
201ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.6 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.212s · 18.5MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.7s · import 0.190s · 19MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

serial_asyncio
import serial_asyncio
open_serial_connection
from serial_asyncio import open_serial_connection
Preferred for simpler stream-based I/O over `create_serial_connection`.
create_serial_connection
from serial_asyncio import create_serial_connection
Used when implementing custom `asyncio.Protocol` subclasses.

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.

import asyncio import os import serial_asyncio async def main(): # For testing, use a virtual serial port like 'loop://'. # On Linux, you can create virtual ports using 'socat -d -d pty,raw,echo=0 pty,raw,echo=0'. # Replace 'loop://' with your actual port (e.g., '/dev/ttyUSB0' or 'COM1'). port = os.environ.get('SERIAL_PORT', 'loop://') baudrate = int(os.environ.get('SERIAL_BAUDRATE', '115200')) print(f"Attempting to open serial port {port} at {baudrate} baud...") try: # open_serial_connection returns (StreamReader, StreamWriter) reader, writer = await serial_asyncio.open_serial_connection(url=port, baudrate=baudrate) print("Serial port opened successfully.") except Exception as e: print(f"Failed to open serial port: {e}") return try: message = b"Hello pySerial-asyncio!\n" print(f"Sending: {message.decode().strip()}") writer.write(message) await writer.drain() # Crucial to ensure data is sent print("Waiting for response...") response = await reader.readline() # Read until newline print(f"Received: {response.decode().strip()}") except Exception as e: print(f"Error during serial communication: {e}") finally: print("Closing serial port...") writer.close() await writer.wait_closed() print("Serial port closed.") if __name__ == '__main__': asyncio.run(main())
Debug
Known issues
breakingThe `pyserial-asyncio` library is known to block the asyncio event loop due to blocking sleep calls, especially on Windows, which can lead to performance issues and unresponsiveness in asynchronous applications. This library is also not actively maintained, with the last release being in 2021.
fix
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`.
affects: <=0.6
gotchaWhen using `StreamWriter` objects obtained from `open_serial_connection`, it is critical to call `await writer.drain()` after `writer.write()` to ensure that all buffered data is flushed and sent over the serial port. Forgetting to call `drain()` can result in data not being transmitted, especially in tight loops or when the buffer fills up.
fix
Always follow `writer.write(data)` with `await writer.drain()` to ensure reliable data transmission.
affects: All
gotchaOn Windows, `pyserial-asyncio` uses a polling-based implementation for serial I/O, which may be less performant and slower compared to the native event-driven implementations on POSIX systems (Linux, macOS, BSD).
fix
Be aware of potential performance implications on Windows. If performance is critical, thoroughly test your application on Windows or consider alternative approaches.
affects: All
gotchaWhen working with `asyncio`, creating `asyncio.Lock` objects (or similar synchronization primitives) outside of an actively running event loop can lead to subtle bugs and exceptions when the lock is later acquired or released in a different event loop (e.g., one started by `asyncio.run()`).
fix
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()`.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pyserial_asyncio'
The `pyserial-asyncio` library has not been installed or is not accessible in the current Python environment.
fix
pip install pyserial-asyncio
FileNotFoundError: [Errno 2] No such file or directory: '/dev/ttyUSB0'
The specified serial port name does not exist on the system, is misspelled, or the device is not connected.
fix
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.
SerialException: Could not open port /dev/ttyUSB0: [Errno 13] Permission denied: '/dev/ttyUSB0'
The current user does not have the necessary read/write permissions to access the serial port.
fix
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.
AttributeError: 'NoneType' object has no attribute 'write'
The `transport` or `protocol` object obtained from `pyserial_asyncio.open_serial_connection` is `None`, indicating that the connection failed to establish or was not properly initialized.
fix
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.
asyncio.exceptions.CancelledError
An asyncio task performing operations, such as reading from the serial port, was cancelled without proper exception handling, typically during program shutdown or explicit task cancellation.
fix
Wrap `await` calls that might be cancelled in `try...except asyncio.CancelledError` blocks, and ensure graceful task shutdown before closing the event loop.
Upgrade
Version history
0.6latest on PyPI · released Sep 30, 2021
Audit
Dependencies
pyserialrequiredCore dependency for serial port communication.
Agent activity
11 hits · last 30 days
node
8
Amazon
1
Resources
pyserial-asyncio — pip install pyserial-asyncio · libregistry