Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 | None = None,
**kwargs: object,
):
"""Construct and open a CAN bus instance of the specified type.
Expand All @@ -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 <listen_only>`.
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
"""
Expand Down Expand Up @@ -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 <listen_only>` without local loopback
"""
raise NotImplementedError("Trying to write to a readonly bus?")

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

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

# 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"]

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
37 changes: 32 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,43 @@ 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:
"""
: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 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()
Expand Down Expand Up @@ -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__(
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading