diff --git a/can/bus.py b/can/bus.py index 72cd208ea..e126264aa 100644 --- a/can/bus.py +++ b/can/bus.py @@ -3,6 +3,7 @@ """ import contextlib +import inspect import logging import threading from abc import ABC, abstractmethod @@ -10,10 +11,11 @@ from enum import Enum, auto from time import time from types import TracebackType -from typing import Self, cast +from typing import Any, Self, cast import can.typechecking from can.broadcastmanager import CyclicSendTaskABC, ThreadBasedCyclicSendTask +from can.exceptions import CanInterfaceNotImplementedError from can.message import Message LOG = logging.getLogger(__name__) @@ -56,12 +58,23 @@ class BusABC(ABC): #: Assume that no cleanup is needed until something was initialized _is_shutdown: bool = True _can_protocol: CanProtocol = CanProtocol.CAN_20 + _listen_only: bool = False + + def __new__(cls, *args: Any, **kwargs: Any) -> Self: + # reject listen-only mode before the subclass opens any driver or device + if kwargs.get("listen_only") and not _accepts_listen_only(cls): + raise CanInterfaceNotImplementedError( + f"{cls.__name__} does not support listen-only mode" + ) + return super().__new__(cls) @abstractmethod def __init__( self, channel: can.typechecking.Channel, can_filters: can.typechecking.CanFilters | None = None, + *, + listen_only: bool | None = None, **kwargs: object, ): """Construct and open a CAN bus instance of the specified type. @@ -75,12 +88,24 @@ def __init__( :param can_filters: See :meth:`~can.BusABC.set_filters` for details. + :param listen_only: + If ``True``, open the bus in :ref:`listen-only mode `. + If ``False``, open the bus in normal mode. ``None`` (the default) + means that listen-only mode was not requested. + :class:`~can.exceptions.CanInterfaceNotImplementedError` is raised + if the interface does not support listen-only mode, and + :class:`~can.exceptions.CanInitializationError` if it cannot be + applied. :class:`~can.BusABC` does not apply the mode: a subclass that + supports listen-only mode must declare ``listen_only`` in its own + constructor and apply it. + :param dict kwargs: Any backend dependent configurations are passed in this dictionary :raises ValueError: If parameters are out of range :raises ~can.exceptions.CanInterfaceNotImplementedError: - If the driver cannot be accessed + If the driver cannot be accessed, or if ``listen_only`` is ``True`` + and the interface does not support listen-only mode :raises ~can.exceptions.CanInitializationError: If the bus cannot be initialized """ @@ -190,7 +215,8 @@ def send(self, msg: Message, timeout: float | None = None) -> None: None blocks indefinitely. :raises ~can.exceptions.CanOperationError: - If an error occurred while sending + If an error occurred while sending, or if the bus was opened + in :ref:`listen-only mode ` without local loopback """ raise NotImplementedError("Trying to write to a readonly bus?") @@ -510,6 +536,28 @@ def protocol(self) -> CanProtocol: """ return self._can_protocol + @property + def listen_only(self) -> bool: + """Whether this bus instance is in :ref:`listen-only mode `. + + Interfaces that do not support listen-only mode return ``False``. If the + bus was created with ``listen_only=None``, this property reports ``False``, + meaning that listen-only mode was not requested; the mode of the channel + is not read back from the driver. + + Interfaces that can switch the mode at runtime allow setting this + property to ``True`` or ``False``. + + :raises NotImplementedError: + When set, if the interface cannot switch listen-only mode at runtime. + """ + return self._listen_only + + @listen_only.setter + def listen_only(self, value: bool) -> None: + """Switch :ref:`listen-only mode ` on or off at runtime.""" + raise NotImplementedError("Property is not implemented.") + @staticmethod def _detect_available_configs() -> Sequence[can.typechecking.AutoDetectedConfig]: """Detect all configurations/channels that this interface could @@ -536,3 +584,38 @@ class _SelfRemovingCyclicTask(CyclicSendTaskABC, ABC): def stop(self, remove_task: bool = True) -> None: raise NotImplementedError() + + +def _accepts_listen_only(bus_class: type["BusABC"]) -> bool: + """Check whether a constructor of ``bus_class`` declares ``listen_only``. + + The constructors in the MRO are checked from the most derived one up to, + but excluding, :meth:`BusABC.__init__`. The first one that declares + ``listen_only`` explicitly means support. A constructor that takes + ``**kwargs`` may forward ``listen_only`` to its base class, so the search + continues there. A constructor that takes neither cannot receive + ``listen_only``. If a signature cannot be inspected, ``True`` is returned. + """ + for klass in bus_class.__mro__: + if klass is BusABC: + return False + init = klass.__dict__.get("__init__") + if init is None: + continue + try: + parameters = inspect.signature(init).parameters + except (TypeError, ValueError): + return True + parameter = parameters.get("listen_only") + if parameter is not None and parameter.kind in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + ): + return True + # without **kwargs, this constructor can neither receive nor forward + # listen_only, so base class constructors do not matter + if not any( + p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters.values() + ): + return False + return False diff --git a/can/cli.py b/can/cli.py index e15e7d153..f678628ba 100644 --- a/can/cli.py +++ b/can/cli.py @@ -12,6 +12,7 @@ def add_bus_arguments( parser: argparse.ArgumentParser, *, filter_arg: bool = False, + listen_only_arg: bool = False, prefix: str | None = None, group_title: str | None = None, ) -> None: @@ -21,6 +22,8 @@ def add_bus_arguments( The argument parser to which the options will be added. :param filter_arg: Whether to include the filter argument. + :param listen_only_arg: + Whether to include the ``--listen-only``/``--no-listen-only`` argument. :param prefix: An optional prefix for the argument names, allowing configuration of multiple buses. :param group_title: @@ -78,6 +81,20 @@ def add_bus_arguments( help="Activate CAN-FD support", ) + if listen_only_arg: + flags = [f"--{prefix}-listen-only"] if prefix else ["--listen-only"] + dest = f"{prefix}_listen_only" if prefix else "listen_only" + group.add_argument( + *flags, + dest=dest, + default=argparse.SUPPRESS, + action=argparse.BooleanOptionalAction, + help="Open the bus in listen-only mode: receive only, never transmit " + "frames, acknowledgements or error frames. " + f"--no-{flags[0][2:]} opens the bus in normal mode, overriding a " + "listen-only mode set in the configuration.", + ) + flags = [f"--{prefix}-data-bitrate"] if prefix else ["--data-bitrate"] dest = f"{prefix}_data_bitrate" if prefix else "data_bitrate" group.add_argument( @@ -165,6 +182,7 @@ def create_bus_from_namespace( "interface", "bitrate", "fd", + "listen_only", "data_bitrate", "can_filters", "timing", diff --git a/can/interface.py b/can/interface.py index 69112fa4d..afcc4cbc3 100644 --- a/can/interface.py +++ b/can/interface.py @@ -11,7 +11,7 @@ from typing import Any, cast from . import util -from .bus import BusABC +from .bus import BusABC, _accepts_listen_only from .exceptions import CanInterfaceNotImplementedError from .interfaces import BACKENDS from .typechecking import AutoDetectedConfig, Channel @@ -68,6 +68,7 @@ def Bus( # noqa: N802 interface: str | None = None, config_context: str | None = None, ignore_config: bool = False, + listen_only: bool | None = None, **kwargs: Any, ) -> BusABC: """Create a new bus instance with configuration loading. @@ -100,11 +101,19 @@ def Bus( # noqa: N802 If ``True``, only the given arguments will be used for the bus instantiation. Existing configuration sources will be ignored. + :param listen_only: + If ``True``, open the bus in :ref:`listen-only mode `. + Set to ``None`` to let it be resolved from the default + :ref:`configuration`; if the configuration does not set it either, + listen-only mode is not requested. + ``listen_only=False`` is accepted by every interface. + :param kwargs: ``interface`` specific keyword arguments. :raises ~can.exceptions.CanInterfaceNotImplementedError: - if the ``interface`` isn't recognized or cannot be loaded + if the ``interface`` isn't recognized or cannot be loaded, + or if it does not support listen-only mode and ``listen_only`` is ``True`` :raises ~can.exceptions.CanInitializationError: if the bus cannot be instantiated @@ -118,6 +127,8 @@ def Bus( # noqa: N802 kwargs["interface"] = interface if channel is not None: kwargs["channel"] = channel + if listen_only is not None: + kwargs["listen_only"] = listen_only if not ignore_config: kwargs = util.load_config(config=kwargs, context=config_context) @@ -125,6 +136,11 @@ def Bus( # noqa: N802 # resolve the bus class to use for that interface cls = _get_class_for_interface(kwargs["interface"]) + # drop listen_only=False for interfaces that cannot take the argument, + # so that they keep working + if not kwargs.get("listen_only", True) and not _accepts_listen_only(cls): + del kwargs["listen_only"] + # remove the "interface" key, so it doesn't get passed to the backend del kwargs["interface"] diff --git a/can/interfaces/canalystii.py b/can/interfaces/canalystii.py index e2bf7555e..ca9072c67 100644 --- a/can/interfaces/canalystii.py +++ b/can/interfaces/canalystii.py @@ -27,7 +27,7 @@ def __init__( timing: BitTiming | BitTimingFd | None = None, can_filters: CanFilters | None = None, rx_queue_size: int | None = None, - **kwargs: dict[str, Any], + **kwargs: Any, ): """ diff --git a/can/interfaces/cantact.py b/can/interfaces/cantact.py index 7b11df614..9e28cb8c5 100644 --- a/can/interfaces/cantact.py +++ b/can/interfaces/cantact.py @@ -12,10 +12,15 @@ from can.exceptions import ( CanInitializationError, CanInterfaceNotImplementedError, + CanOperationError, error_check, ) from can.typechecking import AutoDetectedConfig -from can.util import check_or_adjust_timing_clock, deprecated_args_alias +from can.util import ( + _warn_listen_only_deprecated, + check_or_adjust_timing_clock, + deprecated_args_alias, +) logger = logging.getLogger(__name__) @@ -54,8 +59,9 @@ def __init__( channel: int, bitrate: int = 500_000, poll_interval: float = 0.01, - monitor: bool = False, + monitor: bool | None = None, timing: BitTiming | BitTimingFd | None = None, + listen_only: bool | None = None, **kwargs: Any, ) -> None: """ @@ -63,15 +69,33 @@ def __init__( Channel number (zero indexed, labeled on multi-channel devices) :param int bitrate: Bitrate in bits/s - :param bool monitor: - If true, operate in listen-only monitoring mode + :param monitor: + If true, operate in listen-only monitoring mode. + If ``listen_only`` is also given with a contradicting value, + :class:`ValueError` is raised. + + .. deprecated:: 4.7.0 + Use ``listen_only`` instead. :param timing: Optional :class:`~can.BitTiming` instance to use for custom bit timing setting. If this argument is set then it overrides the bitrate argument. The `f_clock` value of the timing instance must be set to 24_000_000 (24MHz) for standard CAN. CAN FD and the :class:`~can.BitTimingFd` class are not supported. + :param listen_only: + If true, operate in listen-only monitoring mode. In this mode, + :meth:`send` raises :class:`~can.exceptions.CanOperationError`. + If ``None`` (the default), the monitor mode of the device is left + unchanged. """ + if monitor is not None: + _warn_listen_only_deprecated("The 'monitor' argument", "'listen_only'") + if listen_only is not None and listen_only != bool(monitor): + raise ValueError( + f"monitor={monitor!r} contradicts listen_only={listen_only!r}" + ) + listen_only = bool(monitor) + self._listen_only = bool(listen_only) if kwargs.get("_testing", False): self.interface = MockInterface() @@ -112,7 +136,8 @@ def __init__( self.interface.set_bitrate(int(channel), int(bitrate)) self.interface.set_enabled(int(channel), True) - self.interface.set_monitor(int(channel), monitor) + if listen_only is not None: + self.interface.set_monitor(int(channel), listen_only) self.interface.start() super().__init__( @@ -145,6 +170,8 @@ def _recv_internal(self, timeout: float | None) -> tuple[Message | None, bool]: return msg, False def send(self, msg: Message, timeout: float | None = None) -> None: + if self._listen_only: + raise CanOperationError("Cannot send in listen-only mode") with error_check("Cannot send message"): self.interface.send( self.channel, diff --git a/can/interfaces/kvaser/canlib.py b/can/interfaces/kvaser/canlib.py index 94fbab7ef..61c7dbd90 100644 --- a/can/interfaces/kvaser/canlib.py +++ b/can/interfaces/kvaser/canlib.py @@ -14,7 +14,11 @@ from can import BitTiming, BitTimingFd, BusABC, CanProtocol, Message from can.exceptions import CanError, CanInitializationError, CanOperationError from can.typechecking import CanFilters -from can.util import check_or_adjust_timing_clock, time_perfcounter_correlation +from can.util import ( + _warn_listen_only_deprecated, + check_or_adjust_timing_clock, + time_perfcounter_correlation, +) from . import constants as canstat from . import structures @@ -230,6 +234,13 @@ def __check_bus_handle_validity(handle, function, arguments): errcheck=__check_status_initialization, ) + canGetBusOutputControl = __get_canlib_function( + "canGetBusOutputControl", + argtypes=[c_canHandle, ctypes.POINTER(ctypes.c_uint)], + restype=canstat.c_canStatus, + errcheck=__check_status_initialization, + ) + canSetAcceptanceFilter = __get_canlib_function( "canSetAcceptanceFilter", argtypes=[c_canHandle, ctypes.c_uint, ctypes.c_uint, ctypes.c_int], @@ -376,6 +387,7 @@ def __init__( channel: int, can_filters: CanFilters | None = None, timing: BitTiming | BitTimingFd | None = None, + listen_only: bool | None = None, **kwargs, ): """ @@ -416,6 +428,19 @@ def __init__( :param bool driver_mode: Silent or normal. + If ``listen_only`` is also given with a contradicting value, + :class:`ValueError` is raised. + + .. deprecated:: 4.7.0 + Use ``listen_only`` instead. + :param listen_only: + If True, open the channel in silent mode. In silent mode, + :meth:`send` raises :class:`~can.exceptions.CanOperationError`. + If False, open the channel in normal mode. If None (the default), + the driver mode of the channel is left unchanged. A channel without + init access is accepted only if it already is in the requested + mode; otherwise :class:`~can.exceptions.CanInitializationError` is + raised, for ``listen_only=False`` as well. :param bool single_handle: Use one Kvaser CANLIB bus handle for both reading and writing. @@ -449,7 +474,16 @@ def __init__( tseg2 = kwargs.get("tseg2", 0) sjw = kwargs.get("sjw", 0) no_samp = kwargs.get("no_samp", 0) - driver_mode = kwargs.get("driver_mode", DRIVER_MODE_NORMAL) + if "driver_mode" in kwargs: + _warn_listen_only_deprecated("The 'driver_mode' argument", "'listen_only'") + silent = kwargs["driver_mode"] == DRIVER_MODE_SILENT + if listen_only is not None and listen_only != silent: + raise ValueError( + f"driver_mode={kwargs['driver_mode']!r} contradicts " + f"listen_only={listen_only!r}" + ) + listen_only = silent + self._listen_only = bool(listen_only) single_handle = kwargs.get("single_handle", False) receive_own_messages = kwargs.get("receive_own_messages", False) exclusive = kwargs.get("exclusive", False) @@ -578,12 +612,23 @@ def __init__( flags_ = flags self._write_handle = canOpenChannel(channel, flags_) - can_driver_mode = ( - canstat.canDRIVER_SILENT - if driver_mode == DRIVER_MODE_SILENT - else canstat.canDRIVER_NORMAL - ) - canSetBusOutputControl(self._write_handle, can_driver_mode) + if listen_only is not None: + can_driver_mode = ( + canstat.canDRIVER_SILENT if listen_only else canstat.canDRIVER_NORMAL + ) + # the driver mode requires init access, which only the read handle + # can hold; without init access, the call has no effect + canSetBusOutputControl(self._read_handle, can_driver_mode) + # accept a channel without init access if it already is in the + # requested mode, e.g. because another application set it + driver_type = ctypes.c_uint(0) + canGetBusOutputControl(self._read_handle, ctypes.byref(driver_type)) + if bool(driver_type.value & canstat.canDRIVER_SILENT) != listen_only: + mode = "silent" if listen_only else "normal" + raise CanInitializationError( + f"Cannot set {mode} mode on channel {channel}, " + f"probably because the channel was opened without init access" + ) self._is_filtered = False super().__init__( @@ -708,6 +753,8 @@ def _recv_internal(self, timeout=None): return None, self._is_filtered def send(self, msg, timeout=None): + if self._listen_only: + raise CanOperationError("Cannot send in listen-only mode") # log.debug("Writing a message: {}".format(msg)) flags = canstat.canMSG_EXT if msg.is_extended_id else canstat.canMSG_STD if msg.is_remote_frame: diff --git a/can/interfaces/nixnet.py b/can/interfaces/nixnet.py index 24157d032..252cc3ed4 100644 --- a/can/interfaces/nixnet.py +++ b/can/interfaces/nixnet.py @@ -59,6 +59,7 @@ def __init__( fd: bool = False, fd_bitrate: int | None = None, poll_interval: float = 0.001, + listen_only: bool | None = None, **kwargs: Any, ) -> None: """ @@ -84,6 +85,12 @@ def __init__( :param poll_interval: Poll interval in seconds. + :param listen_only: + If True, open the interface in listen-only mode. In listen-only + mode, :meth:`send` raises :class:`~can.exceptions.CanOperationError`. + If None (the default), the listen-only mode of the interface is left + unchanged. + :raises ~can.exceptions.CanInitializationError: If starting communication fails """ @@ -103,6 +110,7 @@ def __init__( self.channel_info = "NI-XNET: " + channel self.poll_interval = poll_interval + self._listen_only = bool(listen_only) is_fd = isinstance(timing, BitTimingFd) if timing else fd self._can_protocol = CanProtocol.CAN_FD if is_fd else CanProtocol.CAN_20 @@ -122,7 +130,8 @@ def __init__( self._interface = self._session_send.intf # set interface properties - self._interface.can_lstn_only = kwargs.get("listen_only", False) + if listen_only is not None: + self._interface.can_lstn_only = bool(listen_only) self._interface.echo_tx = receive_own_messages self._interface.bus_err_to_in_strm = True @@ -267,7 +276,10 @@ def send(self, msg: Message, timeout: float | None = None) -> None: :raises can.exceptions.CanOperationError: If writing to transmit buffer fails. It does not wait for message to be ACKed currently. + Also raised if the bus was opened in listen-only mode. """ + if self._listen_only: + raise CanOperationError("Cannot send in listen-only mode") if timeout is None: timeout = self.nixnet.constants.TIMEOUT_INFINITE diff --git a/can/interfaces/pcan/pcan.py b/can/interfaces/pcan/pcan.py index aad4a1fcc..b93d56f9a 100644 --- a/can/interfaces/pcan/pcan.py +++ b/can/interfaces/pcan/pcan.py @@ -21,7 +21,12 @@ CanProtocol, Message, ) -from can.util import check_or_adjust_timing_clock, dlc2len, len2dlc +from can.util import ( + _warn_listen_only_deprecated, + check_or_adjust_timing_clock, + dlc2len, + len2dlc, +) from .basic import ( FEATURE_FD_CAPABLE, @@ -138,10 +143,11 @@ def __init__( self, channel: str = "PCAN_USBBUS1", device_id: int | None = None, - state: BusState = BusState.ACTIVE, + state: BusState | None = None, timing: BitTiming | BitTimingFd | None = None, bitrate: int = 500000, receive_own_messages: bool = False, + listen_only: bool | None = None, **kwargs: Any, ): """A PCAN USB interface to CAN. @@ -163,9 +169,13 @@ def __init__( first one that matches the parameter value. If no device is found, an exception is raised. - :param can.bus.BusState state: + :param state: BusState of the channel. - Default is ACTIVE + If ``listen_only`` is also given with a contradicting value, + :class:`ValueError` is raised. + + .. deprecated:: 4.7.0 + Use ``listen_only`` instead. :param timing: An instance of :class:`~can.BitTiming` or :class:`~can.BitTimingFd` @@ -187,6 +197,16 @@ def __init__( :param receive_own_messages: Enable self-reception of sent messages. + :param listen_only: + Open the channel in listen-only mode. In listen-only mode, + :attr:`state` is ``BusState.PASSIVE`` and :meth:`send` raises + :class:`~can.exceptions.CanOperationError`. The mode can be switched + at runtime with :attr:`listen_only`. If ``None`` (the default), the + listen-only mode of the channel is left unchanged. If listen-only + mode cannot be set, :class:`~can.exceptions.CanInitializationError` + is raised; if it cannot be switched off, e.g. on PCAN-LAN devices, + the channel opens anyway and a warning is logged. + :param bool fd: Should the Bus be initialized in CAN-FD mode. @@ -285,10 +305,24 @@ def __init__( self.check_api_version() - if state in [BusState.ACTIVE, BusState.PASSIVE]: - self.state = state - else: - raise ValueError("BusState must be Active or Passive") + if state is not None: + _warn_listen_only_deprecated("The 'state' argument", "'listen_only'") + if state not in [BusState.ACTIVE, BusState.PASSIVE]: + raise ValueError("BusState must be Active or Passive") + passive = state is BusState.PASSIVE + if listen_only is not None and listen_only != passive: + raise ValueError( + f"state={state} contradicts listen_only={listen_only!r}" + ) + listen_only = passive + if listen_only is not None: + try: + self._set_listen_only_mode(listen_only, PcanCanInitializationError) + except PcanCanInitializationError as error: + if listen_only: + raise + # e.g. PCAN-LAN devices cannot set PCAN_LISTEN_ONLY + log.warning("Cannot switch off listen-only mode: %s", error) if isinstance(timing, BitTiming): timing = check_or_adjust_timing_clock(timing, VALID_PCAN_CAN_CLOCKS) @@ -373,7 +407,6 @@ def __init__( super().__init__( channel=channel, - state=state, bitrate=bitrate, **kwargs, ) @@ -624,6 +657,8 @@ def _recv_internal(self, timeout: float | None) -> tuple[Message | None, bool]: return rx_msg, False def send(self, msg, timeout=None): + if self._listen_only: + raise CanOperationError("Cannot send in listen-only mode") msgType = ( PCAN_MESSAGE_EXTENDED.value if msg.is_extended_id @@ -708,27 +743,44 @@ def fd(self) -> bool: ) return self._can_protocol is CanProtocol.CAN_FD + @property + def listen_only(self) -> bool: + return self._listen_only + + @listen_only.setter + def listen_only(self, value: bool) -> None: + self._set_listen_only_mode(bool(value), PcanCanOperationError) + @property def state(self): - return self._state + """Return the current state of the channel. + + .. deprecated:: 4.7.0 + Setting the state to switch listen-only mode is deprecated. + Use :attr:`listen_only` instead. + """ + return BusState.PASSIVE if self._listen_only else BusState.ACTIVE @state.setter def state(self, new_state): - # declare here, which is called by __init__() - self._state = new_state # pylint: disable=attribute-defined-outside-init - - if new_state is BusState.ACTIVE: - self.m_objPCANBasic.SetValue( - self.m_PcanHandle, PCAN_LISTEN_ONLY, PCAN_PARAMETER_OFF - ) - - elif new_state is BusState.PASSIVE: - # When this mode is set, the CAN controller does not take part on active events (eg. transmit CAN messages) - # but stays in a passive mode (CAN monitor), in which it can analyse the traffic on the CAN bus used by a - # PCAN channel. See also the Philips Data Sheet "SJA1000 Stand-alone CAN controller". - self.m_objPCANBasic.SetValue( - self.m_PcanHandle, PCAN_LISTEN_ONLY, PCAN_PARAMETER_ON - ) + _warn_listen_only_deprecated("Setting 'bus.state'", "'bus.listen_only'") + if new_state is BusState.ACTIVE or new_state is BusState.PASSIVE: + self.listen_only = new_state is BusState.PASSIVE + + def _set_listen_only_mode( + self, listen_only: bool, error_class: type["PcanError"] + ) -> None: + # When this mode is set, the CAN controller does not take part on active events (eg. transmit CAN messages) + # but stays in a passive mode (CAN monitor), in which it can analyse the traffic on the CAN bus used by a + # PCAN channel. See also the Philips Data Sheet "SJA1000 Stand-alone CAN controller". + result = self.m_objPCANBasic.SetValue( + self.m_PcanHandle, + PCAN_LISTEN_ONLY, + PCAN_PARAMETER_ON if listen_only else PCAN_PARAMETER_OFF, + ) + if result != PCAN_ERROR_OK: + raise error_class(self._get_formatted_error(result)) + self._listen_only = listen_only @staticmethod def _detect_available_configs(): diff --git a/can/interfaces/seeedstudio/seeedstudio.py b/can/interfaces/seeedstudio/seeedstudio.py index b7b0e46ab..334b7eb93 100644 --- a/can/interfaces/seeedstudio/seeedstudio.py +++ b/can/interfaces/seeedstudio/seeedstudio.py @@ -10,9 +10,12 @@ import logging import struct from time import time +from typing import Any import can from can import BusABC, CanProtocol, Message +from can.typechecking import CanFilters +from can.util import _warn_listen_only_deprecated logger = logging.getLogger("seeedbus") @@ -57,15 +60,16 @@ class SeeedBus(BusABC): def __init__( self, - channel, - baudrate=2000000, - timeout=0.1, - frame_type="STD", - operation_mode="normal", - bitrate=500000, - can_filters=None, - **kwargs, - ): + channel: str, + baudrate: int = 2000000, + timeout: float = 0.1, + frame_type: str = "STD", + operation_mode: str = "normal", + bitrate: int = 500000, + can_filters: CanFilters | None = None, + listen_only: bool | None = None, + **kwargs: Any, + ) -> None: """ :param str channel: The serial device to open. For example "/dev/ttyS1" or @@ -81,7 +85,14 @@ def __init__( STD or EXT, to select standard or extended messages :param operation_mode - normal, loopback, silent or loopback_and_silent. + normal or loopback. With ``listen_only``, loopback selects the + device's loopback and silent mode. + + .. deprecated:: 4.7.0 + The ``"silent"`` and ``"loopback_and_silent"`` modes are + deprecated. Use ``listen_only=True`` instead, combined with + ``"loopback"`` for ``"loopback_and_silent"``. With + ``listen_only=False``, these modes raise :class:`ValueError`. :param bitrate CAN bus bit rate, selected from available list. @@ -92,6 +103,15 @@ def __init__( zero or more than one filter is provided, software-based filtering will be used. Defaults to None (no filtering). + :param listen_only: + If True, open the device in silent mode. In silent mode, + :meth:`send` raises :class:`~can.exceptions.CanOperationError`, + unless ``operation_mode`` is loopback: then sent messages are not + put on the bus, but only looped back by the device. If False or + None (the default), the device opens in normal mode. + + :raises ValueError: + If ``operation_mode`` is invalid or contradicts ``listen_only``. :raises can.CanInitializationError: If the given parameters are invalid. :raises can.CanInterfaceNotImplementedError: If the serial module is not installed. """ @@ -113,7 +133,32 @@ def __init__( self.bit_rate = bitrate self.frame_type = frame_type + if operation_mode not in self.OPERATIONMODE: + raise ValueError(f"Invalid operation_mode {operation_mode!r}") + if operation_mode in ("silent", "loopback_and_silent"): + loopback = operation_mode == "loopback_and_silent" + _warn_listen_only_deprecated( + f"The operation_mode '{operation_mode}'", + ( + "'listen_only=True' with operation_mode 'loopback'" + if loopback + else "'listen_only=True'" + ), + ) + if listen_only is not None and not listen_only: + raise ValueError( + f"operation_mode {operation_mode!r} contradicts listen_only=False" + ) + listen_only = True + operation_mode = "loopback" if loopback else "normal" + if listen_only: + operation_mode = ( + "loopback_and_silent" if operation_mode == "loopback" else "silent" + ) + self._listen_only = bool(listen_only) self.op_mode = operation_mode + # in listen-only mode, sending is only possible with loopback + self._send_blocked = operation_mode == "silent" self.filter_id = struct.pack(" None: @@ -109,7 +109,9 @@ def __init__( turn hardware handshake (RTS/CTS) on and off :param listen_only: If True, open interface/channel in listen mode with ``L`` command. - Otherwise, the (default) ``O`` command is still used. See ``open`` method. + Otherwise, including ``None`` (the default), the ``O`` command is used + and the channel opens in normal mode. See ``open`` method. + In listen mode, :meth:`send` raises :class:`~can.exceptions.CanOperationError`. :param timeout: Timeout for the serial or usb device in seconds (default 0.001) @@ -117,7 +119,7 @@ def __init__( :raise CanInterfaceNotImplementedError: if the serial module is missing :raise CanInitializationError: if the underlying serial connection could not be established """ - self._listen_only = listen_only + self._listen_only = bool(listen_only) if serial is None: raise CanInterfaceNotImplementedError("The serial module is not installed") @@ -351,6 +353,8 @@ def _recv_internal(self, timeout: float | None) -> tuple[Message | None, bool]: return None, False def send(self, msg: Message, timeout: float | None = None) -> None: + if self._listen_only: + raise CanOperationError("Cannot send in listen-only mode") if timeout != self.serialPortOrig.write_timeout: self.serialPortOrig.write_timeout = timeout if msg.is_remote_frame: diff --git a/can/interfaces/systec/ucanbus.py b/can/interfaces/systec/ucanbus.py index f5558b5fe..c7806c3ad 100644 --- a/can/interfaces/systec/ucanbus.py +++ b/can/interfaces/systec/ucanbus.py @@ -1,5 +1,6 @@ import logging from threading import Event +from typing import Any from can import ( BusABC, @@ -10,6 +11,8 @@ CanProtocol, Message, ) +from can.typechecking import CanFilters +from can.util import _warn_listen_only_deprecated from .constants import * from .exceptions import UcanException @@ -57,7 +60,13 @@ class UcanBus(BusABC): 1000000: Baudrate.BAUD_1MBit, } - def __init__(self, channel, can_filters=None, **kwargs): + def __init__( + self, + channel: int, + can_filters: CanFilters | None = None, + listen_only: bool | None = None, + **kwargs: Any, + ) -> None: """ :param int channel: The Channel id to create this bus with. @@ -65,6 +74,13 @@ def __init__(self, channel, can_filters=None, **kwargs): :param list can_filters: See :meth:`can.BusABC.set_filters`. + :param listen_only: + Open the channel in listen-only mode. In listen-only mode, + :attr:`state` is ``BusState.PASSIVE`` and :meth:`send` raises + :class:`~can.exceptions.CanOperationError`. The mode can be switched + at runtime with :attr:`listen_only`. If False or None (the default), + the channel opens in normal mode. + Backend Configuration :param int bitrate: @@ -79,7 +95,11 @@ def __init__(self, channel, can_filters=None, **kwargs): :param can.bus.BusState state: BusState of the channel. - Default is ACTIVE. + If ``listen_only`` is also given with a contradicting value, + :class:`ValueError` is raised. + + .. deprecated:: 4.7.0 + Use ``listen_only`` instead. :param bool receive_own_messages: If messages transmitted should also be received back. @@ -121,17 +141,24 @@ def __init__(self, channel, can_filters=None, **kwargs): if bitrate not in self.BITRATES: raise ValueError(f"Invalid bitrate {bitrate}") - state = kwargs.get("state", BusState.ACTIVE) - if state is BusState.ACTIVE or state is BusState.PASSIVE: - self._state = state - else: - raise ValueError("BusState must be Active or Passive") + state = kwargs.get("state") + if state is not None: + _warn_listen_only_deprecated("The 'state' argument", "'listen_only'") + if state is not BusState.ACTIVE and state is not BusState.PASSIVE: + raise ValueError("BusState must be Active or Passive") + passive = state is BusState.PASSIVE + if listen_only is not None and listen_only != passive: + raise ValueError( + f"state={state} contradicts listen_only={listen_only!r}" + ) + listen_only = passive + self._listen_only = bool(listen_only) # get parameters self._params = { "mode": Mode.MODE_NORMAL | (Mode.MODE_TX_ECHO if kwargs.get("receive_own_messages") else 0) - | (Mode.MODE_LISTEN_ONLY if state is BusState.PASSIVE else 0), + | (Mode.MODE_LISTEN_ONLY if self._listen_only else 0), "BTR": self.BITRATES[bitrate], } # get extra parameters @@ -196,8 +223,11 @@ def send(self, msg, timeout=None): Transmit timeout in seconds (value 0 switches off the "auto delete") :raises ~can.exceptions.CanOperationError: - If the message could not be sent. + If the message could not be sent, or if the channel is in + listen-only mode. """ + if self._listen_only: + raise CanOperationError("Cannot send in listen-only mode") try: if timeout is not None and timeout >= 0: self._ucan.set_tx_timeout(self.channel, int(timeout * 1000)) @@ -301,27 +331,41 @@ def create_filter(extended, from_id, to_id, rtr_only, rtr_too): } ] + @property + def listen_only(self) -> bool: + return self._listen_only + + @listen_only.setter + def listen_only(self, value: bool) -> None: + try: + # close the CAN channel + self._ucan.shutdown(self.channel, False) + # set mode + if value: + self._params["mode"] |= Mode.MODE_LISTEN_ONLY + else: + self._params["mode"] &= ~Mode.MODE_LISTEN_ONLY + # reinitialize CAN channel + self._ucan.init_can(self.channel, **self._params) + except UcanException as exception: + raise CanOperationError() from exception + self._listen_only = value + @property def state(self): - return self._state + """Return the current state of the channel. + + .. deprecated:: 4.7.0 + Setting the state to switch listen-only mode is deprecated. + Use :attr:`listen_only` instead. + """ + return BusState.PASSIVE if self._listen_only else BusState.ACTIVE @state.setter def state(self, new_state): - if self._state is not BusState.ERROR and ( - new_state is BusState.ACTIVE or new_state is BusState.PASSIVE - ): - try: - # close the CAN channel - self._ucan.shutdown(self.channel, False) - # set mode - if new_state is BusState.ACTIVE: - self._params["mode"] &= ~Mode.MODE_LISTEN_ONLY - else: - self._params["mode"] |= Mode.MODE_LISTEN_ONLY - # reinitialize CAN channel - self._ucan.init_can(self.channel, **self._params) - except UcanException as exception: - raise CanOperationError() from exception + _warn_listen_only_deprecated("Setting 'bus.state'", "'bus.listen_only'") + if new_state is BusState.ACTIVE or new_state is BusState.PASSIVE: + self.listen_only = new_state is BusState.PASSIVE def shutdown(self): """ diff --git a/can/interfaces/vector/canlib.py b/can/interfaces/vector/canlib.py index 799b5ac8e..5f5c39f5d 100644 --- a/can/interfaces/vector/canlib.py +++ b/can/interfaces/vector/canlib.py @@ -24,6 +24,7 @@ BusABC, CanInitializationError, CanInterfaceNotImplementedError, + CanOperationError, CanProtocol, Message, ) @@ -95,7 +96,7 @@ def __init__( sjw_dbr: int = 2, tseg1_dbr: int = 6, tseg2_dbr: int = 3, - listen_only: bool | None = False, + listen_only: bool | None = None, **kwargs: Any, ) -> None: """ @@ -150,7 +151,17 @@ def __init__( :param tseg2_dbr: Bus timing value tseg2 (data) :param listen_only: - if the bus should be set to listen only mode. + if the bus should be set to listen-only (silent) mode. In listen-only + mode, :meth:`send` raises :class:`~can.exceptions.CanOperationError`, + unless ``receive_own_messages`` is set: then a sent frame is + received back as the bus's own message and is not put on the bus. + If False, init access is requested and the channels are set to + normal mode, so other applications cannot change the channel + settings while the bus is open. If None (the default), the output + mode of the channels is left unchanged. A channel without init + access is accepted only if it already is in the requested mode; + otherwise :class:`~can.exceptions.CanInitializationError` is + raised, for ``listen_only=False`` as well. :raise ~can.exceptions.CanInterfaceNotImplementedError: If the current operating system is not supported or the driver could not be loaded. @@ -199,7 +210,10 @@ def __init__( self.index_to_channel: dict[int, int] = {} self._can_protocol = CanProtocol.CAN_FD if is_fd else CanProtocol.CAN_20 - self._listen_only = listen_only + self._listen_only = bool(listen_only) + # with receive_own_messages, frames are still passed to the driver + # in listen-only mode, as before 4.7.0 + self._send_blocked = self._listen_only and not receive_own_messages for channel in self.channels: if ( @@ -228,7 +242,7 @@ def __init__( permission_mask = xlclass.XLaccess() # Set mask to request channel init permission if needed - if bitrate or fd or timing or self._listen_only: + if bitrate or fd or timing or listen_only is not None: permission_mask.value = self.mask interface_version = ( @@ -307,8 +321,8 @@ def __init__( if assert_timing: self._check_can_settings(channel_mask=self.mask, bitrate=bitrate) - if self._listen_only: - self._set_output_mode(channel_mask=self.mask, listen_only=True) + if listen_only is not None: + self._set_output_mode(channel_mask=self.mask, listen_only=self._listen_only) # Enable/disable TX receipts tx_receipts = 1 if receive_own_messages else 0 @@ -446,26 +460,28 @@ def _read_bus_params( ) def _set_output_mode(self, channel_mask: int, listen_only: bool) -> None: - # set parameters for channels with init access - channel_mask = channel_mask & self.permission_mask - - if channel_mask: - if listen_only: - self.xldriver.xlCanSetChannelOutput( - self.port_handle, - channel_mask, - xldefine.XL_OutputMode.XL_OUTPUT_MODE_SILENT, - ) - else: - self.xldriver.xlCanSetChannelOutput( - self.port_handle, - channel_mask, - xldefine.XL_OutputMode.XL_OUTPUT_MODE_NORMAL, - ) + mode = ( + xldefine.XL_OutputMode.XL_OUTPUT_MODE_SILENT + if listen_only + else xldefine.XL_OutputMode.XL_OUTPUT_MODE_NORMAL + ) + # without init access, accept only channels already in the requested mode + if no_init_access := channel_mask & ~self.permission_mask: + vcc_list = get_channel_configs() + for channel_index in _iterate_channel_index(no_init_access): + bus_params = self._read_bus_params(channel_index, vcc_list) + if bus_params.can.output_mode != mode: + channel = self.index_to_channel[channel_index] + raise CanInitializationError( + f"Cannot set {mode.name} on channel {channel} without " + f"init access, the channel is in " + f"{bus_params.can.output_mode.name}" + ) + # set parameters for channels with init access + if channel_mask := channel_mask & self.permission_mask: + self.xldriver.xlCanSetChannelOutput(self.port_handle, channel_mask, mode) LOG.info("xlCanSetChannelOutput: listen_only=%u", listen_only) - else: - LOG.warning("No channels with init access to set listen only mode") def _set_bitrate(self, channel_mask: int, bitrate: int) -> None: # set parameters for channels with init access @@ -836,6 +852,8 @@ def handle_canfd_event(self, event: xlclass.XLcanRxEvent) -> None: """ def send(self, msg: Message, timeout: float | None = None) -> None: + if self._send_blocked: + raise CanOperationError("Cannot send in listen-only mode") self._send_sequence([msg]) def _send_sequence(self, msgs: Sequence[Message]) -> int: diff --git a/can/interfaces/virtual.py b/can/interfaces/virtual.py index ba33a6ea8..093c3f0f4 100644 --- a/can/interfaces/virtual.py +++ b/can/interfaces/virtual.py @@ -58,6 +58,7 @@ def __init__( rx_queue_size: int = 0, preserve_timestamps: bool = False, protocol: CanProtocol = CanProtocol.CAN_20, + listen_only: bool | None = None, **kwargs: Any, ) -> None: """ @@ -84,6 +85,9 @@ def __init__( :param protocol: The protocol implemented by this bus instance. The value does not affect the operation of the bus instance and can be set to an arbitrary value for testing purposes. + :param listen_only: If set to True, the bus instance only receives + messages and :meth:`send` raises + :class:`~can.exceptions.CanOperationError`. :param kwargs: Additional keyword arguments passed to the parent constructor. """ @@ -99,6 +103,7 @@ def __init__( self.channel_info = f"Virtual bus channel {self.channel_id}" self.receive_own_messages = receive_own_messages self.preserve_timestamps = preserve_timestamps + self._listen_only = bool(listen_only) self._open = True with channels_lock: @@ -129,6 +134,8 @@ def _recv_internal(self, timeout: float | None) -> tuple[Message | None, bool]: def send(self, msg: Message, timeout: float | None = None) -> None: self._check_if_open() + if self._listen_only: + raise CanOperationError("Cannot send in listen-only mode") timestamp = msg.timestamp if self.preserve_timestamps else time.time() # Add message to all listening on this channel diff --git a/can/logger.py b/can/logger.py index 198480d40..d6a9f61de 100644 --- a/can/logger.py +++ b/can/logger.py @@ -2,9 +2,9 @@ import errno import sys from datetime import UTC, datetime -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any -from can import BusState, Logger, SizedRotatingLogger +from can import Logger, SizedRotatingLogger from can.cli import ( _add_extra_args, _parse_additional_config, @@ -13,6 +13,7 @@ create_bus_from_namespace, ) from can.typechecking import TAdditionalCliArgs +from can.util import _warn_listen_only_deprecated if TYPE_CHECKING: from can.io import BaseRotatingLogger @@ -69,20 +70,15 @@ def _parse_logger_args( ) state_group = logger_group.add_mutually_exclusive_group(required=False) - state_group.add_argument( - "--active", - help="Start the bus as active, this is applied by default.", - action="store_true", - ) - state_group.add_argument( - "--passive", help="Start the bus as passive.", action="store_true" - ) + # deprecated, hidden from the help output + state_group.add_argument("--active", help=argparse.SUPPRESS, action="store_true") + state_group.add_argument("--passive", help=argparse.SUPPRESS, action="store_true") # handle remaining arguments _add_extra_args(logger_group) # add bus options - add_bus_arguments(parser, filter_arg=True) + add_bus_arguments(parser, filter_arg=True, listen_only_arg=True) # print help message when no arguments were given if not args: @@ -90,19 +86,27 @@ def _parse_logger_args( raise SystemExit(errno.EINVAL) results, unknown_args = parser.parse_known_args(args) + listen_only = getattr(results, "listen_only", None) + if results.active and listen_only: + parser.error("argument --active: not allowed with argument --listen-only") + if results.passive and listen_only is False: + parser.error("argument --passive: not allowed with argument --no-listen-only") additional_config = _parse_additional_config([*results.extra_args, *unknown_args]) return results, additional_config def main() -> None: results, additional_config = _parse_logger_args(sys.argv[1:]) - bus = create_bus_from_namespace(results) - _set_logging_level_from_namespace(results) - + bus_kwargs: dict[str, Any] = {} if results.active: - bus.state = BusState.ACTIVE + _warn_listen_only_deprecated("The '--active' argument", "'--no-listen-only'") + bus_kwargs["listen_only"] = False elif results.passive: - bus.state = BusState.PASSIVE + _warn_listen_only_deprecated("The '--passive' argument", "'--listen-only'") + bus_kwargs["listen_only"] = True + + bus = create_bus_from_namespace(results, **bus_kwargs) + _set_logging_level_from_namespace(results) print(f"Connected to {bus.__class__.__name__}: {bus.channel_info}") print(f"Can Logger (Started on {datetime.now(tz=UTC)})") diff --git a/can/thread_safe_bus.py b/can/thread_safe_bus.py index ab6e0b4e3..a303fbb46 100644 --- a/can/thread_safe_bus.py +++ b/can/thread_safe_bus.py @@ -116,6 +116,16 @@ def state(self, new_state: BusState) -> None: with self._self_lock_send, self._self_lock_recv: self._self_wrapped.state = new_state + @property + def listen_only(self) -> bool: + # like state, reading must not wait for a thread blocking in recv() + return self._self_wrapped.listen_only + + @listen_only.setter + def listen_only(self, value: bool) -> None: + with self._self_lock_send, self._self_lock_recv: + self._self_wrapped.listen_only = value + @property def protocol(self) -> CanProtocol: return self._self_wrapped.protocol diff --git a/can/util.py b/can/util.py index 27f421f42..9f81bc74c 100644 --- a/can/util.py +++ b/can/util.py @@ -4,6 +4,7 @@ import copy import functools +import inspect import json import logging import os @@ -241,6 +242,16 @@ def _create_bus_config(config: dict[str, Any]) -> typechecking.BusConfig: if "fd" in config: config["fd"] = config["fd"] not in (0, False) + if "listen_only" in config and config["listen_only"] is None: + # not requested + del config["listen_only"] + elif "listen_only" in config: + if isinstance(config["listen_only"], str): + raise ValueError( + f"listen_only config must be a boolean, got {config['listen_only']!r}" + ) + config["listen_only"] = config["listen_only"] not in (0, False) + if "state" in config and not isinstance(config["state"], can.BusState): try: config["state"] = can.BusState[config["state"]] @@ -425,6 +436,41 @@ def _rename_kwargs( warnings.warn(deprecation_notice, DeprecationWarning, stacklevel=3) +def _warn_listen_only_deprecated( + deprecated_usage: str, replacement: str | None = "'listen_only=True'" +) -> None: + """Emit the deprecation warning for a legacy way to request listen-only mode. + + :param deprecated_usage: + Description of the deprecated usage, e.g. ``"The 'monitor' argument"``. + :param replacement: + Description of what to use instead, or ``None`` if there is no replacement. + """ + message = ( + f"{deprecated_usage} is deprecated since python-can v4.7.0, and " + f"scheduled for removal in python-can v5.0.0." + ) + if replacement is not None: + message += f" Use {replacement} instead." + + # attribute the warning to the first frame outside of python-can or to a + # python-can script run as __main__, so that the default filters show it + package_dir = os.path.join(os.path.dirname(can.__file__), "") + frame = inspect.currentframe() + stacklevel = 1 + while ( + frame is not None + and frame.f_code.co_filename.startswith(package_dir) + and frame.f_globals.get("__name__") != "__main__" + ): + frame = frame.f_back + stacklevel += 1 + if frame is None: + # called from python-can only, attribute it to the direct caller + stacklevel = 2 + warnings.warn(message, DeprecationWarning, stacklevel=stacklevel) + + T2 = TypeVar("T2", BitTiming, BitTimingFd) diff --git a/can/viewer.py b/can/viewer.py index ca9eafdc0..f8512f426 100644 --- a/can/viewer.py +++ b/can/viewer.py @@ -412,7 +412,9 @@ def _parse_viewer_args( ) # add bus options group - add_bus_arguments(parser, filter_arg=True, group_title="Bus arguments") + add_bus_arguments( + parser, filter_arg=True, listen_only_arg=True, group_title="Bus arguments" + ) optional = parser.add_argument_group("Optional arguments") diff --git a/doc/bus.rst b/doc/bus.rst index f63c244c2..b33daa11c 100644 --- a/doc/bus.rst +++ b/doc/bus.rst @@ -74,6 +74,121 @@ Example defining two filters, one to pass 11-bit ID ``0x451``, the other to pass See :meth:`~can.BusABC.set_filters` for the implementation. +.. _listen_only: + +Listen-only mode +'''''''''''''''' + +A bus in listen-only mode only receives: it never puts frames, acknowledgements +or error frames on the wire, which makes it safe for passively logging a live +bus. Listen-only mode corresponds to the bus monitoring mode of +ISO 11898-1:2015, ยง10.14. + +Listen-only mode is selected when the bus is created, with the ``listen_only`` +argument, with ``listen_only = True`` in a :ref:`configuration file `, +or with ``--listen-only`` on ``can.logger`` and ``can.viewer``. ``listen_only=False`` +or ``--no-listen-only`` opens the bus in normal mode, overriding the configuration. +``listen_only=False`` is accepted by every interface, so a shared configuration +file can set it. The interfaces in the table below support listen-only mode; on +other interfaces, ``listen_only=True`` raises +:class:`~can.exceptions.CanInterfaceNotImplementedError`. If the mode cannot be +applied, :class:`~can.exceptions.CanInitializationError` is raised. + +.. code-block:: python + + with can.Bus(interface="vector", channel=0, listen_only=True) as bus: + for msg in bus: + print(msg) + +The :attr:`~can.BusABC.listen_only` property tells whether a bus is in listen-only +mode; if listen-only mode was not requested, it reports ``False``. Interfaces that +can switch the mode at runtime also allow setting it. + +.. list-table:: + :header-rows: 1 + :widths: 12 18 10 20 40 + + * - Interface + - ``listen_only=None`` means + - Switch at runtime + - :meth:`~can.BusABC.send` in listen-only mode (raises + :class:`~can.exceptions.CanOperationError`) + - Notes + * - ``cantact`` + - mode unchanged + - no + - raises + - + * - ``kvaser`` + - mode unchanged + - no + - raises + - Silent mode is supported only by some CAN controllers (Kvaser CANlib + help, "CAN Driver Modes"). A channel without init access is accepted + only if it already is in the requested mode; otherwise + :class:`~can.exceptions.CanInitializationError` is raised, for + ``listen_only=False`` as well. + * - ``nixnet`` + - mode unchanged + - no + - raises + - + * - ``pcan`` + - mode unchanged + - yes + - raises + - On PCAN-LAN devices, the mode can only be set on the device itself. + * - ``seeedstudio`` + - normal mode + - no + - raises, except with ``operation_mode="loopback"`` + - With ``operation_mode="loopback"``, sent frames are looped back by the + device and not put on the bus. + * - ``slcan`` + - normal mode + - no + - raises + - + * - ``systec`` + - normal mode + - yes + - raises + - + * - ``vector`` + - mode unchanged + - no + - raises, except with ``receive_own_messages=True`` + - With ``receive_own_messages=True``, a sent frame is received back as + the bus's own message and is not put on the bus. ``listen_only=False`` + requests init access too, so other applications cannot change the + channel settings while the bus is open. A channel without init access + is accepted only if it already is in the requested mode; otherwise + :class:`~can.exceptions.CanInitializationError` is raised, for + ``listen_only=False`` as well. + * - ``virtual`` + - normal mode + - no + - raises + - + +On ``socketcan``, set listen-only mode on the network interface, e.g. +``ip link set can0 type can bitrate 500000 listen-only on``. See +:ref:`businternals` for how a plugin interface declares support. + +.. deprecated:: 4.7.0 + The interface specific ways to request listen-only mode are deprecated in favour + of ``listen_only``: the ``monitor`` argument of ``cantact``, the ``driver_mode`` + argument of ``kvaser``, the ``"silent"`` and ``"loopback_and_silent"`` operation + modes of ``seeedstudio``, the ``state`` argument and setting ``bus.state`` for + ``pcan`` and ``systec``, and the ``--passive`` and ``--active`` arguments of + ``can.logger``. If ``listen_only`` is also given, e.g. in a configuration file, + and contradicts a deprecated option, :class:`ValueError` is raised. + +.. versionchanged:: 4.7.0 + In listen-only mode, :meth:`~can.BusABC.send` raises + :class:`~can.exceptions.CanOperationError` instead of passing the frame to the + driver, except for the two cases in the table above. + Bus API ''''''' diff --git a/doc/changelog.d/2149.added.rst b/doc/changelog.d/2149.added.rst new file mode 100644 index 000000000..01dfd504f --- /dev/null +++ b/doc/changelog.d/2149.added.rst @@ -0,0 +1 @@ +Added the ``listen_only`` argument to :func:`can.Bus` and :class:`can.BusABC`, the :attr:`can.BusABC.listen_only` property, and ``--listen-only``/``--no-listen-only`` to ``can.logger`` and ``can.viewer``. diff --git a/doc/changelog.d/2149.changed.rst b/doc/changelog.d/2149.changed.rst new file mode 100644 index 000000000..d8a180d48 --- /dev/null +++ b/doc/changelog.d/2149.changed.rst @@ -0,0 +1 @@ +The default ``listen_only=None`` leaves the mode unchanged on ``cantact``, ``kvaser``, ``nixnet`` and ``pcan``. An explicit ``listen_only=False`` on ``vector`` now requests init access and sets normal mode. On ``vector`` and ``kvaser``, a channel without init access that is not in the requested mode raises :class:`~can.exceptions.CanInitializationError`, for ``listen_only=False`` as well. ``send()`` raises :class:`~can.exceptions.CanOperationError` in listen-only mode. ``listen_only=True`` raises :class:`~can.exceptions.CanInterfaceNotImplementedError` on interfaces without support, including third-party plugins whose constructor does not declare a ``listen_only`` parameter. ``listen_only=True`` raises :class:`~can.exceptions.CanInitializationError` when the mode cannot be applied (``vector`` or ``kvaser`` channels without init access that are not already silent, ``kvaser`` controllers without silent mode, PCAN-LAN devices); before, the bus silently opened in normal mode. diff --git a/doc/changelog.d/2149.deprecated.rst b/doc/changelog.d/2149.deprecated.rst new file mode 100644 index 000000000..d47e32fe8 --- /dev/null +++ b/doc/changelog.d/2149.deprecated.rst @@ -0,0 +1 @@ +Deprecated the interface specific listen-only options in favour of ``listen_only``: ``monitor`` of ``cantact``, ``driver_mode`` of ``kvaser``, the ``"silent"`` and ``"loopback_and_silent"`` operation modes of ``seeedstudio``, the ``state`` argument and setting ``bus.state`` on ``pcan`` and ``systec``, and ``--active``/``--passive`` of ``can.logger``. Giving such an option together with a contradicting ``listen_only`` raises :class:`ValueError`. diff --git a/doc/changelog.d/2149.fixed.rst b/doc/changelog.d/2149.fixed.rst new file mode 100644 index 000000000..a0dfc5070 --- /dev/null +++ b/doc/changelog.d/2149.fixed.rst @@ -0,0 +1 @@ +The deprecated silent ``driver_mode`` of ``kvaser`` is now applied to the handle with init access; it was ineffective with ``single_handle=False``. ``can.logger --active`` no longer fails with ``NotImplementedError`` on interfaces that cannot set ``bus.state``, and ``can.logger --passive`` now works on every interface that supports listen-only mode instead of only on ``pcan`` and ``systec``. An invalid ``operation_mode`` of ``seeedstudio`` now raises :class:`ValueError` before the serial port is opened, instead of a ``KeyError`` afterwards. diff --git a/doc/interfaces/pcan.rst b/doc/interfaces/pcan.rst index 851fa5899..b4996fe7f 100644 --- a/doc/interfaces/pcan.rst +++ b/doc/interfaces/pcan.rst @@ -15,7 +15,7 @@ Here is an example configuration file for using `PCAN-USB `. + +``state`` (default ``None``) + BusState of the channel. + Deprecated since 4.7.0, use ``listen_only`` instead. + If ``listen_only`` is also given with a contradicting value, :class:`ValueError` is raised. ``bitrate`` (default ``500000``) Channel bitrate diff --git a/doc/interfaces/seeedstudio.rst b/doc/interfaces/seeedstudio.rst index 173944e0d..6f7920d69 100644 --- a/doc/interfaces/seeedstudio.rst +++ b/doc/interfaces/seeedstudio.rst @@ -45,7 +45,8 @@ Configuration frame_type='STD', operation_mode='normal', bitrate=500000, - can_filters=None) + can_filters=None, + listen_only=None) CHANNEL The serial port created by the USB device when connected. @@ -60,8 +61,15 @@ FRAMETYPE OPERATIONMODE - "normal" - "loopback" - - "silent" - - "loopback_and_silent" + - "silent" (deprecated since 4.7.0, use ``listen_only=True`` instead) + - "loopback_and_silent" (deprecated since 4.7.0, use ``listen_only=True`` with + "loopback" instead). With ``listen_only=False``, the deprecated modes raise + :class:`ValueError`. + +LISTEN_ONLY + Open the device in :ref:`listen-only mode `. Combined with + OPERATIONMODE "loopback", sent frames are looped back by the device instead of + raising :class:`~can.exceptions.CanOperationError`. BITRATE - 1000000 diff --git a/doc/interfaces/systec.rst b/doc/interfaces/systec.rst index 6b04fdfe0..20937e51d 100644 --- a/doc/interfaces/systec.rst +++ b/doc/interfaces/systec.rst @@ -48,7 +48,10 @@ Optional parameters: * ``device_number`` (default first device) The device number of the USB-CAN * ``rx_buffer_entries`` (default 4096) The maximum number of entries in the receive buffer * ``tx_buffer_entries`` (default 4096) The maximum number of entries in the transmit buffer -* ``state`` (default BusState.ACTIVE) BusState of the channel +* ``listen_only`` (default None, i.e. normal mode) Open the channel in :ref:`listen-only mode ` +* ``state`` (default None) BusState of the channel. + Deprecated since 4.7.0, use ``listen_only`` instead. + If ``listen_only`` is also given with a contradicting value, :class:`ValueError` is raised. * ``receive_own_messages`` (default False) If messages transmitted should also be received back diff --git a/doc/internal-api.rst b/doc/internal-api.rst index 9e544f052..677781faa 100644 --- a/doc/internal-api.rst +++ b/doc/internal-api.rst @@ -41,8 +41,21 @@ They **might** implement the following: * :meth:`~can.BusABC._detect_available_configs` to allow the interface to report which configurations are currently available for new connections. - * :meth:`~can.BusABC.state` property to allow reading and/or changing - the bus state. + * :meth:`~can.BusABC.state` property to allow reading the bus state. + Listen-only mode is requested through a ``listen_only`` constructor + parameter instead, see :ref:`listen_only`. + * :ref:`listen-only mode `. An interface supports it only if + its constructor declares ``listen_only`` as a keyword parameter (a + positional-only one is not detected), or + forwards ``**kwargs`` to a base class constructor that does; decorators + on the constructor must use :func:`functools.wraps`. For any other + interface, ``listen_only=True`` raises + :class:`~can.exceptions.CanInterfaceNotImplementedError` before its + constructor runs. In listen-only mode, :meth:`~can.BusABC.send` must + raise :class:`~can.exceptions.CanOperationError`, and the + :attr:`~can.BusABC.listen_only` property must report the mode. Override + the :attr:`~can.BusABC.listen_only` setter only if the mode can be + switched at runtime. .. note:: diff --git a/examples/receive_all.py b/examples/receive_all.py index e9410e49f..6e05d581b 100755 --- a/examples/receive_all.py +++ b/examples/receive_all.py @@ -5,7 +5,6 @@ """ import can -from can.bus import BusState def receive_all(): @@ -13,13 +12,9 @@ def receive_all(): # this uses the default configuration (for example from environment variables, or a # config file) see https://python-can.readthedocs.io/en/stable/configuration.html - with can.Bus() as bus: - # set to read-only, only supported on some interfaces - try: - bus.state = BusState.PASSIVE - except NotImplementedError: - pass - + # listen-only mode is only supported on some interfaces, see + # https://python-can.readthedocs.io/en/stable/bus.html#listen-only-mode + with can.Bus(listen_only=True) as bus: try: while True: msg = bus.recv(1) diff --git a/test/back2back_test.py b/test/back2back_test.py index 4b448d9ad..be8ae4b08 100644 --- a/test/back2back_test.py +++ b/test/back2back_test.py @@ -8,6 +8,7 @@ import unittest from multiprocessing.dummy import Pool as ThreadPool from time import sleep, time +from unittest.mock import patch import pytest @@ -440,6 +441,39 @@ def test_state_while_recv_blocks(self): self.assertIsNone(pending.get()) receiver.close() + def test_listen_only_while_recv_blocks(self): + """ + Test Scope: + Reading and setting listen_only on a ThreadSafeBus while another + thread blocks in recv(). + Preconditions: + The wrapped bus class has a listen_only property that records when + it is set. + Events: + Block in recv() with a timeout of 0.3 s on another thread, then + read listen_only and set it to True. + Evaluate: + Reading returns within 0.2 s, while recv() still blocks; setting + reaches the wrapped bus only after 0.25 s, once recv() returned. + """ + set_at = [] + listen_only = property(lambda _: False, lambda _, value: set_at.append(time())) + receiver = ThreadPool(1) + with patch.object(type(self.bus2.__wrapped__), "listen_only", listen_only): + start = time() + pending = receiver.apply_async(self.bus2.recv, (0.3,)) + sleep(0.1) # let the receiver take the receive lock + + self.assertIs(self.bus2.listen_only, False) + self.assertLess(time() - start, 0.2) + + self.bus2.listen_only = True + self.assertEqual(len(set_at), 1) + self.assertGreaterEqual(set_at[0] - start, 0.25) + + self.assertIsNone(pending.get()) + receiver.close() + @pytest.mark.timeout(180.0 if IS_PYPY else 5.0) def test_filtered_bus(self): sender_pool = ThreadPool(100) diff --git a/test/test_bus.py b/test/test_bus.py index 6a09a6deb..9a8183194 100644 --- a/test/test_bus.py +++ b/test/test_bus.py @@ -1,7 +1,10 @@ import gc from unittest.mock import patch +import pytest + import can +from can.interfaces.virtual import VirtualBus def test_bus_ignore_config(): @@ -15,6 +18,111 @@ def test_bus_ignore_config(): assert can.util.load_config.called +class _KwargsOnlyBus(can.BusABC): + """A plugin-style bus that passes everything on to BusABC.""" + + instances = 0 + + def __init__(self, channel, **kwargs): + _KwargsOnlyBus.instances += 1 + super().__init__(channel, **kwargs) + + def send(self, msg, timeout=None): + pass + + def _recv_internal(self, timeout): + return None, False + + +def test_bus_listen_only_rejected_if_not_declared(): + """ + Test Scope: + A bus class whose constructor only takes **kwargs. + Preconditions: + A bus class without a listen_only parameter is registered as interface + "kwargs_only". + Events: + Create the bus with listen_only=True through can.Bus and directly, then + with listen_only=False through can.Bus. + Evaluate: + listen_only=True raises CanInterfaceNotImplementedError both ways + before the bus constructor runs; listen_only=False creates the bus. + """ + with patch.dict( + "can.interfaces.BACKENDS", {"kwargs_only": (__name__, "_KwargsOnlyBus")} + ): + _KwargsOnlyBus.instances = 0 + with pytest.raises(can.CanInterfaceNotImplementedError): + can.Bus("ch", interface="kwargs_only", ignore_config=True, listen_only=True) + with pytest.raises(can.CanInterfaceNotImplementedError): + _KwargsOnlyBus("ch", listen_only=True) + assert _KwargsOnlyBus.instances == 0 + + with can.Bus("ch", interface="kwargs_only", ignore_config=True) as bus: + assert not bus.listen_only + assert _KwargsOnlyBus.instances == 1 + + +class _ForwardingVirtualBus(VirtualBus): + """A subclass that forwards all arguments to a listen-only capable bus.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + +def test_bus_listen_only_accepted_if_forwarded(): + """ + Test Scope: + A bus subclass whose constructor forwards **kwargs to a base class + that declares listen_only. + Preconditions: + A subclass of VirtualBus with an __init__(*args, **kwargs). + Events: + Create the subclass with listen_only=True and send a message. + Evaluate: + The bus is created in listen-only mode and send raises + CanOperationError. + """ + with _ForwardingVirtualBus("ch", listen_only=True) as bus: + assert bus.listen_only + with pytest.raises(can.CanOperationError): + bus.send(can.Message()) + + +class _PositionalOnlyBus(VirtualBus): + """A VirtualBus subclass whose constructor takes neither listen_only nor **kwargs.""" + + def __init__(self, channel): + super().__init__(channel) + + +def test_bus_without_listen_only_or_kwargs(): + """ + Test Scope: + can.Bus with an interface whose constructor accepts neither + listen_only nor **kwargs. + Preconditions: + A VirtualBus subclass whose constructor __init__(self, channel) takes + neither listen_only nor **kwargs is registered as interface + "positional_only". + Events: + Create the bus through can.Bus without listen_only and with + listen_only=False. + Evaluate: + Both buses are created and are not in listen-only mode. + """ + with patch.dict( + "can.interfaces.BACKENDS", + {"positional_only": (__name__, "_PositionalOnlyBus")}, + ): + with can.Bus("ch", interface="positional_only", ignore_config=True) as bus: + assert not bus.listen_only + with can.Bus( + "ch", interface="positional_only", ignore_config=True, listen_only=False + ) as bus: + assert not bus.listen_only + + @patch.object(can.bus.BusABC, "shutdown") def test_bus_attempts_self_cleanup(mock_shutdown): bus = can.Bus(interface="virtual") diff --git a/test/test_cantact.py b/test/test_cantact.py index f90655ae5..ff2ed8aba 100644 --- a/test/test_cantact.py +++ b/test/test_cantact.py @@ -12,6 +12,18 @@ class CantactTest(unittest.TestCase): def test_bus_creation(self): + """ + Test Scope: + Creation of a CANtact bus with default arguments. + Preconditions: + A mocked CANtact device. + Events: + Create a bus without listen_only. + Evaluate: + The bus uses classic CAN, the bitrate is set, the channel is + enabled and started, and the monitor mode is left unchanged. + """ + cantact.MockInterface.set_monitor.reset_mock() bus = can.Bus(channel=0, interface="cantact", _testing=True) self.assertIsInstance(bus, cantact.CantactBus) self.assertEqual(bus.protocol, can.CanProtocol.CAN_20) @@ -19,10 +31,21 @@ def test_bus_creation(self): cantact.MockInterface.set_bitrate.assert_called() cantact.MockInterface.set_bit_timing.assert_not_called() cantact.MockInterface.set_enabled.assert_called() - cantact.MockInterface.set_monitor.assert_called() + cantact.MockInterface.set_monitor.assert_not_called() cantact.MockInterface.start.assert_called() def test_bus_creation_bittiming(self): + """ + Test Scope: + Creation of a CANtact bus with a custom bit timing. + Preconditions: + A mocked CANtact device. + Events: + Create a bus with a BitTiming instance. + Evaluate: + The bus uses classic CAN, the bit timing is set instead of the + bitrate, and the channel is enabled and started. + """ cantact.MockInterface.set_bitrate.reset_mock() bt = can.BitTiming(f_clock=24_000_000, brp=3, tseg1=13, tseg2=2, sjw=1) @@ -34,7 +57,6 @@ def test_bus_creation_bittiming(self): cantact.MockInterface.set_bitrate.assert_not_called() cantact.MockInterface.set_bit_timing.assert_called() cantact.MockInterface.set_enabled.assert_called() - cantact.MockInterface.set_monitor.assert_called() cantact.MockInterface.start.assert_called() def test_transmit(self): @@ -57,6 +79,82 @@ def test_recv_timeout(self): cantact.MockInterface.recv.assert_called() self.assertIsNone(frame) + def test_listen_only(self): + """ + Test Scope: + Listen-only mode of the CANtact interface. + Preconditions: + A mocked CANtact device. + Events: + Create a listen-only bus and try to send a message. + Evaluate: + Monitor mode is switched on, send raises CanOperationError and no + frame is passed to the device. + """ + cantact.MockInterface.send.reset_mock() + cantact.MockInterface.set_monitor.reset_mock() + bus = can.Bus(channel=0, interface="cantact", listen_only=True, _testing=True) + + cantact.MockInterface.set_monitor.assert_called_with(0, True) + with self.assertRaises(can.CanOperationError): + bus.send(can.Message(arbitration_id=0x123)) + cantact.MockInterface.send.assert_not_called() + + def test_monitor_deprecated(self): + """ + Test Scope: + The deprecated monitor argument of the CANtact interface. + Preconditions: + A mocked CANtact device. + Events: + Create a bus with monitor set to True as positional argument. + Evaluate: + A DeprecationWarning is emitted and monitor mode is switched on. + """ + cantact.MockInterface.set_monitor.reset_mock() + with self.assertWarns(DeprecationWarning): + cantact.CantactBus(0, 500_000, 0.01, True, _testing=True) + + cantact.MockInterface.set_monitor.assert_called_with(0, True) + + def test_monitor_deprecation_points_at_caller(self): + """ + Test Scope: + Source location of the DeprecationWarning for the deprecated + monitor argument. + Preconditions: + A mocked CANtact device. + Events: + Create a bus through can.Bus with monitor=True. + Evaluate: + The DeprecationWarning is attributed to this test file. + """ + with self.assertWarns(DeprecationWarning) as warning: + can.Bus(channel=0, interface="cantact", monitor=True, _testing=True) + + self.assertEqual(warning.filename, __file__) + + def test_listen_only_contradicts_monitor(self): + """ + Test Scope: + An explicit listen_only that contradicts the deprecated monitor + argument of the CANtact interface. + Preconditions: + A mocked CANtact device. + Events: + Create a bus through can.Bus with listen_only=False and monitor=True. + Evaluate: + A DeprecationWarning is emitted and ValueError is raised. + """ + with self.assertWarns(DeprecationWarning), self.assertRaises(ValueError): + can.Bus( + channel=0, + interface="cantact", + listen_only=False, + monitor=True, + _testing=True, + ) + def test_shutdown(self): bus = can.Bus(channel=0, interface="cantact", _testing=True) bus.shutdown() diff --git a/test/test_cli.py b/test/test_cli.py index ecc662832..e4ef6016c 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -97,6 +97,36 @@ def test_add_bus_arguments_no_prefix(self): self.assertEqual(parsed_args.bus_kwargs["app_name"], "MyApp") self.assertEqual(parsed_args.bus_kwargs["serial"], 1234) + @patch("can.Bus") + def test_listen_only_argument(self, mock_bus): + """ + Test Scope: + The --listen-only and --no-listen-only arguments, with and without + prefix. + Preconditions: + A mocked can.Bus and a parser with listen_only_arg=True. + Events: + Parse --listen-only, --test-listen-only, --no-listen-only and + --no-test-listen-only and create a bus from each namespace. + Evaluate: + The buses are created with listen_only=True for the positive and + listen_only=False for the negative flags. + """ + for prefix, flag, expected in ( + (None, "--listen-only", True), + ("test", "--test-listen-only", True), + (None, "--no-listen-only", False), + ("test", "--no-test-listen-only", False), + ): + mock_bus.reset_mock() + parser = argparse.ArgumentParser() + add_bus_arguments(parser, listen_only_arg=True, prefix=prefix) + + namespace = parser.parse_args([flag]) + create_bus_from_namespace(namespace, prefix=prefix) + + self.assertIs(mock_bus.call_args.kwargs["listen_only"], expected) + @patch("can.Bus") def test_create_bus_from_namespace(self, mock_bus): namespace = argparse.Namespace( diff --git a/test/test_interface_virtual.py b/test/test_interface_virtual.py index c1d842180..8fccc1cb9 100644 --- a/test/test_interface_virtual.py +++ b/test/test_interface_virtual.py @@ -6,7 +6,9 @@ import unittest -from can import Bus, Message +import pytest + +from can import Bus, CanOperationError, Message EXAMPLE_MSG1 = Message(timestamp=1639739471.5565314, arbitration_id=0x481, data=b"\x01") @@ -35,5 +37,39 @@ def test_sendmsg_preserve_timestamp(self): assert r.data == EXAMPLE_MSG1.data +def test_listen_only() -> None: + """ + Test Scope: + Listen-only mode of the virtual interface. + Preconditions: + A listen-only bus and a normal bus on the same virtual channel. + Events: + The normal bus sends a message, then the listen-only bus tries to send one + and to switch listen_only off. + Evaluate: + Only the listen-only bus reports listen_only, it receives the message, + its own send raises CanOperationError and nothing reaches the normal bus. + Setting listen_only raises NotImplementedError. + """ + with ( + Bus("listen_only", interface="virtual", listen_only=True) as listener, + Bus("listen_only", interface="virtual") as sender, + ): + assert listener.listen_only + assert not sender.listen_only + + sender.send(EXAMPLE_MSG1) + received = listener.recv(0.1) + assert received is not None + assert received.arbitration_id == EXAMPLE_MSG1.arbitration_id + + with pytest.raises(CanOperationError): + listener.send(EXAMPLE_MSG1) + assert sender.recv(0) is None + + with pytest.raises(NotImplementedError): + listener.listen_only = False + + if __name__ == "__main__": unittest.main() diff --git a/test/test_kvaser.py b/test/test_kvaser.py index 47ac99cdc..d16ff6186 100644 --- a/test/test_kvaser.py +++ b/test/test_kvaser.py @@ -26,7 +26,14 @@ def setUp(self): canlib.canBusOn = Mock() canlib.canBusOff = Mock() canlib.canClose = Mock() - canlib.canSetBusOutputControl = Mock() + # model a channel with init access: the driver mode reads back as set + self.driver_type = constants.canDRIVER_NORMAL + canlib.canSetBusOutputControl = Mock( + side_effect=lambda hnd, mode: setattr(self, "driver_type", mode) + ) + canlib.canGetBusOutputControl = Mock( + side_effect=lambda hnd, ref: setattr(ref._obj, "value", self.driver_type) + ) canlib.canGetChannelData = Mock() canlib.canSetAcceptanceFilter = Mock() canlib.canWriteSync = Mock() @@ -319,6 +326,121 @@ def test_bus_no_init_access(self): bus.shutdown() + def test_listen_only(self): + """ + Test Scope: + Listen-only mode of the Kvaser interface. + Preconditions: + A mocked CANLIB. + Events: + Create a listen-only bus with separate read and write handles and + try to send a message. + Evaluate: + The bus output of the first opened handle, which holds init access, + is set to silent. send raises CanOperationError and no frame is + written. + """ + canlib.canSetBusOutputControl.reset_mock() + canlib.canOpenChannel = Mock(side_effect=[1, 2]) + bus = can.Bus(interface="kvaser", channel=0, listen_only=True) + + canlib.canSetBusOutputControl.assert_called_once_with( + 1, constants.canDRIVER_SILENT + ) + with self.assertRaises(can.CanOperationError): + bus.send(can.Message(arbitration_id=0x321, data=[50, 51])) + self.assertEqual(self.msg, {}) + + bus.shutdown() + + def test_listen_only_without_init_access(self): + """ + Test Scope: + listen_only=True and False on a Kvaser channel without init access. + Preconditions: + A mocked CANLIB in which setting the driver mode has no effect, as + on a handle without init access. + Events: + Create a bus with listen_only, once with the channel already in the + requested driver mode and once in the other one. + Evaluate: + The bus is created if the channel already is in the requested mode, + otherwise CanInitializationError is raised. + """ + canlib.canSetBusOutputControl = Mock() + modes = (constants.canDRIVER_NORMAL, constants.canDRIVER_SILENT) + for listen_only in (False, True): + for self.driver_type in modes: + with self.subTest(listen_only=listen_only, driver=self.driver_type): + if (self.driver_type == constants.canDRIVER_SILENT) == listen_only: + bus = can.Bus( + interface="kvaser", channel=0, listen_only=listen_only + ) + self.assertEqual(bus.listen_only, listen_only) + bus.shutdown() + else: + with self.assertRaises(can.CanInitializationError): + can.Bus( + interface="kvaser", channel=0, listen_only=listen_only + ) + + def test_listen_only_not_requested(self): + """ + Test Scope: + A Kvaser bus created without listen_only. + Preconditions: + A mocked CANLIB. + Events: + Create a bus without listen_only and driver_mode. + Evaluate: + The driver mode is not written and listen_only reports False. + """ + canlib.canSetBusOutputControl.assert_not_called() + self.assertFalse(self.bus.listen_only) + + def test_listen_only_contradicts_driver_mode(self): + """ + Test Scope: + An explicit listen_only that contradicts the deprecated driver_mode + argument. + Preconditions: + A mocked CANLIB. + Events: + Create a bus with listen_only=False and driver_mode set to silent. + Evaluate: + A DeprecationWarning is emitted and ValueError is raised. + """ + with self.assertWarns(DeprecationWarning), self.assertRaises(ValueError): + can.Bus( + interface="kvaser", + channel=0, + listen_only=False, + driver_mode=canlib.DRIVER_MODE_SILENT, + ) + + def test_driver_mode_silent_deprecated(self): + """ + Test Scope: + The deprecated driver_mode argument of the Kvaser interface. + Preconditions: + A mocked CANLIB. + Events: + Create a bus with driver_mode set to silent. + Evaluate: + A DeprecationWarning is emitted and the bus output is set to silent. + """ + canlib.canSetBusOutputControl.reset_mock() + with self.assertWarns(DeprecationWarning): + bus = can.Bus( + interface="kvaser", channel=0, driver_mode=canlib.DRIVER_MODE_SILENT + ) + + self.assertEqual( + canlib.canSetBusOutputControl.call_args[0][1], constants.canDRIVER_SILENT + ) + + bus.shutdown() + @staticmethod def canGetNumberOfChannels(count): count._obj.value = 2 diff --git a/test/test_load_config.py b/test/test_load_config.py index 3075f7b40..26793d09d 100644 --- a/test/test_load_config.py +++ b/test/test_load_config.py @@ -111,6 +111,38 @@ def test_config_whole_environment(self): expected.update({"interface": "socketcan", "channel": 3, "bitrate": 250000}) self.assertEqual(config, expected) + def test_listen_only_is_normalized_to_bool(self): + """ + Test Scope: + Normalization of the listen_only config value. + Preconditions: + No config file, environment or rc values. + Events: + Load configs with listen_only given as "1", "0", "true" and "false", + then as None, then as "off". + Evaluate: + The loaded listen_only value is the matching bool; None leaves + listen_only out of the loaded config; "off" raises ValueError. + """ + for value, expected in ( + ("1", True), + ("0", False), + ("true", True), + ("false", False), + ): + config = self._load_config_isolated( + config={"interface": "virtual", "listen_only": value} + ) + self.assertIs(config["listen_only"], expected) + config = self._load_config_isolated( + config={"interface": "virtual", "listen_only": None} + ) + self.assertNotIn("listen_only", config) + with self.assertRaises(ValueError): + self._load_config_isolated( + config={"interface": "virtual", "listen_only": "off"} + ) + if __name__ == "__main__": unittest.main() diff --git a/test/test_logger.py b/test/test_logger.py index 41778ab6a..835235629 100644 --- a/test/test_logger.py +++ b/test/test_logger.py @@ -6,8 +6,10 @@ import gzip import os +import runpy import sys import unittest +import warnings from unittest import mock from unittest.mock import Mock @@ -66,22 +68,100 @@ def test_log_virtual(self): self.mock_logger.assert_called_once() def test_log_virtual_active(self): + """ + Test Scope: + The deprecated --active argument of the logger script. + Preconditions: + A mocked can.Bus returning a mocked bus, and a mocked logger. + Events: + Run the logger with --active. + Evaluate: + A DeprecationWarning is emitted, can.Bus is called with + listen_only=False, and the bus and the logger are stopped. + """ self.mock_virtual_bus.recv = Mock(side_effect=[self.testmsg, KeyboardInterrupt]) sys.argv = self.baseargs + ["--active"] - can.logger.main() - self.assertSuccessfullCleanup() - self.mock_logger.assert_called_once() - self.assertEqual(self.mock_virtual_bus.state, can.BusState.ACTIVE) + with ( + mock.patch("can.Bus", return_value=self.mock_virtual_bus) as bus_factory, + self.assertWarns(DeprecationWarning), + ): + can.logger.main() + self.assertIs(bus_factory.call_args.kwargs["listen_only"], False) + self.mock_virtual_bus.shutdown.assert_called_once() + self.loggerToUse.stop.assert_called_once() def test_log_virtual_passive(self): + """ + Test Scope: + The deprecated --passive argument of the logger script. + Preconditions: + A mocked virtual bus and logger. + Events: + Run the logger with --passive. + Evaluate: + A DeprecationWarning is emitted and the bus is created in + listen-only mode. + """ self.mock_virtual_bus.recv = Mock(side_effect=[self.testmsg, KeyboardInterrupt]) sys.argv = self.baseargs + ["--passive"] - can.logger.main() + with self.assertWarns(DeprecationWarning): + can.logger.main() self.assertSuccessfullCleanup() self.mock_logger.assert_called_once() - self.assertEqual(self.mock_virtual_bus.state, can.BusState.PASSIVE) + self.assertIs(self.MockVirtualBus.call_args.kwargs["listen_only"], True) + + def test_passive_deprecation_points_at_script(self): + """ + Test Scope: + Source location of the DeprecationWarning for --passive when the + logger script runs as __main__. + Preconditions: + A mocked virtual bus whose recv raises KeyboardInterrupt, and a + mocked logger. + Events: + Run the can.logger module as __main__ with --passive. + Evaluate: + The DeprecationWarning is attributed to can/logger.py. + """ + self.mock_virtual_bus.recv = Mock(side_effect=KeyboardInterrupt) + + sys.argv = [*self.baseargs, "--passive"] + with ( + mock.patch("can.Logger", self.MockLogger), + warnings.catch_warnings(), + self.assertWarns(DeprecationWarning) as warning, + ): + # runpy warns that can.logger is already imported + warnings.simplefilter("ignore", RuntimeWarning) + runpy.run_module("can.logger", run_name="__main__", alter_sys=True) + self.assertEqual(warning.filename, can.logger.__file__) + + def test_state_not_allowed_with_contradicting_listen_only(self): + """ + Test Scope: + Combining the deprecated --active and --passive arguments with a + contradicting --listen-only or --no-listen-only. + Preconditions: + A mocked virtual bus whose recv raises KeyboardInterrupt. + Events: + Run the logger with --active and --listen-only, then with + --passive and --no-listen-only. + Evaluate: + The logger exits with a usage error and no bus is created. + """ + self.mock_virtual_bus.recv = Mock(side_effect=KeyboardInterrupt) + for args in (["--active", "--listen-only"], ["--passive", "--no-listen-only"]): + with self.subTest(args=args): + sys.argv = self.baseargs + args + with ( + self.assertRaises(SystemExit) as exit_info, + mock.patch("sys.stderr"), + ): + can.logger.main() + self.assertEqual(exit_info.exception.code, 2) + self.MockVirtualBus.assert_not_called() def test_log_virtual_with_config(self): self.mock_virtual_bus.recv = Mock(side_effect=[self.testmsg, KeyboardInterrupt]) diff --git a/test/test_pcan.py b/test/test_pcan.py index dfc87620b..23aef260d 100644 --- a/test/test_pcan.py +++ b/test/test_pcan.py @@ -67,7 +67,17 @@ def test_bus_creation(self) -> None: self.mock_pcan.InitializeFD.assert_not_called() def test_bus_creation_state_error(self) -> None: - with self.assertRaises(ValueError): + """ + Test Scope: + An invalid value for the deprecated state argument. + Preconditions: + A mocked PCAN-Basic API. + Events: + Create a bus with state ERROR. + Evaluate: + A DeprecationWarning is emitted and ValueError is raised. + """ + with self.assertWarns(DeprecationWarning), self.assertRaises(ValueError): can.Bus(interface="pcan", state=BusState.ERROR) @parameterized.expand([("f_clock", 80_000_000), ("f_clock_mhz", 80)]) @@ -476,21 +486,142 @@ def test_shutdown(self) -> None: ] ) def test_state(self, name, bus_state: BusState, expected_parameter) -> None: + """ + Test Scope: + The deprecated way to switch listen-only mode by setting the state. + Preconditions: + A mocked PCAN-Basic API. + Events: + Set the state to BusState.ACTIVE or BusState.PASSIVE. + Evaluate: + A DeprecationWarning is emitted and PCAN_LISTEN_ONLY is switched off + or on. + """ with self.subTest(name): self.bus = can.Bus(interface="pcan") - self.bus.state = bus_state - call_list = self.mock_pcan.SetValue.call_args_list - last_call_args_list = call_list[-1][0] + with self.assertWarns(DeprecationWarning): + self.bus.state = bus_state self.assertEqual( - last_call_args_list, + self.mock_pcan.SetValue.call_args[0], (PCAN_USBBUS1, PCAN_LISTEN_ONLY, expected_parameter), ) - def test_state_constructor(self): - for state in [BusState.ACTIVE, BusState.PASSIVE]: - bus = can.Bus(interface="pcan", state=state) - assert bus.state == state + def test_state_constructor(self) -> None: + """ + Test Scope: + The deprecated state argument of the PCAN bus constructor. + Preconditions: + A mocked PCAN-Basic API. + Events: + Create a bus with state ACTIVE, then one with state PASSIVE passed + positionally. + Evaluate: + Both emit a DeprecationWarning and report the requested state and + listen_only value. + """ + with self.assertWarns(DeprecationWarning): + bus = can.Bus(interface="pcan", state=BusState.ACTIVE) + assert bus.state == BusState.ACTIVE + assert not bus.listen_only + + with self.assertWarns(DeprecationWarning): + bus = PcanBus("PCAN_USBBUS1", None, BusState.PASSIVE) + assert bus.state == BusState.PASSIVE + assert bus.listen_only + + def test_listen_only(self) -> None: + """ + Test Scope: + Listen-only mode of the PCAN interface. + Preconditions: + A mocked PCAN-Basic API. + Events: + Create a listen-only bus, try to send a message, then switch + listen_only off. + Evaluate: + Listen-only mode is switched on, the state is PASSIVE, send raises + CanOperationError and no frame is written. Switching listen_only off + turns the driver's listen-only mode off and the state becomes ACTIVE. + """ + self.mock_pcan.Write = Mock(return_value=PCAN_ERROR_OK) + self.bus = can.Bus(interface="pcan", listen_only=True) + + self.mock_pcan.SetValue.assert_any_call( + PCAN_USBBUS1, PCAN_LISTEN_ONLY, PCAN_PARAMETER_ON + ) + assert self.bus.state == BusState.PASSIVE + with pytest.raises(can.CanOperationError): + self.bus.send(can.Message(arbitration_id=0x123)) + self.mock_pcan.Write.assert_not_called() + + self.bus.listen_only = False + self.assertEqual( + self.mock_pcan.SetValue.call_args[0], + (PCAN_USBBUS1, PCAN_LISTEN_ONLY, PCAN_PARAMETER_OFF), + ) + assert self.bus.state == BusState.ACTIVE + + def test_listen_only_not_requested(self) -> None: + """ + Test Scope: + A PCAN bus created without listen_only. + Preconditions: + A mocked PCAN-Basic API. + Events: + Create a bus without listen_only and state. + Evaluate: + PCAN_LISTEN_ONLY is not written and listen_only reports False. + """ + self.bus = can.Bus(interface="pcan") + + for call in self.mock_pcan.SetValue.call_args_list: + assert call.args[1] != PCAN_LISTEN_ONLY + assert not self.bus.listen_only + + def test_listen_only_set_value_fails(self) -> None: + """ + Test Scope: + Failure to set PCAN_LISTEN_ONLY. + Preconditions: + A mocked PCAN-Basic API that rejects PCAN_LISTEN_ONLY. + Events: + Create a bus with listen_only=True, then create a bus with + listen_only=False and set listen_only to True. + Evaluate: + The constructor raises CanInitializationError for listen_only=True + and succeeds for listen_only=False, the setter raises + CanOperationError and listen_only stays False. + """ + self.mock_pcan.SetValue = Mock( + side_effect=lambda _channel, parameter, _value: ( + PCAN_ERROR_ILLOPERATION + if parameter == PCAN_LISTEN_ONLY + else PCAN_ERROR_OK + ) + ) + with pytest.raises(CanInitializationError): + can.Bus(interface="pcan", listen_only=True) + + self.bus = can.Bus(interface="pcan", listen_only=False) + with pytest.raises(can.CanOperationError): + self.bus.listen_only = True + assert not self.bus.listen_only + + def test_listen_only_contradicts_state(self) -> None: + """ + Test Scope: + An explicit listen_only that contradicts the deprecated state + argument. + Preconditions: + A mocked PCAN-Basic API. + Events: + Create a bus with listen_only=False and state=BusState.PASSIVE. + Evaluate: + A DeprecationWarning is emitted and ValueError is raised. + """ + with self.assertWarns(DeprecationWarning), self.assertRaises(ValueError): + can.Bus(interface="pcan", listen_only=False, state=BusState.PASSIVE) def test_detect_available_configs(self) -> None: if platform.system() == "Darwin": diff --git a/test/test_seeedstudio.py b/test/test_seeedstudio.py new file mode 100644 index 000000000..68e6b29a1 --- /dev/null +++ b/test/test_seeedstudio.py @@ -0,0 +1,100 @@ +""" +Tests for the Seeed Studio USB-CAN analyzer interface +""" + +import contextlib +import warnings +from unittest.mock import patch + +import pytest + +import can +from can.interfaces.seeedstudio import SeeedBus + + +@pytest.mark.parametrize( + ("operation_mode", "listen_only", "device_mode", "can_send"), + [ + ("normal", True, 0x02, False), + ("loopback", True, 0x03, True), + ("silent", None, 0x02, False), + ("loopback_and_silent", None, 0x03, True), + ("loopback_and_silent", True, 0x03, True), + ], +) +def test_listen_only(operation_mode, listen_only, device_mode, can_send) -> None: + """ + Test Scope: + Listen-only mode of the Seeed Studio interface, with and without + loopback, requested with listen_only or with the deprecated + operation modes silent and loopback_and_silent. + Preconditions: + A mocked serial port. + Events: + Create a bus with listen_only=True and operation_mode normal or + loopback, with operation_mode silent and listen_only None, or with + operation_mode loopback_and_silent and listen_only None or True, and + send a message. + Evaluate: + The deprecated operation modes emit a DeprecationWarning. The init + frame selects silent mode (0x02) or loopback and silent mode (0x03). + In silent mode, send raises CanOperationError and writes nothing; in + loopback and silent mode, the message is written. + """ + deprecated = ( + pytest.deprecated_call() + if operation_mode in ("silent", "loopback_and_silent") + else contextlib.nullcontext() + ) + with ( + patch("can.interfaces.seeedstudio.seeedstudio.serial.Serial") as serial, + deprecated, + ): + bus = SeeedBus("port", operation_mode=operation_mode, listen_only=listen_only) + write = serial.return_value.write + init_frame = write.call_args.args[0] + assert init_frame[2] == 0x12 + assert init_frame[13] == device_mode + + msg = can.Message(arbitration_id=0x123, data=[1, 2, 3], is_extended_id=False) + if can_send: + bus.send(msg) + assert write.call_count == 2 + else: + with pytest.raises(can.CanOperationError): + bus.send(msg) + assert write.call_count == 1 + bus.shutdown() + + +@pytest.mark.parametrize( + ("operation_mode", "listen_only"), + [ + ("silent", False), + ("loopback_and_silent", False), + ("loopbak", True), + ("loopbak", None), + ], +) +def test_invalid_operation_mode(operation_mode, listen_only) -> None: + """ + Test Scope: + Rejection of an operation mode that is unknown or contradicts + listen_only. + Preconditions: + A mocked serial port. + Events: + Create a bus with a deprecated silent operation mode and + listen_only=False, or with an unknown operation mode and listen_only + True or None. + Evaluate: + ValueError is raised and the serial port is not opened. + """ + with ( + patch("can.interfaces.seeedstudio.seeedstudio.serial.Serial") as serial, + warnings.catch_warnings(), + pytest.raises(ValueError), + ): + warnings.simplefilter("ignore", DeprecationWarning) + SeeedBus("port", operation_mode=operation_mode, listen_only=listen_only) + serial.assert_not_called() diff --git a/test/test_slcan.py b/test/test_slcan.py index b757ad04d..b20140cc1 100644 --- a/test/test_slcan.py +++ b/test/test_slcan.py @@ -3,6 +3,7 @@ import unittest.mock from typing import cast, Optional +import pytest from serial.serialutil import SerialBase import can.interfaces.slcan @@ -475,5 +476,36 @@ def test_serial_number(self): self.assertEqual(sn, "A123") +@unittest.mock.patch("serial.serial_for_url", SerialMock.serial_for_url) +def test_listen_only() -> None: + """ + Test Scope: + Listen-only mode of the slcan interface. + Preconditions: + A mocked serial port. + Events: + Create a listen-only bus and try to send a message. + Evaluate: + The channel is opened with the L command, send raises + CanOperationError and nothing more is written. + """ + bus = can.Bus( + "loop://", + interface="slcan", + sleep_after_open=0, + timeout=TIMEOUT, + bitrate=500000, + listen_only=True, + ) + serial = cast("SerialMock", bus.serialPortOrig) + assert serial.get_output_buffer() == b"L\r" + + with pytest.raises(can.CanOperationError): + bus.send(can.Message(arbitration_id=0x123, data=[0xAA])) + assert serial.get_output_buffer() == b"L\r" + + bus.shutdown() + + if __name__ == "__main__": unittest.main() diff --git a/test/test_systec.py b/test/test_systec.py index c1f9ad1ce..7293ec2bb 100644 --- a/test/test_systec.py +++ b/test/test_systec.py @@ -226,10 +226,25 @@ def test_receive_own_messages(): ), ) - @staticmethod - def test_bus_passive_state(): + def test_bus_listen_only(self): + """ + Test Scope: + Listen-only mode of the SYS TEC interface. + Preconditions: + A mocked SYS TEC DLL. + Events: + Create a listen-only bus, try to send a message, switch + listen_only off, then switch it on again. + Evaluate: + The channel is initialized in listen-only mode, the state is PASSIVE, + listen_only is True and send raises CanOperationError without writing + a frame. After switching listen_only off, the channel is initialized + again in normal mode and the state is ACTIVE. After switching + listen_only on again, the channel is initialized in listen-only mode. + """ ucan.UcanInitCanEx2.reset_mock() - bus = can.Bus(interface="systec", channel=0, state=can.BusState.PASSIVE) + ucan.UcanWriteCanMsgEx.reset_mock() + bus = can.Bus(interface="systec", channel=0, listen_only=True) ucan.UcanInitCanEx2.assert_called_once_with( bus._ucan._handle, 0, @@ -244,6 +259,82 @@ def test_bus_passive_state(): DEFAULT_BUFFER_ENTRIES, ), ) + assert bus.state is can.BusState.PASSIVE + assert bus.listen_only + with self.assertRaises(can.CanOperationError): + bus.send(can.Message(arbitration_id=0x321)) + ucan.UcanWriteCanMsgEx.assert_not_called() + ucan.UcanInitCanEx2.reset_mock() + bus.listen_only = False + ucan.UcanInitCanEx2.assert_called_once_with( + bus._ucan._handle, + 0, + InitCanParam( + Mode.MODE_NORMAL, + Baudrate.BAUD_500kBit, + OutputControl.OCR_DEFAULT, + AMR_ALL, + ACR_ALL, + BaudrateEx.BAUDEX_USE_BTR01, + DEFAULT_BUFFER_ENTRIES, + DEFAULT_BUFFER_ENTRIES, + ), + ) + assert not bus.listen_only + assert bus.state is can.BusState.ACTIVE + ucan.UcanInitCanEx2.reset_mock() + bus.listen_only = True + assert ucan.UcanInitCanEx2.call_args.args[2].mode == Mode.MODE_LISTEN_ONLY + + def test_bus_passive_state(self): + """ + Test Scope: + The deprecated way to request listen-only mode with state PASSIVE. + Preconditions: + A mocked SYS TEC DLL. + Events: + Create a bus with state PASSIVE. + Evaluate: + A DeprecationWarning is emitted and the channel is initialized in + listen-only mode. + """ + ucan.UcanInitCanEx2.reset_mock() + with self.assertWarns(DeprecationWarning): + bus = can.Bus(interface="systec", channel=0, state=can.BusState.PASSIVE) + ucan.UcanInitCanEx2.assert_called_once_with( + bus._ucan._handle, + 0, + InitCanParam( + Mode.MODE_LISTEN_ONLY, + Baudrate.BAUD_500kBit, + OutputControl.OCR_DEFAULT, + AMR_ALL, + ACR_ALL, + BaudrateEx.BAUDEX_USE_BTR01, + DEFAULT_BUFFER_ENTRIES, + DEFAULT_BUFFER_ENTRIES, + ), + ) + + def test_listen_only_contradicts_state(self): + """ + Test Scope: + An explicit listen_only that contradicts the deprecated state + argument. + Preconditions: + A mocked SYS TEC DLL. + Events: + Create a bus with listen_only=False and state PASSIVE. + Evaluate: + A DeprecationWarning is emitted and ValueError is raised. + """ + with self.assertWarns(DeprecationWarning), self.assertRaises(ValueError): + can.Bus( + interface="systec", + channel=0, + listen_only=False, + state=can.BusState.PASSIVE, + ) @staticmethod def test_rx_buffer_entries(): diff --git a/test/test_vector.py b/test/test_vector.py index 5d074f614..57bf2ab19 100644 --- a/test/test_vector.py +++ b/test/test_vector.py @@ -80,6 +80,17 @@ def mock_xldriver() -> None: def test_listen_only_mocked(mock_xldriver) -> None: + """ + Test Scope: + Listen-only mode of the Vector interface. + Preconditions: + A mocked XL driver. + Events: + Create a listen-only bus and try to send a message. + Evaluate: + The channel output is set to silent mode, send raises + CanOperationError and no frame is passed to the driver. + """ bus = can.Bus(channel=0, interface="vector", listen_only=True, _testing=True) assert isinstance(bus, canlib.VectorBus) assert bus.protocol == can.CanProtocol.CAN_20 @@ -90,9 +101,141 @@ def test_listen_only_mocked(mock_xldriver) -> None: ) assert xlCanSetChannelOutput_args[2] == xldefine.XL_OutputMode.XL_OUTPUT_MODE_SILENT + msg = can.Message(arbitration_id=0x123, data=[1, 2, 3]) + with pytest.raises(can.CanOperationError): + bus.send(msg) + can.interfaces.vector.canlib.xldriver.xlCanTransmit.assert_not_called() + + +def test_listen_only_loopback_mocked(mock_xldriver) -> None: + """ + Test Scope: + Listen-only mode of the Vector interface with receive_own_messages. + Preconditions: + A mocked XL driver. + Events: + Create a listen-only bus with receive_own_messages and send a message. + Evaluate: + The message is passed to the driver. + """ + bus = can.Bus( + channel=0, + interface="vector", + listen_only=True, + receive_own_messages=True, + _testing=True, + ) + bus.send(can.Message(arbitration_id=0x123, data=[1, 2, 3])) + can.interfaces.vector.canlib.xldriver.xlCanTransmit.assert_called() + + +def test_listen_only_false_mocked(mock_xldriver) -> None: + """ + Test Scope: + An explicit listen_only=False on the Vector interface. + Preconditions: + A mocked XL driver. + Events: + Create a bus with listen_only=False. + Evaluate: + xlOpenPort is called with a permission mask requesting init access, and + the channel output is set to normal mode. + """ + requested = [] + + def xl_open_port_recording(*args): + requested.append(args[3].value) + return xlOpenPort(*args) + + canlib.xldriver.xlOpenPort.side_effect = xl_open_port_recording + bus = can.Bus(channel=0, interface="vector", listen_only=False, _testing=True) + + assert requested == [bus.mask] + canlib.xldriver.xlCanSetChannelOutput.assert_called_once_with( + bus.port_handle, bus.mask, xldefine.XL_OutputMode.XL_OUTPUT_MODE_NORMAL + ) + + +def test_listen_only_not_requested_mocked(mock_xldriver) -> None: + """ + Test Scope: + A Vector bus created without listen_only and without bit timing. + Preconditions: + A mocked XL driver. + Events: + Create a bus without listen_only. + Evaluate: + xlOpenPort is called without requesting init access, the output mode + is not written and listen_only reports False. + """ + requested = [] + + def xl_open_port_recording(*args): + requested.append(args[3].value) + return xlOpenPort(*args) + + canlib.xldriver.xlOpenPort.side_effect = xl_open_port_recording + bus = can.Bus(channel=0, interface="vector", _testing=True) + + assert requested == [0] + canlib.xldriver.xlCanSetChannelOutput.assert_not_called() + assert not bus.listen_only + + +@pytest.mark.parametrize("listen_only", [True, False]) +@pytest.mark.parametrize("output_mode", list(xldefine.XL_OutputMode)) +def test_listen_only_without_init_access_mocked( + mock_xldriver, monkeypatch, listen_only: bool, output_mode +) -> None: + """ + Test Scope: + listen_only=True and False on a Vector channel without init access. + Preconditions: + A mocked XL driver that grants no init access and a channel + configuration that reports the given output mode. + Events: + Create a bus with listen_only. + Evaluate: + The bus opens if the output mode matches the requested mode (SILENT for + True, NORMAL for False), otherwise CanInitializationError is raised; the + output mode is not written. + """ + can_params = VectorCanParams(0, 0, 0, 0, 0, output_mode, Mock()) + vcc = Mock(channel_index=0, bus_params=VectorBusParams(Mock(), can_params, Mock())) + monkeypatch.setattr(canlib, "get_channel_configs", lambda: [vcc]) + + def xl_open_port_without_init_access(*args): + xlOpenPort(*args) + args[3].value = 0 + return 0 + + canlib.xldriver.xlOpenPort.side_effect = xl_open_port_without_init_access + requested = "XL_OUTPUT_MODE_SILENT" if listen_only else "XL_OUTPUT_MODE_NORMAL" + if output_mode.name == requested: + can.Bus( + channel=0, interface="vector", listen_only=listen_only, _testing=True + ).shutdown() + else: + with pytest.raises(can.CanInitializationError): + can.Bus( + channel=0, interface="vector", listen_only=listen_only, _testing=True + ) + canlib.xldriver.xlCanSetChannelOutput.assert_not_called() + @pytest.mark.skipif(not XLDRIVER_FOUND, reason="Vector XL API is unavailable") def test_listen_only() -> None: + """ + Test Scope: + Listen-only mode with receive_own_messages on the real XL driver. + Preconditions: + A virtual Vector CAN channel. + Events: + Open the channel in listen-only mode with receive_own_messages, send a + message and receive. + Evaluate: + The sent message is received back. + """ bus = can.Bus( channel=0, serial=_find_virtual_can_serial(), diff --git a/test/test_viewer.py b/test/test_viewer.py index ef3a1d3d3..1b4765502 100644 --- a/test/test_viewer.py +++ b/test/test_viewer.py @@ -474,6 +474,18 @@ def test_pack_unpack(self): ) def test_parse_args(self): + """ + Test Scope: + Command-line argument parsing of the viewer script. + Preconditions: + None. + Events: + Parse bitrate, channel, decode, filter, interface and listen-only + arguments, the help option and an empty argument list. + Evaluate: + The parsed values match the arguments, the help option exits with + code 0 and an empty argument list exits with EINVAL. + """ parsed_args, _ = _parse_viewer_args(["-b", "250000"]) self.assertEqual(parsed_args.bitrate, 250000) @@ -576,6 +588,12 @@ def test_parse_args(self): parsed_args, _ = _parse_viewer_args(["--interface", "pcan"]) self.assertEqual(parsed_args.interface, "pcan") + parsed_args, _ = _parse_viewer_args(["--listen-only"]) + self.assertIs(parsed_args.listen_only, True) + + parsed_args, _ = _parse_viewer_args(["--no-listen-only"]) + self.assertIs(parsed_args.listen_only, False) + # Make sure it exits with the correct error code when displaying the help page # See: https://github.com/hardbyte/python-can/issues/427 with self.assertRaises(SystemExit) as cm: