Skip to content
Open
Show file tree
Hide file tree
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
44 changes: 31 additions & 13 deletions can/interfaces/slcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,21 +219,39 @@ def _read(self, timeout: float | None) -> str | None:

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.
size = self.serialPortOrig.in_waiting or 1
self._buffer.extend(self.serialPortOrig.read(size))

for i, byte in enumerate(self._buffer):
if byte in (self._OK[0], self._ERROR[0]):
string = self._buffer[: i + 1].decode()
del self._buffer[: i + 1]
return string
size = (
self.serialPortOrig.in_waiting or 1
) # read the `serialPortOrig.in_waiting` only once.
self._buffer.extend(
self.serialPortOrig.read(size)
) # read serial at once

i1 = self._buffer.find(
self._OK
) # bytearray.find() or byte.find() is in C level
# an ERROR byte only matters if it comes before the first OK byte,
# so limit the second search to avoid scanning the whole backlog
i2 = self._buffer.find(
self._ERROR, 0, i1 if i1 >= 0 else len(self._buffer)
)

if i1 >= 0 and i2 >= 0:
# python if/else branch is faster than min()/max() but ruff FURB136 rewrites it
i = min(i2, i1)
elif i1 >= 0:
i = i1
elif i2 >= 0:
i = i2
else:
if _timeout.expired():
break
continue

if _timeout.expired():
break
string = self._buffer[: i + 1].decode()
del self._buffer[: i + 1]
return string

return None
return None

def flush(self) -> None:
self._buffer.clear()
Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/2080.changed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The ``slcan`` interface now finds frame terminators with the C-level ``bytearray.find`` instead of a Python-level byte loop, so ``recv()`` is faster and stays fast even when a large backlog of frames has accumulated in the serial buffer.