diff --git a/can/interfaces/slcan.py b/can/interfaces/slcan.py index 2ec4df238..73a18bd8c 100644 --- a/can/interfaces/slcan.py +++ b/can/interfaces/slcan.py @@ -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() diff --git a/doc/changelog.d/2080.changed.rst b/doc/changelog.d/2080.changed.rst new file mode 100644 index 000000000..44dd194e5 --- /dev/null +++ b/doc/changelog.d/2080.changed.rst @@ -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.