Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix inefficiencies, causes write delays to drop #1572

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 13 additions & 23 deletions can/interfaces/slcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ class slcanBus(BusABC):

_SLEEP_AFTER_SERIAL_OPEN = 2 # in seconds

_OK = b"\r"
_ERROR = b"\a"
_OK = ord(b"\r")
_ERROR = ord(b"\a")

LINE_TERMINATOR = b"\r"

Expand All @@ -62,7 +62,7 @@ def __init__(
btr: Optional[str] = None,
sleep_after_open: float = _SLEEP_AFTER_SERIAL_OPEN,
rtscts: bool = False,
timeout: float = 0.001,
timeout: float = 0.00005,
**kwargs: Any,
) -> None:
"""
Expand Down Expand Up @@ -153,27 +153,17 @@ def _write(self, string: str) -> None:
self.serialPortOrig.flush()

def _read(self, timeout: Optional[float]) -> Optional[str]:
_timeout = serial.Timeout(timeout)

with error_check("Could not read from serial device"):
while True:
# Due to accessing `serialPortOrig.in_waiting` too often will reduce the performance.
# We read the `serialPortOrig.in_waiting` only once here.
in_waiting = self.serialPortOrig.in_waiting
for _ in range(max(1, in_waiting)):
new_byte = self.serialPortOrig.read(size=1)
if new_byte:
self._buffer.extend(new_byte)
else:
break

if new_byte in (self._ERROR, self._OK):
string = self._buffer.decode()
self._buffer.clear()
return string

if _timeout.expired():
break
in_waiting = self.serialPortOrig.in_waiting
if in_waiting:
self._buffer.extend(self.serialPortOrig.read(size=in_waiting))
for idx, new_byte in enumerate(self._buffer):
if new_byte in (self._ERROR, self._OK):
# Only decode up to idx
string = self._buffer[: idx].decode()
# Delete self._buffer up to idx
self._buffer = self._buffer[idx+1:]
return string

return None

Expand Down