diff --git a/can/interfaces/pcan/pcan.py b/can/interfaces/pcan/pcan.py index a11a7fa6c..ae188163e 100644 --- a/can/interfaces/pcan/pcan.py +++ b/can/interfaces/pcan/pcan.py @@ -80,20 +80,24 @@ MIN_PCAN_API_VERSION = version.parse("4.2.0") -try: - # use the "uptime" library if available - import uptime +if IS_LINUX: + # PCAN-Basic for Linux already returns timestamps relative to the Unix epoch. + boottimeEpoch = 0 +else: + try: + # use the "uptime" library if available + import uptime - # boottime() and fromtimestamp() are timezone offset, so the difference is not. - if uptime.boottime() is None: + # boottime() and fromtimestamp() are timezone offset, so the difference is not. + if uptime.boottime() is None: + boottimeEpoch = 0 + else: + boottimeEpoch = uptime.boottime().timestamp() + except ImportError: + log.warning( + "uptime library not available, timestamps are relative to boot time and not to Epoch UTC", + ) boottimeEpoch = 0 - else: - boottimeEpoch = uptime.boottime().timestamp() -except ImportError: - log.warning( - "uptime library not available, timestamps are relative to boot time and not to Epoch UTC", - ) - boottimeEpoch = 0 HAS_EVENTS = False diff --git a/doc/changelog.d/2108.fixed.rst b/doc/changelog.d/2108.fixed.rst new file mode 100644 index 000000000..81ba7d65d --- /dev/null +++ b/doc/changelog.d/2108.fixed.rst @@ -0,0 +1,3 @@ +Fixed PCAN classic CAN and CAN FD timestamps on Linux being offset by the system +boot time when ``uptime`` is installed. Linux timestamps no longer depend on +``uptime``; timestamp conversion on other platforms is unchanged. diff --git a/doc/interfaces/pcan.rst b/doc/interfaces/pcan.rst index 48e7dba05..60011ee08 100644 --- a/doc/interfaces/pcan.rst +++ b/doc/interfaces/pcan.rst @@ -45,6 +45,15 @@ Linux installation Beginning with version 3.4, Linux kernels support the PCAN adapters natively via :doc:`/interfaces/socketcan`, refer to: :ref:`socketcan-pcan`. +Timestamps +---------- + +PCAN-Basic on Linux provides timestamps relative to the Unix epoch, so no boot-time +offset or ``uptime`` package is needed. On other supported platforms, install +``python-can[pcan]`` to use ``uptime`` for conversion of boot-relative timestamps to +epoch timestamps. Without a known boot time, those platforms retain relative +timestamps. + Bus --- diff --git a/test/test_pcan.py b/test/test_pcan.py index 9cd208113..dc4cf5a8b 100644 --- a/test/test_pcan.py +++ b/test/test_pcan.py @@ -3,8 +3,12 @@ """ import ctypes +import importlib.util import struct +import sys import unittest +from datetime import datetime, timezone +from types import ModuleType from unittest import mock from unittest.mock import Mock, patch @@ -15,6 +19,7 @@ from can import BusState, CanProtocol from can.exceptions import CanInitializationError from can.interfaces.pcan import PcanBus, PcanError, basic +from can.interfaces.pcan import pcan as pcan_module from can.interfaces.pcan.basic import * @@ -258,6 +263,71 @@ def test_recv_fd(self): self.assertEqual(recv_msg.timestamp, 0) self.assertEqual(recv_msg.channel, "PCAN_USBBUS1") + def _load_timestamp_backend(self, linux: bool) -> ModuleType: + # The platform choice is made at import time; use a separate namespace. + spec = importlib.util.spec_from_file_location( + "can.interfaces.pcan._timestamp_test", pcan_module.__file__ + ) + assert spec is not None and spec.loader is not None + backend = importlib.util.module_from_spec(spec) + uptime_module = Mock() + uptime_module.boottime.return_value = datetime.fromtimestamp( + 1_700_000_000, timezone.utc + ) + with ( + patch("can.interfaces.pcan.basic.IS_LINUX", linux), + patch("can.interfaces.pcan.basic.IS_WINDOWS", not linux), + patch.dict(sys.modules, {"uptime": uptime_module}), + ): + spec.loader.exec_module(backend) + return backend + + @parameterized.expand( + [ + ("linux_classic", True, False), + ("linux_fd", True, True), + ("windows_classic", False, False), + ] + ) + def test_timestamp_clock(self, name: str, linux: bool, fd: bool) -> None: + backend = self._load_timestamp_backend(linux) + backend.HAS_EVENTS = False + with patch.object(backend, "PCANBasic", return_value=self.mock_pcan): + self.bus = backend.PcanBus(fd=fd) + + # Linux timestamps are epoch microseconds, not boot-relative. + raw_us = 1_790_000_000_123_456 if linux else 123_456 + if fd: + self.mock_pcan.ReadFD.return_value = ( + PCAN_ERROR_OK, + TPCANMsgFD( + ID=0x123, + DLC=9, + MSGTYPE=PCAN_MESSAGE_FD.value, + DATA=(ctypes.c_ubyte * 64)(), + ), + TPCANTimestampFD(raw_us), + ) + else: + millis, micros = divmod(raw_us, 1000) + overflow, millis = divmod(millis, 1 << 32) + self.mock_pcan.Read.return_value = ( + PCAN_ERROR_OK, + TPCANMsg( + ID=0x123, + LEN=1, + MSGTYPE=PCAN_MESSAGE_STANDARD, + DATA=(ctypes.c_ubyte * 8)(), + ), + TPCANTimestamp(millis=millis, millis_overflow=overflow, micros=micros), + ) + msg = self.bus.recv(timeout=0) + self.assertIsNotNone(msg) + expected_offset = 0 if linux else 1_700_000_000 + self.assertAlmostEqual( + msg.timestamp, expected_offset + raw_us / 1_000_000, places=6 + ) + @pytest.mark.timeout(3.0) @patch("select.select", return_value=([], [], [])) def test_recv_no_message(self, mock_select):