-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Expand dependancy list rename aioserial_instance to stream
- Loading branch information
1 parent
2c46785
commit 7eb9da1
Showing
2 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import asyncio | ||
from dataclasses import dataclass | ||
|
||
import aioserial | ||
|
||
|
||
class NotOpenedError(Exception): | ||
pass | ||
|
||
|
||
@dataclass | ||
class SerialConnectionSettings: | ||
port: str | ||
baud: int = 115200 | ||
|
||
|
||
class SerialConnection: | ||
def __init__(self): | ||
self.stream = None | ||
self._lock = asyncio.Lock() | ||
|
||
async def connect(self, settings: SerialConnectionSettings) -> None: | ||
self.stream = aioserial.AioSerial(port=settings.port, baudrate=settings.baud) | ||
|
||
def ensure_open(self): | ||
if self.stream is None: | ||
raise NotOpenedError( | ||
"Need to call connect() before using SerialConnection." | ||
) | ||
|
||
async def send_command(self, message: bytes) -> None: | ||
async with self._lock: | ||
self.ensure_open() | ||
await self._send_message(message) | ||
|
||
async def send_query(self, message: bytes, response_size: int) -> bytes: | ||
async with self._lock: | ||
self.ensure_open() | ||
await self._send_message(message) | ||
return await self._receive_response(response_size) | ||
|
||
async def close(self) -> None: | ||
async with self._lock: | ||
self.ensure_open() | ||
self.stream.close() | ||
self.stream = None | ||
|
||
async def _send_message(self, message): | ||
await self.stream.write_async(message) | ||
|
||
async def _receive_response(self, size): | ||
return await self.stream.read_async(size) | ||