diff --git a/can/bus.py b/can/bus.py index 72cd208ea..f637a760c 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 = False, **kwargs: object, ): """Construct and open a CAN bus instance of the specified type. @@ -75,12 +88,26 @@ 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 `: + the bus only receives and never puts frames, acknowledgements or + error frames on the wire, and :meth:`~can.BusABC.send` raises + :class:`~can.exceptions.CanOperationError`. + A subclass supports listen-only mode only if its constructor + declares ``listen_only`` as an explicit parameter, or forwards + ``**kwargs`` to a base class constructor that does (decorators must + use :func:`functools.wraps`). For any other subclass, + ``listen_only=True`` raises + :class:`~can.exceptions.CanInterfaceNotImplementedError` before its + constructor runs. ``False`` is always accepted. + :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 +217,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 ` """ raise NotImplementedError("Trying to write to a readonly bus?") @@ -510,6 +538,26 @@ 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``. Subclasses + that support it must make this property report the current mode. + """ + return self._listen_only + + @listen_only.setter + def listen_only(self, value: bool) -> None: + """Switch :ref:`listen-only mode ` on or off at runtime. + + :param value: + ``True`` to enter listen-only mode, ``False`` to leave it. + :raises NotImplementedError: + If the interface cannot switch listen-only mode 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..1150f3685 100644 --- a/can/cli.py +++ b/can/cli.py @@ -78,6 +78,17 @@ def add_bus_arguments( help="Activate CAN-FD support", ) + 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="store_true", + help="Open the bus in listen-only mode: receive only, never transmit " + "frames, acknowledgements or error frames.", + ) + 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 +176,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..0bde89961 100644 --- a/can/interface.py +++ b/can/interface.py @@ -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,18 @@ 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`, falling back to ``False``. + The resolved value is always passed to the bus class. + :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,10 +126,14 @@ 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) + kwargs.setdefault("listen_only", False) + # resolve the bus class to use for that interface cls = _get_class_for_interface(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..2051d8196 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,8 @@ def __init__( channel: int, bitrate: int = 500_000, poll_interval: float = 0.01, - monitor: bool = False, timing: BitTiming | BitTimingFd | None = None, + listen_only: bool = False, **kwargs: Any, ) -> None: """ @@ -63,15 +68,23 @@ 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 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 "monitor" in kwargs: + _warn_listen_only_deprecated("The 'monitor' argument") + monitor = bool(kwargs["monitor"]) + if listen_only and not monitor: + raise ValueError("'listen_only' and 'monitor' contradict each other") + listen_only = listen_only or monitor + self._listen_only = listen_only if kwargs.get("_testing", False): self.interface = MockInterface() @@ -112,7 +125,7 @@ def __init__( self.interface.set_bitrate(int(channel), int(bitrate)) self.interface.set_enabled(int(channel), True) - self.interface.set_monitor(int(channel), monitor) + self.interface.set_monitor(int(channel), listen_only) self.interface.start() super().__init__( @@ -145,6 +158,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..615038c52 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 @@ -376,6 +380,7 @@ def __init__( channel: int, can_filters: CanFilters | None = None, timing: BitTiming | BitTimingFd | None = None, + listen_only: bool = False, **kwargs, ): """ @@ -413,10 +418,9 @@ def __init__( In this case, the bit will be sampled three quanta in a row, with the last sample being taken in the edge between TSEG1 and TSEG2. Three samples should only be used for relatively slow baudrates. - - :param bool driver_mode: - Silent or normal. - + :param bool listen_only: + If True, open the channel in silent mode. In silent mode, + :meth:`send` raises :class:`~can.exceptions.CanOperationError`. :param bool single_handle: Use one Kvaser CANLIB bus handle for both reading and writing. This can be set if reading and/or writing is done from one thread. @@ -449,7 +453,15 @@ 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") + silent = kwargs["driver_mode"] == DRIVER_MODE_SILENT + if listen_only and not silent: + raise ValueError( + "'listen_only' and 'driver_mode' contradict each other" + ) + listen_only = listen_only or silent + self._listen_only = listen_only single_handle = kwargs.get("single_handle", False) receive_own_messages = kwargs.get("receive_own_messages", False) exclusive = kwargs.get("exclusive", False) @@ -579,9 +591,7 @@ def __init__( self._write_handle = canOpenChannel(channel, flags_) can_driver_mode = ( - canstat.canDRIVER_SILENT - if driver_mode == DRIVER_MODE_SILENT - else canstat.canDRIVER_NORMAL + canstat.canDRIVER_SILENT if listen_only else canstat.canDRIVER_NORMAL ) canSetBusOutputControl(self._write_handle, can_driver_mode) @@ -708,6 +718,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..39f33f6e0 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 = False, **kwargs: Any, ) -> None: """ @@ -84,6 +85,10 @@ 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`. + :raises ~can.exceptions.CanInitializationError: If starting communication fails """ @@ -103,6 +108,7 @@ def __init__( self.channel_info = "NI-XNET: " + channel self.poll_interval = poll_interval + self._listen_only = 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 +128,7 @@ def __init__( self._interface = self._session_send.intf # set interface properties - self._interface.can_lstn_only = kwargs.get("listen_only", False) + self._interface.can_lstn_only = listen_only self._interface.echo_tx = receive_own_messages self._interface.bus_err_to_in_strm = True @@ -267,7 +273,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 a11a7fa6c..ce1190f50 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, @@ -121,10 +126,10 @@ def __init__( self, channel: str = "PCAN_USBBUS1", device_id: int | None = None, - state: BusState = BusState.ACTIVE, timing: BitTiming | BitTimingFd | None = None, bitrate: int = 500000, receive_own_messages: bool = False, + listen_only: bool = False, **kwargs: Any, ): """A PCAN USB interface to CAN. @@ -146,10 +151,6 @@ def __init__( first one that matches the parameter value. If no device is found, an exception is raised. - :param can.bus.BusState state: - BusState of the channel. - Default is ACTIVE - :param timing: An instance of :class:`~can.BitTiming` or :class:`~can.BitTimingFd` to specify the bit timing parameters for the PCAN interface. If this parameter @@ -170,6 +171,12 @@ 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`. + :param bool fd: Should the Bus be initialized in CAN-FD mode. @@ -268,10 +275,15 @@ 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") + state = kwargs.pop("state", None) + 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") + if listen_only and state is BusState.ACTIVE: + raise ValueError("'listen_only' and 'state' contradict each other") + self._listen_only = listen_only or state is BusState.PASSIVE + self._apply_listen_only_mode() if isinstance(timing, BitTiming): timing = check_or_adjust_timing_clock(timing, VALID_PCAN_CAN_CLOCKS) @@ -356,7 +368,6 @@ def __init__( super().__init__( channel=channel, - state=state, bitrate=bitrate, **kwargs, ) @@ -605,6 +616,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 @@ -689,27 +702,37 @@ 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._listen_only = value + self._apply_listen_only_mode() + @property def state(self): - return self._state + 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 + if new_state is BusState.PASSIVE: + _warn_listen_only_deprecated( + "Setting the state to BusState.PASSIVE", "'bus.listen_only = True'" ) + if new_state is BusState.ACTIVE or new_state is BusState.PASSIVE: + self.listen_only = new_state is BusState.PASSIVE - 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 - ) + def _apply_listen_only_mode(self) -> 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". + self.m_objPCANBasic.SetValue( + self.m_PcanHandle, + PCAN_LISTEN_ONLY, + PCAN_PARAMETER_ON if self._listen_only else PCAN_PARAMETER_OFF, + ) @staticmethod def _detect_available_configs(): diff --git a/can/interfaces/seeedstudio/seeedstudio.py b/can/interfaces/seeedstudio/seeedstudio.py index b7b0e46ab..dd62d2e60 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 = False, + **kwargs: Any, + ) -> None: """ :param str channel: The serial device to open. For example "/dev/ttyS1" or @@ -81,7 +85,7 @@ def __init__( STD or EXT, to select standard or extended messages :param operation_mode - normal, loopback, silent or loopback_and_silent. + normal or loopback. :param bitrate CAN bus bit rate, selected from available list. @@ -92,6 +96,11 @@ def __init__( zero or more than one filter is provided, software-based filtering will be used. Defaults to None (no filtering). + :param bool listen_only: + If True, open the device in silent mode. In silent mode, + :meth:`send` raises :class:`~can.exceptions.CanOperationError`. + + :raises ValueError: If ``listen_only`` is combined with loopback mode. :raises can.CanInitializationError: If the given parameters are invalid. :raises can.CanInterfaceNotImplementedError: If the serial module is not installed. """ @@ -113,6 +122,14 @@ def __init__( self.bit_rate = bitrate self.frame_type = frame_type + if operation_mode in ("silent", "loopback_and_silent"): + _warn_listen_only_deprecated(f"The operation_mode '{operation_mode}'") + listen_only = True + elif listen_only and operation_mode == "loopback": + raise ValueError("'listen_only' cannot be combined with loopback mode") + if listen_only: + operation_mode = "silent" + self._listen_only = listen_only self.op_mode = operation_mode self.filter_id = struct.pack(" 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..18faaca1d 100644 --- a/can/interfaces/systec/ucanbus.py +++ b/can/interfaces/systec/ucanbus.py @@ -10,6 +10,7 @@ CanProtocol, Message, ) +from can.util import _warn_listen_only_deprecated from .constants import * from .exceptions import UcanException @@ -57,7 +58,7 @@ class UcanBus(BusABC): 1000000: Baudrate.BAUD_1MBit, } - def __init__(self, channel, can_filters=None, **kwargs): + def __init__(self, channel, can_filters=None, listen_only: bool = False, **kwargs): """ :param int channel: The Channel id to create this bus with. @@ -65,6 +66,12 @@ def __init__(self, channel, can_filters=None, **kwargs): :param list can_filters: See :meth:`can.BusABC.set_filters`. + :param bool 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`. + Backend Configuration :param int bitrate: @@ -77,10 +84,6 @@ def __init__(self, channel, can_filters=None, **kwargs): be used, in case only one module is connected to the computer). Default is 255. - :param can.bus.BusState state: - BusState of the channel. - Default is ACTIVE. - :param bool receive_own_messages: If messages transmitted should also be received back. Default is False. @@ -121,17 +124,20 @@ 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") + if listen_only and state is BusState.ACTIVE: + raise ValueError("'listen_only' and 'state' contradict each other") + self._listen_only = listen_only or state is BusState.PASSIVE # 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 +202,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 +310,38 @@ 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 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 + if new_state is BusState.PASSIVE: + _warn_listen_only_deprecated( + "Setting the state to BusState.PASSIVE", "'bus.listen_only = True'" + ) + 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..94d129f27 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 = False, **kwargs: Any, ) -> None: """ @@ -150,7 +151,8 @@ 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 mode. In listen only mode, + :meth:`send` raises :class:`~can.exceptions.CanOperationError`. :raise ~can.exceptions.CanInterfaceNotImplementedError: If the current operating system is not supported or the driver could not be loaded. @@ -836,6 +838,8 @@ def handle_canfd_event(self, event: xlclass.XLcanRxEvent) -> None: """ def send(self, msg: Message, timeout: float | None = None) -> None: + if self._listen_only: + 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..25949f33e 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 = False, **kwargs: Any, ) -> None: """ @@ -84,12 +85,16 @@ 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. """ super().__init__( channel=channel, receive_own_messages=receive_own_messages, + listen_only=listen_only, **kwargs, ) @@ -99,6 +104,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 = listen_only self._open = True with channels_lock: @@ -129,6 +135,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..6e09f93fc 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,14 +70,9 @@ 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) @@ -90,19 +86,23 @@ def _parse_logger_args( raise SystemExit(errno.EINVAL) results, unknown_args = parser.parse_known_args(args) + if results.active and "listen_only" in results: + parser.error("argument --active: not allowed with argument --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", replacement=None) 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/util.py b/can/util.py index 27f421f42..329edae39 100644 --- a/can/util.py +++ b/can/util.py @@ -241,6 +241,9 @@ 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: + 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 +428,25 @@ 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." + warnings.warn(message, DeprecationWarning, stacklevel=3) + + T2 = TypeVar("T2", BitTiming, BitTimingFd) diff --git a/doc/bus.rst b/doc/bus.rst index f63c244c2..849d7c513 100644 --- a/doc/bus.rst +++ b/doc/bus.rst @@ -74,6 +74,51 @@ 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 opened with ``listen_only=True`` only receives: it never puts frames, +acknowledgements or error frames on the wire, which makes it safe for passively +logging a live bus. Calling :meth:`~can.BusABC.send` on such a bus raises +:class:`~can.exceptions.CanOperationError`. + +Listen-only mode corresponds to the bus monitoring mode of ISO 11898-1 (§10.14): +the node receives frames but never drives the bus dominant, so it sends no +acknowledgements, error flags or overload flags. It is not the restricted +operation mode (§10.15), which still acknowledges frames. + +.. code-block:: python + + with can.Bus(interface="vector", channel=0, listen_only=True) as bus: + for msg in bus: + print(msg) + +Listen-only mode is selected when the bus is created. It can also be set +in a :ref:`configuration file ` with ``listen_only = True``, and the +command line tools accept ``--listen-only``. + +The :attr:`~can.BusABC.listen_only` property tells whether a bus is in listen-only +mode. Interfaces that can switch the mode at runtime, currently ``pcan`` and +``systec``, also allow setting it. + +An interface supports listen-only mode only if its constructor declares a +``listen_only`` parameter, or forwards ``**kwargs`` to a base class constructor +that does. For any other interface, ``listen_only=True`` raises +:class:`~can.exceptions.CanInterfaceNotImplementedError` before the bus is +created, see :class:`~can.BusABC`. Of the built-in interfaces, ``cantact``, +``kvaser``, ``nixnet``, ``pcan``, ``seeedstudio``, ``slcan``, ``systec``, +``vector`` and ``virtual`` support it. + +.. 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 ``BusState.PASSIVE`` for + ``pcan`` and ``systec``, and the ``--passive`` and ``--active`` arguments of + ``can.logger``. + Bus API ''''''' diff --git a/doc/changelog.d/2149.added.rst b/doc/changelog.d/2149.added.rst new file mode 100644 index 000000000..f74aafc02 --- /dev/null +++ b/doc/changelog.d/2149.added.rst @@ -0,0 +1 @@ +Added the ``listen_only`` argument and property to :class:`can.BusABC` and ``--listen-only`` to the CLI tools, deprecating the interface specific alternatives; ``send()`` on a listen-only bus now raises :class:`~can.exceptions.CanOperationError` on all built-in interfaces, interfaces whose constructor does not declare ``listen_only`` reject ``listen_only=True`` with :class:`~can.exceptions.CanInterfaceNotImplementedError`, and :func:`can.Bus` always passes ``listen_only``, so third-party interfaces must accept it. diff --git a/doc/interfaces/cantact.rst b/doc/interfaces/cantact.rst index dc9667218..faf366a38 100644 --- a/doc/interfaces/cantact.rst +++ b/doc/interfaces/cantact.rst @@ -3,6 +3,9 @@ CANtact CAN Interface Interface for CANtact devices from Linklayer Labs +.. deprecated:: 4.7.0 + The ``monitor`` argument is deprecated. Use ``listen_only`` instead. + .. autoclass:: can.interfaces.cantact.CantactBus :show-inheritance: :members: diff --git a/doc/interfaces/kvaser.rst b/doc/interfaces/kvaser.rst index f2c93f85b..036b8bf2c 100644 --- a/doc/interfaces/kvaser.rst +++ b/doc/interfaces/kvaser.rst @@ -9,6 +9,9 @@ Linux). Bus --- +.. deprecated:: 4.7.0 + The ``driver_mode`` argument is deprecated. Use ``listen_only`` instead. + .. autoclass:: can.interfaces.kvaser.canlib.KvaserBus :members: :exclude-members: get_stats diff --git a/doc/interfaces/pcan.rst b/doc/interfaces/pcan.rst index 48e7dba05..827de44f3 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 ``can.bus.BusState.ACTIVE``) - BusState of the channel + BusState of the channel. + Deprecated since 4.7.0, use ``listen_only`` instead. + In ``BusState.PASSIVE``, sending raises :class:`~can.exceptions.CanOperationError`. ``bitrate`` (default ``500000``) Channel bitrate diff --git a/doc/interfaces/seeedstudio.rst b/doc/interfaces/seeedstudio.rst index 173944e0d..28acf472f 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=False) CHANNEL The serial port created by the USB device when connected. @@ -60,8 +61,12 @@ 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`` instead) + +LISTEN_ONLY + Open the device in :ref:`listen-only mode `. Cannot be combined + with OPERATIONMODE "loopback". BITRATE - 1000000 diff --git a/doc/interfaces/systec.rst b/doc/interfaces/systec.rst index 6b04fdfe0..e8f3f5d3a 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 False) Open the channel in :ref:`listen-only mode ` +* ``state`` (default BusState.ACTIVE) BusState of the channel. + Deprecated since 4.7.0, use ``listen_only`` instead. + In ``BusState.PASSIVE``, sending raises :class:`~can.exceptions.CanOperationError`. * ``receive_own_messages`` (default False) If messages transmitted should also be received back diff --git a/doc/interfaces/vector.rst b/doc/interfaces/vector.rst index d3e2bed45..485c1d9b9 100644 --- a/doc/interfaces/vector.rst +++ b/doc/interfaces/vector.rst @@ -29,6 +29,11 @@ application named "python-can": VectorBus --------- +.. versionchanged:: 4.7.0 + In :ref:`listen-only mode `, :meth:`~can.interfaces.vector.VectorBus.send` + raises :class:`~can.exceptions.CanOperationError`. Previously, the message was + accepted and only received back locally. + .. autoclass:: can.interfaces.vector.VectorBus :show-inheritance: :member-order: bysource diff --git a/test/test_bus.py b/test/test_bus.py index 6a09a6deb..b4a763a19 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,77 @@ 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()) + + @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..d9fc53573 100644 --- a/test/test_cantact.py +++ b/test/test_cantact.py @@ -57,6 +57,43 @@ 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() + 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. + Evaluate: + A DeprecationWarning is emitted and monitor mode is switched on. + """ + cantact.MockInterface.set_monitor.reset_mock() + with self.assertWarns(DeprecationWarning): + can.Bus(channel=0, interface="cantact", monitor=True, _testing=True) + + cantact.MockInterface.set_monitor.assert_called_with(0, 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..a18783fea 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -97,6 +97,29 @@ 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 argument, with and without prefix. + Preconditions: + A mocked can.Bus. + Events: + Parse --listen-only and --test-listen-only and create a bus from + each namespace. + Evaluate: + Both buses are created with listen_only=True. + """ + for prefix, flag in ((None, "--listen-only"), ("test", "--test-listen-only")): + mock_bus.reset_mock() + parser = argparse.ArgumentParser() + add_bus_arguments(parser, prefix=prefix) + + namespace = parser.parse_args([flag]) + create_bus_from_namespace(namespace, prefix=prefix) + + self.assertIs(mock_bus.call_args.kwargs["listen_only"], True) + @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..de7cc5ff8 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,38 @@ 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. + 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..49098d0ae 100644 --- a/test/test_kvaser.py +++ b/test/test_kvaser.py @@ -319,6 +319,54 @@ 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 and try to send a message. + Evaluate: + The bus output is set to silent, send raises CanOperationError + and no frame is written. + """ + canlib.canSetBusOutputControl.reset_mock() + bus = can.Bus(interface="kvaser", channel=0, listen_only=True) + + canlib.canSetBusOutputControl.assert_called_once() + self.assertEqual( + canlib.canSetBusOutputControl.call_args[0][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_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..be3dff757 100644 --- a/test/test_load_config.py +++ b/test/test_load_config.py @@ -111,6 +111,28 @@ 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". + Evaluate: + The loaded listen_only value is the matching bool. + """ + 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) + if __name__ == "__main__": unittest.main() diff --git a/test/test_logger.py b/test/test_logger.py index 41778ab6a..b0ed2ab78 100644 --- a/test/test_logger.py +++ b/test/test_logger.py @@ -66,22 +66,65 @@ 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 virtual bus and logger. + Events: + Run the logger with --active. + Evaluate: + A DeprecationWarning is emitted, the bus is created in normal mode + and its state is left untouched. + """ self.mock_virtual_bus.recv = Mock(side_effect=[self.testmsg, KeyboardInterrupt]) + state_before = self.mock_virtual_bus.state sys.argv = self.baseargs + ["--active"] - 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.ACTIVE) + self.assertIs(self.MockVirtualBus.call_args.kwargs["listen_only"], False) + self.assertIs(self.mock_virtual_bus.state, state_before) 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_active_not_allowed_with_listen_only(self): + """ + Test Scope: + Combining the deprecated --active argument with --listen-only. + Preconditions: + A mocked virtual bus. + Events: + Run the logger with --active and --listen-only. + Evaluate: + The logger exits with a usage error and no bus is created. + """ + sys.argv = self.baseargs + ["--active", "--listen-only"] + 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 9cd208113..7b71a9346 100644 --- a/test/test_pcan.py +++ b/test/test_pcan.py @@ -63,7 +63,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)]) @@ -367,28 +377,102 @@ def test_shutdown(self) -> None: self.bus.shutdown() self.mock_pcan.Uninitialize.assert_called_once_with(PCAN_USBBUS1) - @parameterized.expand( - [ - ("active", BusState.ACTIVE, PCAN_PARAMETER_OFF), - ("passive", BusState.PASSIVE, PCAN_PARAMETER_ON), - ] - ) - def test_state(self, name, bus_state: BusState, expected_parameter) -> None: - with self.subTest(name): - self.bus = can.Bus(interface="pcan") + def test_state_active(self) -> None: + """ + Test Scope: + Setting the state of a PCAN bus to ACTIVE. + Preconditions: + A mocked PCAN-Basic API. + Events: + Set the state to BusState.ACTIVE. + Evaluate: + Listen-only mode is switched off. + """ + 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] - self.assertEqual( - last_call_args_list, - (PCAN_USBBUS1, PCAN_LISTEN_ONLY, expected_parameter), - ) + self.bus.state = BusState.ACTIVE + self.assertEqual( + self.mock_pcan.SetValue.call_args[0], + (PCAN_USBBUS1, PCAN_LISTEN_ONLY, PCAN_PARAMETER_OFF), + ) - 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_passive_deprecated(self) -> None: + """ + Test Scope: + The deprecated way to enter listen-only mode by setting the state. + Preconditions: + A mocked PCAN-Basic API. + Events: + Set the state to BusState.PASSIVE. + Evaluate: + A DeprecationWarning is emitted and listen-only mode is switched on. + """ + self.bus = can.Bus(interface="pcan") + + with self.assertWarns(DeprecationWarning): + self.bus.state = BusState.PASSIVE + self.assertEqual( + self.mock_pcan.SetValue.call_args[0], + (PCAN_USBBUS1, PCAN_LISTEN_ONLY, PCAN_PARAMETER_ON), + ) + + 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. + Evaluate: + Both emit a DeprecationWarning and report the requested state and + listen_only value, and the PASSIVE bus can still be switched to + ACTIVE, which turns listen_only off. + """ + 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 = can.Bus(interface="pcan", state=BusState.PASSIVE) + assert bus.state == BusState.PASSIVE + assert bus.listen_only + bus.state = BusState.ACTIVE + assert bus.state == BusState.ACTIVE + assert not 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_detect_available_configs(self) -> None: if platform.system() == "Darwin": 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..5fd001720 100644 --- a/test/test_systec.py +++ b/test/test_systec.py @@ -226,10 +226,61 @@ 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, then switch + listen_only off. + 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 state is ACTIVE. + """ + ucan.UcanInitCanEx2.reset_mock() + ucan.UcanWriteCanMsgEx.reset_mock() + bus = can.Bus(interface="systec", channel=0, listen_only=True) + 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, + ), + ) + 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() + bus.listen_only = False + assert not bus.listen_only + assert bus.state is can.BusState.ACTIVE + + 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() - bus = can.Bus(interface="systec", channel=0, state=can.BusState.PASSIVE) + 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, diff --git a/test/test_vector.py b/test/test_vector.py index 5d074f614..02e8333db 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,14 +101,28 @@ 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() + @pytest.mark.skipif(not XLDRIVER_FOUND, reason="Vector XL API is unavailable") def test_listen_only() -> None: + """ + Test Scope: + Listen-only mode of the Vector interface with the real XL driver. + Preconditions: + A virtual Vector CAN channel. + Events: + Open the channel in listen-only mode and try to send a message. + Evaluate: + Send raises CanOperationError. + """ bus = can.Bus( channel=0, serial=_find_virtual_can_serial(), interface="vector", - receive_own_messages=True, listen_only=True, ) assert isinstance(bus, canlib.VectorBus) @@ -107,12 +132,8 @@ def test_listen_only() -> None: arbitration_id=0xC0FFEF, data=[1, 2, 3, 4, 5, 6, 7, 8], is_extended_id=True ) - bus.send(msg) - - received_msg = bus.recv() - - assert received_msg.arbitration_id == msg.arbitration_id - assert received_msg.data == msg.data + with pytest.raises(can.CanOperationError): + bus.send(msg) bus.shutdown()