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
65 changes: 52 additions & 13 deletions can/interfaces/pcan/pcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,24 +81,63 @@

MIN_PCAN_API_VERSION = version.parse("4.2.0")

# The following cases need to be considered when determining the boottimeEpoch
# for PCAN timestamps:
#
# - Linux: PCAN-Basic for Linux already returns timestamps relative to the
# Unix epoch, so boottimeEpoch shall stay 0
# - Windows Vista or newer: Use Windows API to convert boot-relative
# timestamps to epoch times, so boottimeEpoch shall be set accordingly.
# - Windows XP or older: Use the uptime package to convert boot-relative
# timestamps to epoch times, so boottimeEpoch shall be set accordingly.
# - Other platforms: Use the uptime package to convert boot-relative
# timestamps to epoch times, so boottimeEpoch shall be set accordingly.
#
# If the boot time cannot be determined, timestamps remain relative to system
# startup and a warning is logged to inform the user how to interpret them.
boottimeEpoch = 0
if IS_LINUX:
# PCAN-Basic for Linux already returns timestamps relative to the Unix epoch.
boottimeEpoch = 0
# boottimeEpoch shall stay 0
pass
else:
try:
# use the "uptime" library if available
import uptime
if IS_WINDOWS:
# try first to determine boottimeEpoch via Windows-native API
# if this fails, we can still fallback to trying to import uptime
import ctypes
import time

# boottime() and fromtimestamp() are timezone offset, so the difference is not.
if uptime.boottime() is None:
boottimeEpoch = 0
try:
# GetTickCount64 exists since Windows Vista
# https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount64#requirements
# if we are running on an older version, try to fallback to uptime again
get_tick_count = ctypes.windll.kernel32.GetTickCount64
get_tick_count.restype = ctypes.c_ulonglong
except (AttributeError, OSError):
log.warning("Could not resolve 'GetTickCount64' from the Windows API")
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
try:
tick_count = get_tick_count()
except OSError:
log.warning("Call to 'GetTickCount64' failed")
else:
boottimeEpoch = time.time() - tick_count / 1000

if not boottimeEpoch:
# we are neither running on Windows or Linux, but still on a supported
# platform and the boottimeEpoch was still not set
try:
import uptime
except ImportError:
log.warning("uptime library not available")
else:
if boottime := uptime.boottime():
boottimeEpoch = boottime.timestamp()

if not boottimeEpoch:
# 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")

HAS_EVENTS = False

Expand Down
3 changes: 3 additions & 0 deletions doc/changelog.d/xxxx.changed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Update PCAN timestamp determination for Linux and Windows, using the Unix
epoch or native Windows system time APIs where available and falling back to
the ``uptime`` package where necessary.
3 changes: 3 additions & 0 deletions doc/changelog.d/xxxx.fixed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix script command tests by invoking module entry points with
``sys.executable`` and console entry points from the active Python environment
instead of relying on PATH resolution.
18 changes: 9 additions & 9 deletions doc/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@ 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]``.

This library can take advantage of the `Python for Windows Extensions
<https://github.com/mhammond/pywin32>`__ library if installed.
It will be used to get notified of new messages instead of
the CPU intensive polling that will otherwise have be used.
PCAN-Basic for Linux returns timestamps relative to the Unix epoch,
so no boot-time offset or ``uptime`` package is needed.
On Windows Vista or newer, the Windows API is used to convert
boot-relative timestamps to epoch times, so ``uptime`` is not needed.
On Windows XP or older and on other platforms, install
``python-can[pcan]`` to use ``uptime`` for timestamp conversion.

If the boot time cannot be determined, timestamps remain relative to system
startup.

IXXAT
~~~~~
Expand Down
17 changes: 12 additions & 5 deletions doc/interfaces/pcan.rst
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,18 @@ 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 Vista or newer: Windows API is used, ``uptime`` package is not needed.
- Windows XP or older: install ``python-can[pcan]`` to use ``uptime`` for
conversion of boot-relative timestamps to epoch timestamps.
- 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
71 changes: 60 additions & 11 deletions test/test_pcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
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 +228,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 +252,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,7 +291,13 @@ 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,
uptime_available: bool = True,
native_windows: bool = True,
) -> 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__
Expand All @@ -302,10 +308,22 @@ def _load_timestamp_backend(self, linux: bool) -> ModuleType:
uptime_module.boottime.return_value = datetime.fromtimestamp(
1_700_000_000, timezone.utc
)

uptime_entry = uptime_module if uptime_available else None
if native_windows:
get_tick_count = Mock(return_value=100_000_000)
get_tick_count.restype = ctypes.c_ulonglong
kernel32 = SimpleNamespace(GetTickCount64=get_tick_count)
else:
kernel32 = SimpleNamespace()
fake_windll = SimpleNamespace(kernel32=kernel32)

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}),
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),
patch.dict(sys.modules, {"uptime": uptime_entry}),
):
spec.loader.exec_module(backend)
return backend
Expand All @@ -318,7 +336,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 Expand Up @@ -356,6 +374,37 @@ def test_timestamp_clock(self, name: str, linux: bool, fd: bool) -> None:
msg.timestamp, expected_offset + raw_us / 1_000_000, places=6
)

def test_timestamp_linux_boot_offset_is_zero(self) -> None:
backend = self._load_timestamp_backend(linux=True, windows=False)
self.assertEqual(backend.boottimeEpoch, 0)

def test_timestamp_windows_native_boot_offset(self) -> None:
backend = self._load_timestamp_backend(
linux=False, windows=True, native_windows=True
)
self.assertAlmostEqual(backend.boottimeEpoch, 1_700_000_000, places=6)

def test_timestamp_windows_uptime_fallback(self) -> None:
backend = self._load_timestamp_backend(
linux=False, windows=True, native_windows=False
)
self.assertEqual(backend.boottimeEpoch, 1_700_000_000)

def test_timestamp_windows_without_boot_time_source(self) -> None:
backend = self._load_timestamp_backend(
linux=False,
windows=True,
uptime_available=False,
native_windows=False,
)
self.assertEqual(backend.boottimeEpoch, 0)

def test_timestamp_other_platform_uptime_fallback(self) -> None:
backend = self._load_timestamp_backend(
linux=False, windows=False, native_windows=False
)
self.assertEqual(backend.boottimeEpoch, 1_700_000_000)

@pytest.mark.timeout(3.0)
@patch("select.select", return_value=([], [], []))
def test_recv_no_message(self, mock_select):
Expand Down
29 changes: 19 additions & 10 deletions test/test_scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import sys
import unittest
from abc import ABCMeta, abstractmethod
from pathlib import Path

from .config import *

Expand All @@ -27,11 +28,13 @@ def test_do_commands_exist(self):
"""
for command in self._commands():
try:
args = (
command if isinstance(command, (list, tuple)) else command.split()
)
subprocess.check_output(
command.split(),
args,
stderr=subprocess.STDOUT,
encoding="utf-8",
shell=IS_WINDOWS,
)
except subprocess.CalledProcessError as e:
return_code = e.returncode
Expand All @@ -57,6 +60,12 @@ def test_does_not_crash(self):
module.main()
self.assertEqual(cm.exception.code, errno.EINVAL)

def _console_command(self, name: str) -> list[str]:
executable = Path(sys.executable).parent / name
if IS_WINDOWS:
executable = executable.with_suffix(".exe")
return [str(executable), "--help"]

@abstractmethod
def _commands(self):
"""Returns an Iterable of commands that should "succeed", meaning they exit
Expand All @@ -73,8 +82,8 @@ def _import(self):
class TestLoggerScript(CanScriptTest):
def _commands(self):
commands = [
"python -m can.logger --help",
"can_logger --help",
[sys.executable, "-m", "can.logger", "--help"],
self._console_command("can_logger"),
]
return commands

Expand All @@ -87,8 +96,8 @@ def _import(self):
class TestPlayerScript(CanScriptTest):
def _commands(self):
commands = [
"python -m can.player --help",
"can_player --help",
[sys.executable, "-m", "can.player", "--help"],
self._console_command("can_player"),
]
return commands

Expand All @@ -101,8 +110,8 @@ def _import(self):
class TestBridgeScript(CanScriptTest):
def _commands(self):
commands = [
"python -m can.bridge --help",
"can_bridge --help",
[sys.executable, "-m", "can.bridge", "--help"],
self._console_command("can_bridge"),
]
return commands

Expand All @@ -115,8 +124,8 @@ def _import(self):
class TestLogconvertScript(CanScriptTest):
def _commands(self):
commands = [
"python -m can.logconvert --help",
"can_logconvert --help",
[sys.executable, "-m", "can.logconvert", "--help"],
self._console_command("can_logconvert"),
]
return commands

Expand Down