diff --git a/can/interfaces/socketcan/socketcan.py b/can/interfaces/socketcan/socketcan.py index 5970d8a20..561991a90 100644 --- a/can/interfaces/socketcan/socketcan.py +++ b/can/interfaces/socketcan/socketcan.py @@ -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 */ @@ -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. @@ -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() diff --git a/doc/changelog.d/1538.fixed.rst b/doc/changelog.d/1538.fixed.rst new file mode 100644 index 000000000..ef692e2ff --- /dev/null +++ b/doc/changelog.d/1538.fixed.rst @@ -0,0 +1 @@ +Catch ``OSError`` when enabling ``SO_TIMESTAMPNS`` in ``SocketcanBus`` and fall back to ``time.time()`` when receive ancillary data is unavailable. diff --git a/test/test_socketcan.py b/test/test_socketcan.py index 3b5430a14..a6de057d1 100644 --- a/test/test_socketcan.py +++ b/test/test_socketcan.py @@ -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()