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
37 changes: 27 additions & 10 deletions can/interfaces/pcan/pcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,29 +76,46 @@
TPCANMsgFD,
)

if IS_WINDOWS:
import ctypes

# Set up logging
log = logging.getLogger("can.pcan")

MIN_PCAN_API_VERSION = version.parse("4.2.0")

# explicit uninitialized marker 'None' to distinguish from the case where the boot time is 0 (Linux)
boottimeEpoch = None
if IS_LINUX:
# PCAN-Basic for Linux already returns timestamps relative to the Unix epoch.
boottimeEpoch = 0
elif IS_WINDOWS:
# GetTickCount64 exists since Windows Vista and python-can requires
# Python >= 3.11, which runs only on Windows 8.1 or newer
get_tick_count = ctypes.windll.kernel32.GetTickCount64
get_tick_count.restype = ctypes.c_ulonglong
try:
tick_count = get_tick_count()
except OSError:
log.warning("Call to 'GetTickCount64' failed")
boottimeEpoch = 0
else:
boottimeEpoch = time.time() - tick_count / 1000
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:
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
log.warning("uptime library not available")
else:
if boottime := uptime.boottime():
boottimeEpoch = boottime.timestamp()

if boottimeEpoch is None:
# No success in somehow determining the boottimeEpoch, therefore at least
# warn the user about how to interpret the timestamps
log.warning("Timestamps are relative to boot time and not to Epoch UTC")
boottimeEpoch = 0

HAS_EVENTS = False

Expand Down
2 changes: 2 additions & 0 deletions doc/changelog.d/2153.changed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Update PCAN timestamp determination for Linux and Windows and fall back to
the ``uptime`` package where necessary (if ``uptime`` is available).
14 changes: 10 additions & 4 deletions doc/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,16 @@ Download and install the latest driver for your interface:
- `Linux <https://www.peak-system.com/Downloads.76.0.html?&L=1>`__ (`also works without <https://www.peak-system.com/fileadmin/media/linux/index.htm>`__, see also :ref:`pcandoc linux installation`)
- `macOS <https://www.mac-can.com>`__

Note that PCANBasic API timestamps count seconds from system startup. To
convert these to epoch times, the uptime library is used. If it is not
available, the times are returned as number of seconds from system
startup. To install the uptime library, run ``pip install python-can[pcan]``.
Note that PCANBasic API timestamps count seconds from system startup.
Timestamp handling then depends on the platform:

- Linux: PCAN-Basic provides timestamps relative to the Unix epoch, so no
boot-time offset or ``uptime`` package is needed.
- Windows: the native API determines the boot time, so no ``uptime`` library
is needed.
- Other platforms: ``uptime`` converts timestamps to epoch times. If it is
unavailable, timestamps are returned as seconds from system startup. Install
the library with ``pip install python-can[pcan]``.

This library can take advantage of the `Python for Windows Extensions
<https://github.com/mhammond/pywin32>`__ library if installed.
Expand Down
16 changes: 11 additions & 5 deletions doc/interfaces/pcan.rst
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,17 @@ Beginning with version 3.4, Linux kernels support the PCAN adapters natively via
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.
- Linux: PCAN-Basic on Linux provides timestamps relative to the Unix epoch,
so no boot-time offset or ``uptime`` package is needed.
- Windows: the native Windows API determines the boot time, so no ``uptime``
package is needed.
- Other platforms: install ``python-can[pcan]`` to use ``uptime`` for
conversion of boot-relative timestamps to epoch timestamps.

.. note::

Knowing the boot time is not a requirement, but without a known boot time,
those platforms retain relative timestamps.

Bus
---
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ cantact = ["cantact>=0.0.7"]
cvector = ["python-can-cvector"]
gs-usb = ["gs-usb>=0.2.1", "pyusb>=1.0.2"]
nixnet = ["nixnet>=0.3.2"]
pcan = ["uptime~=3.0.1"]
pcan = ["uptime~=3.0.1; platform_system != 'Windows' and platform_system != 'Linux'"]
remote = ["python-can-remote"]
sontheim = ["python-can-sontheim>=0.1.2"]
canine = ["python-can-canine>=0.2.2"]
Expand Down
42 changes: 23 additions & 19 deletions test/test_pcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
import struct
import sys
import unittest
from datetime import datetime, timezone
from types import ModuleType
from types import ModuleType, SimpleNamespace
from unittest import mock
from unittest.mock import Mock, patch

Expand Down Expand Up @@ -228,9 +227,9 @@ def test_recv(self):

timestamp = TPCANTimestamp()
self.mock_pcan.Read = Mock(return_value=(PCAN_ERROR_OK, msg, timestamp))
self.bus = can.Bus(interface="pcan")

recv_msg = self.bus.recv()
with patch.object(pcan_module, "boottimeEpoch", 0):
self.bus = can.Bus(interface="pcan")
recv_msg = self.bus.recv()
self.assertEqual(recv_msg.arbitration_id, msg.ID)
self.assertEqual(recv_msg.dlc, msg.LEN)
self.assertEqual(recv_msg.is_extended_id, True)
Expand All @@ -252,9 +251,9 @@ def test_recv_fd(self):

self.mock_pcan.ReadFD = Mock(return_value=(PCAN_ERROR_OK, msg, timestamp))

self.bus = can.Bus(interface="pcan", fd=True)

recv_msg = self.bus.recv()
with patch.object(pcan_module, "boottimeEpoch", 0):
self.bus = can.Bus(interface="pcan", fd=True)
recv_msg = self.bus.recv()
self.assertEqual(recv_msg.arbitration_id, msg.ID)
self.assertEqual(recv_msg.dlc, msg.DLC)
self.assertEqual(recv_msg.is_extended_id, True)
Expand Down Expand Up @@ -291,23 +290,28 @@ def test_recv_skips_status_frames(self, name, fd):
self.assertSequenceEqual(recv_msg.data, [0xAB])
self.assertIsNone(self.bus.recv(timeout=0))

def _load_timestamp_backend(self, linux: bool) -> ModuleType:
def _load_timestamp_backend(self, linux: bool, windows: 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
get_tick_count = Mock(return_value=100_000_000)
get_tick_count.restype = ctypes.c_ulonglong
fake_windll = SimpleNamespace(
kernel32=SimpleNamespace(GetTickCount64=get_tick_count)
)
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)

with patch.dict(sys.modules):
sys.modules.pop("uptime", None)
with (
patch("can.interfaces.pcan.basic.IS_LINUX", linux),
patch("can.interfaces.pcan.basic.IS_WINDOWS", windows),
patch.object(ctypes, "windll", fake_windll, create=True),
patch("time.time", return_value=1_700_100_000),
):
spec.loader.exec_module(backend)
return backend

@parameterized.expand(
Expand All @@ -318,7 +322,7 @@ def _load_timestamp_backend(self, linux: bool) -> ModuleType:
]
)
def test_timestamp_clock(self, name: str, linux: bool, fd: bool) -> None:
backend = self._load_timestamp_backend(linux)
backend = self._load_timestamp_backend(linux, windows=not linux)
backend.HAS_EVENTS = False
with patch.object(backend, "PCANBasic", return_value=self.mock_pcan):
self.bus = backend.PcanBus(fd=fd)
Expand Down
Loading