From 7de6da60c483e07458b98b8d918a8ff58593d292 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Waldh=C3=B6r?= Date: Tue, 24 Nov 2026 23:04:22 +0100 Subject: [PATCH 1/4] Fix PCAN timestamp determination across platforms Use native epoch timestamps on Linux and Windows Vista and newer, with 'uptime' as a fallback for legacy Windows and other platforms. --- can/interfaces/pcan/pcan.py | 64 ++++++++++++++++++++++------ doc/changelog.d/xxxx.changed.rst | 3 ++ doc/changelog.d/xxxx.fixed.rst | 3 ++ doc/installation.rst | 18 ++++---- doc/interfaces/pcan.rst | 17 +++++--- test/test_pcan.py | 71 +++++++++++++++++++++++++++----- test/test_scripts.py | 27 +++++++----- 7 files changed, 155 insertions(+), 48 deletions(-) create mode 100644 doc/changelog.d/xxxx.changed.rst create mode 100644 doc/changelog.d/xxxx.fixed.rst diff --git a/can/interfaces/pcan/pcan.py b/can/interfaces/pcan/pcan.py index 2bc2294e2..4edf532be 100644 --- a/can/interfaces/pcan/pcan.py +++ b/can/interfaces/pcan/pcan.py @@ -81,24 +81,62 @@ 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 + 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: + try: + tick_count = get_tick_count() + except OSError: + log.warning("Call to 'GetTickCount64' failed") + else: + boottimeEpoch = time.time() - tick_count / 1000 - # boottime() and fromtimestamp() are timezone offset, so the difference is not. - if uptime.boottime() is None: - boottimeEpoch = 0 + 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: - 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 + 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 diff --git a/doc/changelog.d/xxxx.changed.rst b/doc/changelog.d/xxxx.changed.rst new file mode 100644 index 000000000..3e292d6d8 --- /dev/null +++ b/doc/changelog.d/xxxx.changed.rst @@ -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. diff --git a/doc/changelog.d/xxxx.fixed.rst b/doc/changelog.d/xxxx.fixed.rst new file mode 100644 index 000000000..a997737ca --- /dev/null +++ b/doc/changelog.d/xxxx.fixed.rst @@ -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. diff --git a/doc/installation.rst b/doc/installation.rst index 822de2ce0..e65d75646 100644 --- a/doc/installation.rst +++ b/doc/installation.rst @@ -59,15 +59,15 @@ Download and install the latest driver for your interface: - `Linux `__ (`also works without `__, see also :ref:`pcandoc linux installation`) - `macOS `__ -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 -`__ 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 ~~~~~ diff --git a/doc/interfaces/pcan.rst b/doc/interfaces/pcan.rst index 60011ee08..7eb41b1d7 100644 --- a/doc/interfaces/pcan.rst +++ b/doc/interfaces/pcan.rst @@ -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 --- diff --git a/test/test_pcan.py b/test/test_pcan.py index 5fcdfc2fc..67919247a 100644 --- a/test/test_pcan.py +++ b/test/test_pcan.py @@ -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 @@ -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) @@ -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) @@ -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__ @@ -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("ctypes.windll", fake_windll), + patch("time.time", return_value=1_700_100_000), + patch.dict(sys.modules, {"uptime": uptime_entry}), ): spec.loader.exec_module(backend) return backend @@ -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) @@ -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): diff --git a/test/test_scripts.py b/test/test_scripts.py index c1a6c082d..19614b635 100644 --- a/test/test_scripts.py +++ b/test/test_scripts.py @@ -9,6 +9,7 @@ import sys import unittest from abc import ABCMeta, abstractmethod +from pathlib import Path from .config import * @@ -27,11 +28,11 @@ 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 @@ -57,6 +58,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 @@ -73,8 +80,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 @@ -87,8 +94,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 @@ -101,8 +108,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 @@ -115,8 +122,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 From f8192e7705f744fe221dd69eb66cc1a6846bf33a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Waldh=C3=B6r?= Date: Wed, 25 Nov 2026 00:08:14 +0100 Subject: [PATCH 2/4] Fix unit tests on non-Windows platforms Fix formatting --- can/interfaces/pcan/pcan.py | 7 ++++--- test/test_pcan.py | 2 +- test/test_scripts.py | 4 +++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/can/interfaces/pcan/pcan.py b/can/interfaces/pcan/pcan.py index 4edf532be..d31724295 100644 --- a/can/interfaces/pcan/pcan.py +++ b/can/interfaces/pcan/pcan.py @@ -92,7 +92,7 @@ # 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 @@ -106,6 +106,7 @@ # if this fails, we can still fallback to trying to import uptime import ctypes import time + try: # GetTickCount64 exists since Windows Vista # https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount64#requirements @@ -130,11 +131,11 @@ except ImportError: log.warning("uptime library not available") else: - if boottime:= uptime.boottime(): + if boottime := uptime.boottime(): boottimeEpoch = boottime.timestamp() if not boottimeEpoch: - # No success in somehow determining the boottimeEpoch, therefore at least + # 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") diff --git a/test/test_pcan.py b/test/test_pcan.py index 67919247a..613bb1bdb 100644 --- a/test/test_pcan.py +++ b/test/test_pcan.py @@ -321,7 +321,7 @@ def _load_timestamp_backend( with ( patch("can.interfaces.pcan.basic.IS_LINUX", linux), patch("can.interfaces.pcan.basic.IS_WINDOWS", windows), - patch("ctypes.windll", fake_windll), + patch.object(ctypes, "windll", fake_windll, create=True), patch("time.time", return_value=1_700_100_000), patch.dict(sys.modules, {"uptime": uptime_entry}), ): diff --git a/test/test_scripts.py b/test/test_scripts.py index 19614b635..2d71d2eea 100644 --- a/test/test_scripts.py +++ b/test/test_scripts.py @@ -28,7 +28,9 @@ def test_do_commands_exist(self): """ for command in self._commands(): try: - args = command if isinstance(command, (list, tuple)) else command.split() + args = ( + command if isinstance(command, (list, tuple)) else command.split() + ) subprocess.check_output( args, stderr=subprocess.STDOUT, From 3133178489a1503349cded42f1637298fc323c91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Waldh=C3=B6r?= Date: Thu, 26 Nov 2026 22:32:34 +0100 Subject: [PATCH 3/4] Address review - Simplify overall implementation (possible due to the packages platform constraints) - Simplify tests - Fix documentation - Remove unrelated test-only fix (follow up PR will be created) --- can/interfaces/pcan/pcan.py | 84 ++++++++++++-------------------- doc/changelog.d/2153.changed.rst | 2 + doc/changelog.d/xxxx.changed.rst | 3 -- doc/changelog.d/xxxx.fixed.rst | 3 -- doc/installation.rst | 24 +++++---- doc/interfaces/pcan.rst | 5 +- pyproject.toml | 2 +- test/test_pcan.py | 73 ++++++--------------------- test/test_scripts.py | 29 ++++------- 9 files changed, 75 insertions(+), 150 deletions(-) create mode 100644 doc/changelog.d/2153.changed.rst delete mode 100644 doc/changelog.d/xxxx.changed.rst delete mode 100644 doc/changelog.d/xxxx.fixed.rst diff --git a/can/interfaces/pcan/pcan.py b/can/interfaces/pcan/pcan.py index d31724295..eff5b039d 100644 --- a/can/interfaces/pcan/pcan.py +++ b/can/interfaces/pcan/pcan.py @@ -76,68 +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") -# 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 +# 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 shall stay 0 - pass -else: - 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 - - 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: - 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 + 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: - import uptime - except ImportError: - log.warning("uptime library not available") + tick_count = get_tick_count() + except OSError: + log.warning("Call to 'GetTickCount64' failed") + boottimeEpoch = 0 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") + boottimeEpoch = time.time() - tick_count / 1000 +else: + try: + # use the "uptime" library if available + import uptime + except ImportError: + 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 diff --git a/doc/changelog.d/2153.changed.rst b/doc/changelog.d/2153.changed.rst new file mode 100644 index 000000000..b31b87751 --- /dev/null +++ b/doc/changelog.d/2153.changed.rst @@ -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). diff --git a/doc/changelog.d/xxxx.changed.rst b/doc/changelog.d/xxxx.changed.rst deleted file mode 100644 index 3e292d6d8..000000000 --- a/doc/changelog.d/xxxx.changed.rst +++ /dev/null @@ -1,3 +0,0 @@ -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. diff --git a/doc/changelog.d/xxxx.fixed.rst b/doc/changelog.d/xxxx.fixed.rst deleted file mode 100644 index a997737ca..000000000 --- a/doc/changelog.d/xxxx.fixed.rst +++ /dev/null @@ -1,3 +0,0 @@ -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. diff --git a/doc/installation.rst b/doc/installation.rst index e65d75646..2184ce18a 100644 --- a/doc/installation.rst +++ b/doc/installation.rst @@ -59,15 +59,21 @@ Download and install the latest driver for your interface: - `Linux `__ (`also works without `__, see also :ref:`pcandoc linux installation`) - `macOS `__ -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. +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 +`__ 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. IXXAT ~~~~~ diff --git a/doc/interfaces/pcan.rst b/doc/interfaces/pcan.rst index 7eb41b1d7..17abe5912 100644 --- a/doc/interfaces/pcan.rst +++ b/doc/interfaces/pcan.rst @@ -50,9 +50,8 @@ 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. +- 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. diff --git a/pyproject.toml b/pyproject.toml index 9aa2987a4..a844e346b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"] diff --git a/test/test_pcan.py b/test/test_pcan.py index 613bb1bdb..dfc87620b 100644 --- a/test/test_pcan.py +++ b/test/test_pcan.py @@ -7,7 +7,6 @@ import struct import sys import unittest -from datetime import datetime, timezone from types import ModuleType, SimpleNamespace from unittest import mock from unittest.mock import Mock, patch @@ -291,41 +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, - windows: bool, - uptime_available: bool = True, - native_windows: bool = True, - ) -> 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) ) - 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", 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) + 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( @@ -374,37 +360,6 @@ 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): diff --git a/test/test_scripts.py b/test/test_scripts.py index 2d71d2eea..c1a6c082d 100644 --- a/test/test_scripts.py +++ b/test/test_scripts.py @@ -9,7 +9,6 @@ import sys import unittest from abc import ABCMeta, abstractmethod -from pathlib import Path from .config import * @@ -28,13 +27,11 @@ 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( - args, + command.split(), stderr=subprocess.STDOUT, encoding="utf-8", + shell=IS_WINDOWS, ) except subprocess.CalledProcessError as e: return_code = e.returncode @@ -60,12 +57,6 @@ 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 @@ -82,8 +73,8 @@ def _import(self): class TestLoggerScript(CanScriptTest): def _commands(self): commands = [ - [sys.executable, "-m", "can.logger", "--help"], - self._console_command("can_logger"), + "python -m can.logger --help", + "can_logger --help", ] return commands @@ -96,8 +87,8 @@ def _import(self): class TestPlayerScript(CanScriptTest): def _commands(self): commands = [ - [sys.executable, "-m", "can.player", "--help"], - self._console_command("can_player"), + "python -m can.player --help", + "can_player --help", ] return commands @@ -110,8 +101,8 @@ def _import(self): class TestBridgeScript(CanScriptTest): def _commands(self): commands = [ - [sys.executable, "-m", "can.bridge", "--help"], - self._console_command("can_bridge"), + "python -m can.bridge --help", + "can_bridge --help", ] return commands @@ -124,8 +115,8 @@ def _import(self): class TestLogconvertScript(CanScriptTest): def _commands(self): commands = [ - [sys.executable, "-m", "can.logconvert", "--help"], - self._console_command("can_logconvert"), + "python -m can.logconvert --help", + "can_logconvert --help", ] return commands From d8682809195b01bf4d1687e19f6f8a7ba473eccc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Waldh=C3=B6r?= Date: Thu, 26 Nov 2026 23:13:48 +0100 Subject: [PATCH 4/4] Fix formatting --- can/interfaces/pcan/pcan.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/can/interfaces/pcan/pcan.py b/can/interfaces/pcan/pcan.py index eff5b039d..8a605b9f9 100644 --- a/can/interfaces/pcan/pcan.py +++ b/can/interfaces/pcan/pcan.py @@ -90,17 +90,17 @@ # 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 + # 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