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
28 changes: 16 additions & 12 deletions can/interfaces/pcan/pcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 3 additions & 0 deletions doc/changelog.d/2108.fixed.rst
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 9 additions & 0 deletions doc/interfaces/pcan.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
---

Expand Down
70 changes: 70 additions & 0 deletions test/test_pcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 *


Expand Down Expand Up @@ -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):
Expand Down
Loading