From 3c61634d94b33a2510ed70848416ba56225d1611 Mon Sep 17 00:00:00 2001 From: Silver Valdvee Date: Fri, 21 Apr 2023 22:06:58 +0300 Subject: [PATCH 1/2] Fix inefficiencies, causes write delays to drop --- can/interfaces/slcan.py | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/can/interfaces/slcan.py b/can/interfaces/slcan.py index 21306f28f..f5f625c24 100644 --- a/can/interfaces/slcan.py +++ b/can/interfaces/slcan.py @@ -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" @@ -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: """ @@ -156,24 +156,16 @@ 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 From 890c4edb0d61d881d42c3c541a5a8cc1eea7a731 Mon Sep 17 00:00:00 2001 From: Silver Valdvee Date: Fri, 21 Apr 2023 22:22:06 +0300 Subject: [PATCH 2/2] Remove removed timeout --- can/interfaces/slcan.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/can/interfaces/slcan.py b/can/interfaces/slcan.py index f5f625c24..ac0916432 100644 --- a/can/interfaces/slcan.py +++ b/can/interfaces/slcan.py @@ -153,8 +153,6 @@ 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"): in_waiting = self.serialPortOrig.in_waiting if in_waiting: