Skip to content
89 changes: 86 additions & 3 deletions can/bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,19 @@
"""

import contextlib
import inspect
import logging
import threading
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterator, Sequence
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__)
Expand Down Expand Up @@ -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.
Expand All @@ -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 <listen_only>`:
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
"""
Expand Down Expand Up @@ -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 <listen_only>`
"""
raise NotImplementedError("Trying to write to a readonly bus?")

Expand Down Expand Up @@ -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 <listen_only>`.

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 <listen_only>` 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
Expand All @@ -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
12 changes: 12 additions & 0 deletions can/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -165,6 +176,7 @@ def create_bus_from_namespace(
"interface",
"bitrate",
"fd",
"listen_only",
"data_bitrate",
"can_filters",
"timing",
Expand Down
14 changes: 13 additions & 1 deletion can/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 <listen_only>`.
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
Expand All @@ -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"])

Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/canalystii.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
):
"""

Expand Down
25 changes: 20 additions & 5 deletions can/interfaces/cantact.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -54,24 +59,32 @@ 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:
"""
:param int channel:
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()
Expand Down Expand Up @@ -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__(
Expand Down Expand Up @@ -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,
Expand Down
30 changes: 21 additions & 9 deletions can/interfaces/kvaser/canlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -376,6 +380,7 @@ def __init__(
channel: int,
can_filters: CanFilters | None = None,
timing: BitTiming | BitTimingFd | None = None,
listen_only: bool = False,
**kwargs,
):
"""
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading