33"""
44
55import contextlib
6+ import inspect
67import logging
78import threading
89from abc import ABC , abstractmethod
910from collections .abc import Callable , Iterator , Sequence
1011from enum import Enum , auto
1112from time import time
1213from types import TracebackType
13- from typing import Self , cast
14+ from typing import Any , Self , cast
1415
1516import can .typechecking
1617from can .broadcastmanager import CyclicSendTaskABC , ThreadBasedCyclicSendTask
18+ from can .exceptions import CanInterfaceNotImplementedError
1719from can .message import Message
1820
1921LOG = 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
0 commit comments