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
21 changes: 14 additions & 7 deletions can/interfaces/serial/serial_can.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,15 @@ def send(self, msg: Message, timeout: float | None = None) -> None:
except serial.SerialTimeoutException as error:
raise CanTimeoutError() from error

def _read_exact(self, size: int) -> bytes:
data = cast("bytes", self._ser.read(size))
if len(data) != size:
raise CanOperationError(
f"serial read timed out in the middle of a frame "
f"(expected {size} bytes, got {len(data)})"
)
return data

def _recv_internal(self, timeout: float | None) -> tuple[Message | None, bool]:
"""
Read a message from the serial device.
Expand All @@ -176,14 +185,12 @@ def _recv_internal(self, timeout: float | None) -> tuple[Message | None, bool]:
try:
rx_byte = self._ser.read()
if rx_byte and ord(rx_byte) == 0xAA:
s = self._ser.read(4)
timestamp = struct.unpack("<I", s)[0]
dlc = ord(self._ser.read())
timestamp = struct.unpack("<I", self._read_exact(4))[0]
dlc = self._read_exact(1)[0]
if dlc > 8:
raise ValueError("received DLC may not exceed 8 bytes")

s = self._ser.read(4)
arbitration_id = struct.unpack("<I", s)[0]
arbitration_id = struct.unpack("<I", self._read_exact(4))[0]
is_extended_id = bool(arbitration_id & CAN_EFF_FLAG)
is_error_frame = bool(arbitration_id & CAN_ERR_FLAG)
is_remote_frame = bool(arbitration_id & CAN_RTR_FLAG)
Expand All @@ -195,9 +202,9 @@ def _recv_internal(self, timeout: float | None) -> tuple[Message | None, bool]:

# a remote frame carries the requested length in the DLC but
# no payload, see send()
data = b"" if is_remote_frame else self._ser.read(dlc)
data = b"" if is_remote_frame else self._read_exact(dlc)

delimiter_byte = ord(self._ser.read())
delimiter_byte = self._read_exact(1)[0]
if delimiter_byte == 0xBB:
# received message data okay
msg = Message(
Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/2175.fixed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The ``serial`` interface raises :class:`~can.exceptions.CanOperationError` when a read times out in the middle of a frame, instead of ``struct.error`` or ``TypeError``, or a message with a truncated payload.
33 changes: 32 additions & 1 deletion test/serial_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
Copyright: 2017 Boris Wenzlaff
"""

import struct
import unittest
from unittest.mock import patch
from unittest.mock import Mock, patch

import can
from can.interfaces.serial.serial_can import SerialBus
Expand Down Expand Up @@ -217,6 +218,20 @@ def setUp(self):
def tearDown(self):
self.serial_dummy.reset()

def test_short_payload_with_trailing_delimiter_raises_can_operation_error(self):
self.mock_serial.return_value.read = Mock(
side_effect=[
b"\xaa",
bytes(4),
b"\x08",
struct.pack("<I", 0x123),
b"\x01\x02",
b"\xbb",
]
)
with self.assertRaises(can.CanOperationError):
self.bus.recv(timeout=0)


class SimpleSerialLoopTest(unittest.TestCase, SimpleSerialTestBase):
def __init__(self, *args, **kwargs):
Expand All @@ -229,6 +244,22 @@ def setUp(self):
def tearDown(self):
self.bus.shutdown()

def test_truncated_frame_raises_can_operation_error(self):
frame = (
b"\xaa"
+ struct.pack("<I", 0)
+ bytes([8])
+ struct.pack("<I", 0x123)
+ bytes(range(1, 9))
+ b"\xbb"
)
for cut in (3, 5, 8, len(frame) - 1):
with self.subTest(cut=cut):
self.bus._ser.reset_input_buffer()
self.bus._ser.write(frame[:cut])
with self.assertRaises(can.CanOperationError):
self.bus.recv(timeout=0.05)


if __name__ == "__main__":
unittest.main()