Skip to content
Merged
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
43 changes: 23 additions & 20 deletions can/interfaces/socketcan/socketcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,18 +635,21 @@ def capture_message(sock: socket.socket, get_channel: bool = False) -> Message |
can_id, can_dlc, flags, data = dissect_can_frame(cf)

# Fetching the timestamp
assert len(ancillary_data) == 1, "only requested a single extra field"
cmsg_level, cmsg_type, cmsg_data = ancillary_data[0]
assert (
cmsg_level == socket.SOL_SOCKET and cmsg_type == constants.SO_TIMESTAMPNS
), "received control message type that was not requested"
# see https://man7.org/linux/man-pages/man3/timespec.3.html -> struct timespec for details
seconds, nanoseconds = RECEIVED_TIMESTAMP_STRUCT.unpack_from(cmsg_data)
if nanoseconds >= 1e9:
raise can.CanOperationError(
f"Timestamp nanoseconds field was out of range: {nanoseconds} not less than 1e9"
)
timestamp = seconds + nanoseconds * 1e-9
if ancillary_data:
assert len(ancillary_data) == 1, "only requested a single extra field"
cmsg_level, cmsg_type, cmsg_data = ancillary_data[0]
assert (
cmsg_level == socket.SOL_SOCKET and cmsg_type == constants.SO_TIMESTAMPNS
), "received control message type that was not requested"
# see https://man7.org/linux/man-pages/man3/timespec.3.html -> struct timespec for details
seconds, nanoseconds = RECEIVED_TIMESTAMP_STRUCT.unpack_from(cmsg_data)
if nanoseconds >= 1e9:
raise can.CanOperationError(
f"Timestamp nanoseconds field was out of range: {nanoseconds} not less than 1e9"
)
timestamp = seconds + nanoseconds * 1e-9
else:
timestamp = time.time()

# EXT, RTR, ERR flags -> boolean attributes
# /* special address description flags for the CAN_ID */
Expand Down Expand Up @@ -711,8 +714,9 @@ def __init__(
but no exception will be thrown. This includes enabling:

- that own messages should be received,
- CAN-FD frames and
- error frames.
- CAN-FD frames,
- error frames and
- nanosecond timestamping.

:param channel:
The can interface name with which to create this bus.
Expand Down Expand Up @@ -783,12 +787,11 @@ def __init__(
except OSError as error:
log.error("Could not enable error frames (%s)", error)

# enable nanosecond resolution timestamping
# we can always do this since
# 1) it is guaranteed to be at least as precise as without
# 2) it is available since Linux 2.6.22, and CAN support was only added afterward
# so this is always supported by the kernel
self.socket.setsockopt(socket.SOL_SOCKET, constants.SO_TIMESTAMPNS, 1)
# enable nanosecond resolution timestamping when supported by the environment
try:
self.socket.setsockopt(socket.SOL_SOCKET, constants.SO_TIMESTAMPNS, 1)
except OSError as error:
log.error("Could not enable nanosecond timestamping (%s)", error)

# Create epoll instance and register socket for read and write events
self._epoll = select.epoll()
Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/1538.fixed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Catch ``OSError`` when enabling ``SO_TIMESTAMPNS`` in ``SocketcanBus`` and fall back to ``time.time()`` when receive ancillary data is unavailable.
58 changes: 58 additions & 0 deletions test/test_socketcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,64 @@ def test_send_does_not_retry_other_errors(self):
self.assertEqual(ctx.exception.error_code, errno.ENETDOWN)
self.assertEqual(bus.socket.send.call_count, 1)

def test_init_ignores_so_timestampns_oserror(self):
"""SocketcanBus.__init__ tolerates ENOPROTOOPT on SO_TIMESTAMPNS."""
mock_socket = Mock()
mock_socket.fileno.return_value = 3

def setsockopt_side_effect(level, optname, value):
if level == socket.SOL_SOCKET and optname == SO_TIMESTAMPNS:
raise OSError(errno.ENOPROTOOPT, "Protocol not available")

mock_socket.setsockopt.side_effect = setsockopt_side_effect
mock_epoll = Mock()
mock_epoll.closed = False

with (
patch(
"can.interfaces.socketcan.socketcan.create_socket",
return_value=mock_socket,
),
patch("can.interfaces.socketcan.socketcan.bind_socket"),
patch(
"can.interfaces.socketcan.socketcan.select.epoll",
create=True,
return_value=mock_epoll,
),
patch(
"can.interfaces.socketcan.socketcan.select.EPOLLIN",
1,
create=True,
),
patch(
"can.interfaces.socketcan.socketcan.select.EPOLLOUT",
4,
create=True,
),
):
bus = SocketcanBus(channel="vcan0")
bus.shutdown()

def test_capture_message_without_ancillary_data(self):
"""capture_message falls back to time.time() if ancillary_data is empty."""
expected = can.Message(
timestamp=1_700_000_000.5,
arbitration_id=0x123,
is_extended_id=False,
data=[1, 2, 3],
)
sock = Mock()
sock.recvmsg.return_value = (build_can_frame(expected), [], 0, ("vcan0",))

with patch(
"can.interfaces.socketcan.socketcan.time.time",
return_value=1_700_000_000.5,
):
received = capture_message(sock)

self.assertIsNotNone(received)
self.assertTrue(received.equals(expected), f"{received!r} != {expected!r}")


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