diff --git a/can/interfaces/pcan/pcan.py b/can/interfaces/pcan/pcan.py index 2bc2294e2..d31724295 100644 --- a/can/interfaces/pcan/pcan.py +++ b/can/interfaces/pcan/pcan.py @@ -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 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..613bb1bdb 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.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 @@ -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..2d71d2eea 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,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 @@ -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 @@ -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 @@ -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 @@ -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 @@ -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