Skip to content

Commit bc70b2f

Browse files
authored
Add listen_only to can.Bus and BusABC and deprecate interface specific listen-only options (#2149)
1 parent c62a8ef commit bc70b2f

41 files changed

Lines changed: 1801 additions & 163 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎can/bus.py‎

Lines changed: 86 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,19 @@
33
"""
44

55
import contextlib
6+
import inspect
67
import logging
78
import threading
89
from abc import ABC, abstractmethod
910
from collections.abc import Callable, Iterator, Sequence
1011
from enum import Enum, auto
1112
from time import time
1213
from types import TracebackType
13-
from typing import Self, cast
14+
from typing import Any, Self, cast
1415

1516
import can.typechecking
1617
from can.broadcastmanager import CyclicSendTaskABC, ThreadBasedCyclicSendTask
18+
from can.exceptions import CanInterfaceNotImplementedError
1719
from can.message import Message
1820

1921
LOG = logging.getLogger(__name__)
@@ -56,12 +58,23 @@ class BusABC(ABC):
5658
#: Assume that no cleanup is needed until something was initialized
5759
_is_shutdown: bool = True
5860
_can_protocol: CanProtocol = CanProtocol.CAN_20
61+
_listen_only: bool = False
62+
63+
def __new__(cls, *args: Any, **kwargs: Any) -> Self:
64+
# reject listen-only mode before the subclass opens any driver or device
65+
if kwargs.get("listen_only") and not _accepts_listen_only(cls):
66+
raise CanInterfaceNotImplementedError(
67+
f"{cls.__name__} does not support listen-only mode"
68+
)
69+
return super().__new__(cls)
5970

6071
@abstractmethod
6172
def __init__(
6273
self,
6374
channel: can.typechecking.Channel,
6475
can_filters: can.typechecking.CanFilters | None = None,
76+
*,
77+
listen_only: bool | None = None,
6578
**kwargs: object,
6679
):
6780
"""Construct and open a CAN bus instance of the specified type.
@@ -75,12 +88,24 @@ def __init__(
7588
:param can_filters:
7689
See :meth:`~can.BusABC.set_filters` for details.
7790
91+
:param listen_only:
92+
If ``True``, open the bus in :ref:`listen-only mode <listen_only>`.
93+
If ``False``, open the bus in normal mode. ``None`` (the default)
94+
means that listen-only mode was not requested.
95+
:class:`~can.exceptions.CanInterfaceNotImplementedError` is raised
96+
if the interface does not support listen-only mode, and
97+
:class:`~can.exceptions.CanInitializationError` if it cannot be
98+
applied. :class:`~can.BusABC` does not apply the mode: a subclass that
99+
supports listen-only mode must declare ``listen_only`` in its own
100+
constructor and apply it.
101+
78102
:param dict kwargs:
79103
Any backend dependent configurations are passed in this dictionary
80104
81105
:raises ValueError: If parameters are out of range
82106
:raises ~can.exceptions.CanInterfaceNotImplementedError:
83-
If the driver cannot be accessed
107+
If the driver cannot be accessed, or if ``listen_only`` is ``True``
108+
and the interface does not support listen-only mode
84109
:raises ~can.exceptions.CanInitializationError:
85110
If the bus cannot be initialized
86111
"""
@@ -190,7 +215,8 @@ def send(self, msg: Message, timeout: float | None = None) -> None:
190215
None blocks indefinitely.
191216
192217
:raises ~can.exceptions.CanOperationError:
193-
If an error occurred while sending
218+
If an error occurred while sending, or if the bus was opened
219+
in :ref:`listen-only mode <listen_only>` without local loopback
194220
"""
195221
raise NotImplementedError("Trying to write to a readonly bus?")
196222

@@ -510,6 +536,28 @@ def protocol(self) -> CanProtocol:
510536
"""
511537
return self._can_protocol
512538

539+
@property
540+
def listen_only(self) -> bool:
541+
"""Whether this bus instance is in :ref:`listen-only mode <listen_only>`.
542+
543+
Interfaces that do not support listen-only mode return ``False``. If the
544+
bus was created with ``listen_only=None``, this property reports ``False``,
545+
meaning that listen-only mode was not requested; the mode of the channel
546+
is not read back from the driver.
547+
548+
Interfaces that can switch the mode at runtime allow setting this
549+
property to ``True`` or ``False``.
550+
551+
:raises NotImplementedError:
552+
When set, if the interface cannot switch listen-only mode at runtime.
553+
"""
554+
return self._listen_only
555+
556+
@listen_only.setter
557+
def listen_only(self, value: bool) -> None:
558+
"""Switch :ref:`listen-only mode <listen_only>` on or off at runtime."""
559+
raise NotImplementedError("Property is not implemented.")
560+
513561
@staticmethod
514562
def _detect_available_configs() -> Sequence[can.typechecking.AutoDetectedConfig]:
515563
"""Detect all configurations/channels that this interface could
@@ -536,3 +584,38 @@ class _SelfRemovingCyclicTask(CyclicSendTaskABC, ABC):
536584

537585
def stop(self, remove_task: bool = True) -> None:
538586
raise NotImplementedError()
587+
588+
589+
def _accepts_listen_only(bus_class: type["BusABC"]) -> bool:
590+
"""Check whether a constructor of ``bus_class`` declares ``listen_only``.
591+
592+
The constructors in the MRO are checked from the most derived one up to,
593+
but excluding, :meth:`BusABC.__init__`. The first one that declares
594+
``listen_only`` explicitly means support. A constructor that takes
595+
``**kwargs`` may forward ``listen_only`` to its base class, so the search
596+
continues there. A constructor that takes neither cannot receive
597+
``listen_only``. If a signature cannot be inspected, ``True`` is returned.
598+
"""
599+
for klass in bus_class.__mro__:
600+
if klass is BusABC:
601+
return False
602+
init = klass.__dict__.get("__init__")
603+
if init is None:
604+
continue
605+
try:
606+
parameters = inspect.signature(init).parameters
607+
except (TypeError, ValueError):
608+
return True
609+
parameter = parameters.get("listen_only")
610+
if parameter is not None and parameter.kind in (
611+
inspect.Parameter.POSITIONAL_OR_KEYWORD,
612+
inspect.Parameter.KEYWORD_ONLY,
613+
):
614+
return True
615+
# without **kwargs, this constructor can neither receive nor forward
616+
# listen_only, so base class constructors do not matter
617+
if not any(
618+
p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters.values()
619+
):
620+
return False
621+
return False

‎can/cli.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ def add_bus_arguments(
1212
parser: argparse.ArgumentParser,
1313
*,
1414
filter_arg: bool = False,
15+
listen_only_arg: bool = False,
1516
prefix: str | None = None,
1617
group_title: str | None = None,
1718
) -> None:
@@ -21,6 +22,8 @@ def add_bus_arguments(
2122
The argument parser to which the options will be added.
2223
:param filter_arg:
2324
Whether to include the filter argument.
25+
:param listen_only_arg:
26+
Whether to include the ``--listen-only``/``--no-listen-only`` argument.
2427
:param prefix:
2528
An optional prefix for the argument names, allowing configuration of multiple buses.
2629
:param group_title:
@@ -78,6 +81,20 @@ def add_bus_arguments(
7881
help="Activate CAN-FD support",
7982
)
8083

84+
if listen_only_arg:
85+
flags = [f"--{prefix}-listen-only"] if prefix else ["--listen-only"]
86+
dest = f"{prefix}_listen_only" if prefix else "listen_only"
87+
group.add_argument(
88+
*flags,
89+
dest=dest,
90+
default=argparse.SUPPRESS,
91+
action=argparse.BooleanOptionalAction,
92+
help="Open the bus in listen-only mode: receive only, never transmit "
93+
"frames, acknowledgements or error frames. "
94+
f"--no-{flags[0][2:]} opens the bus in normal mode, overriding a "
95+
"listen-only mode set in the configuration.",
96+
)
97+
8198
flags = [f"--{prefix}-data-bitrate"] if prefix else ["--data-bitrate"]
8299
dest = f"{prefix}_data_bitrate" if prefix else "data_bitrate"
83100
group.add_argument(
@@ -165,6 +182,7 @@ def create_bus_from_namespace(
165182
"interface",
166183
"bitrate",
167184
"fd",
185+
"listen_only",
168186
"data_bitrate",
169187
"can_filters",
170188
"timing",

‎can/interface.py‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from typing import Any, cast
1212

1313
from . import util
14-
from .bus import BusABC
14+
from .bus import BusABC, _accepts_listen_only
1515
from .exceptions import CanInterfaceNotImplementedError
1616
from .interfaces import BACKENDS
1717
from .typechecking import AutoDetectedConfig, Channel
@@ -68,6 +68,7 @@ def Bus( # noqa: N802
6868
interface: str | None = None,
6969
config_context: str | None = None,
7070
ignore_config: bool = False,
71+
listen_only: bool | None = None,
7172
**kwargs: Any,
7273
) -> BusABC:
7374
"""Create a new bus instance with configuration loading.
@@ -100,11 +101,19 @@ def Bus( # noqa: N802
100101
If ``True``, only the given arguments will be used for the bus instantiation. Existing
101102
configuration sources will be ignored.
102103
104+
:param listen_only:
105+
If ``True``, open the bus in :ref:`listen-only mode <listen_only>`.
106+
Set to ``None`` to let it be resolved from the default
107+
:ref:`configuration`; if the configuration does not set it either,
108+
listen-only mode is not requested.
109+
``listen_only=False`` is accepted by every interface.
110+
103111
:param kwargs:
104112
``interface`` specific keyword arguments.
105113
106114
:raises ~can.exceptions.CanInterfaceNotImplementedError:
107-
if the ``interface`` isn't recognized or cannot be loaded
115+
if the ``interface`` isn't recognized or cannot be loaded,
116+
or if it does not support listen-only mode and ``listen_only`` is ``True``
108117
109118
:raises ~can.exceptions.CanInitializationError:
110119
if the bus cannot be instantiated
@@ -118,13 +127,20 @@ def Bus( # noqa: N802
118127
kwargs["interface"] = interface
119128
if channel is not None:
120129
kwargs["channel"] = channel
130+
if listen_only is not None:
131+
kwargs["listen_only"] = listen_only
121132

122133
if not ignore_config:
123134
kwargs = util.load_config(config=kwargs, context=config_context)
124135

125136
# resolve the bus class to use for that interface
126137
cls = _get_class_for_interface(kwargs["interface"])
127138

139+
# drop listen_only=False for interfaces that cannot take the argument,
140+
# so that they keep working
141+
if not kwargs.get("listen_only", True) and not _accepts_listen_only(cls):
142+
del kwargs["listen_only"]
143+
128144
# remove the "interface" key, so it doesn't get passed to the backend
129145
del kwargs["interface"]
130146

‎can/interfaces/canalystii.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def __init__(
2727
timing: BitTiming | BitTimingFd | None = None,
2828
can_filters: CanFilters | None = None,
2929
rx_queue_size: int | None = None,
30-
**kwargs: dict[str, Any],
30+
**kwargs: Any,
3131
):
3232
"""
3333

‎can/interfaces/cantact.py‎

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,15 @@
1212
from can.exceptions import (
1313
CanInitializationError,
1414
CanInterfaceNotImplementedError,
15+
CanOperationError,
1516
error_check,
1617
)
1718
from can.typechecking import AutoDetectedConfig
18-
from can.util import check_or_adjust_timing_clock, deprecated_args_alias
19+
from can.util import (
20+
_warn_listen_only_deprecated,
21+
check_or_adjust_timing_clock,
22+
deprecated_args_alias,
23+
)
1924

2025
logger = logging.getLogger(__name__)
2126

@@ -54,24 +59,43 @@ def __init__(
5459
channel: int,
5560
bitrate: int = 500_000,
5661
poll_interval: float = 0.01,
57-
monitor: bool = False,
62+
monitor: bool | None = None,
5863
timing: BitTiming | BitTimingFd | None = None,
64+
listen_only: bool | None = None,
5965
**kwargs: Any,
6066
) -> None:
6167
"""
6268
:param int channel:
6369
Channel number (zero indexed, labeled on multi-channel devices)
6470
:param int bitrate:
6571
Bitrate in bits/s
66-
:param bool monitor:
67-
If true, operate in listen-only monitoring mode
72+
:param monitor:
73+
If true, operate in listen-only monitoring mode.
74+
If ``listen_only`` is also given with a contradicting value,
75+
:class:`ValueError` is raised.
76+
77+
.. deprecated:: 4.7.0
78+
Use ``listen_only`` instead.
6879
:param timing:
6980
Optional :class:`~can.BitTiming` instance to use for custom bit timing setting.
7081
If this argument is set then it overrides the bitrate argument. The
7182
`f_clock` value of the timing instance must be set to 24_000_000 (24MHz)
7283
for standard CAN.
7384
CAN FD and the :class:`~can.BitTimingFd` class are not supported.
85+
:param listen_only:
86+
If true, operate in listen-only monitoring mode. In this mode,
87+
:meth:`send` raises :class:`~can.exceptions.CanOperationError`.
88+
If ``None`` (the default), the monitor mode of the device is left
89+
unchanged.
7490
"""
91+
if monitor is not None:
92+
_warn_listen_only_deprecated("The 'monitor' argument", "'listen_only'")
93+
if listen_only is not None and listen_only != bool(monitor):
94+
raise ValueError(
95+
f"monitor={monitor!r} contradicts listen_only={listen_only!r}"
96+
)
97+
listen_only = bool(monitor)
98+
self._listen_only = bool(listen_only)
7599

76100
if kwargs.get("_testing", False):
77101
self.interface = MockInterface()
@@ -112,7 +136,8 @@ def __init__(
112136
self.interface.set_bitrate(int(channel), int(bitrate))
113137

114138
self.interface.set_enabled(int(channel), True)
115-
self.interface.set_monitor(int(channel), monitor)
139+
if listen_only is not None:
140+
self.interface.set_monitor(int(channel), listen_only)
116141
self.interface.start()
117142

118143
super().__init__(
@@ -145,6 +170,8 @@ def _recv_internal(self, timeout: float | None) -> tuple[Message | None, bool]:
145170
return msg, False
146171

147172
def send(self, msg: Message, timeout: float | None = None) -> None:
173+
if self._listen_only:
174+
raise CanOperationError("Cannot send in listen-only mode")
148175
with error_check("Cannot send message"):
149176
self.interface.send(
150177
self.channel,

0 commit comments

Comments
 (0)