remotivelabs.broker.filters

It is possible to filter frames and signals using filter predicates. A filter predicate is any callable that takes a remotivelabs.broker.frame.FrameInfo or remotivelabs.broker.signal.SignalInfo object and returns a boolean indicating whether the object matches the filter criteria.

All filters have an exclude flag to indicate whether matches should be excluded (True) or included (False, default). Filters are callable and can be passed to Python built-in functions that expect a predicate, such as filter(), any(), or all(). The snippet below shows examples using filter():

Filter Strategy:

The filter_recursive() function applies frame and signal filters with context-dependent behavior. Frame filtering determines eligibility, then signal filtering applies differently based on frame inclusion: included frames start with all signals (exclude-only), excluded frames require explicit signal inclusion. Exclusion filters always take priority over inclusion filters.

Examples:

from remotivelabs.broker import FrameInfo, SignalInfo
from remotivelabs.broker.filters import (
    AllFramesFilter,
    E2eSignalsFilter,
    FrameFilter,
    ReceiverFilter,
    SenderFilter,
    SignalFilter,
    filter_recursive,
    is_frame_filter,
    is_frame_signal_filter,
    is_signal_filter,
)

# assume frames and signals are populated elsewhere
frames: list[FrameInfo] = []
signals: list[SignalInfo] = []

# Example 1: Include all frames
all_frames_filter = AllFramesFilter()
filtered_frames = list(filter(all_frames_filter, frames))

# Example 2: Include all frames but exclude a specific frame
frame_exclude_filter = FrameFilter(frame_name="Frame1", exclude=True)
filtered_frames = list(filter(frame_exclude_filter, frames))

# Example 3: Filter frames sent by a specific ECU
sender_filter = SenderFilter(ecu_name="ECU1")
filtered_frames = list(filter(sender_filter, frames))

# Example 4: Filter frames received by a specific ECU, excluding one signal
receiver_filter = ReceiverFilter(ecu_name="ECU2")
signal_exclude_filter = SignalFilter(signal_name="SignalA", exclude=True)
filtered_frames = list(filter(receiver_filter, frames))
filtered_signals = list(filter(signal_exclude_filter, signals))

# Example 5: Chaining filters
frame_include = FrameFilter(frame_name="FrameA")
frame_exclude = FrameFilter(frame_name="FrameB", exclude=True)
filtered_frames = list(filter(frame_exclude, filter(frame_include, frames)))

# Example 6: Combining inclusion and exclusion with AllFramesFilter and FrameFilter
all_frames_filter = AllFramesFilter()
frame_exclude_filter = FrameFilter(frame_name="FrameC", exclude=True)
filtered_frames = list(filter(frame_exclude_filter, filter(all_frames_filter, frames)))

# Example 7: Recursive filtering of signals (SignalInfos) in frames (FrameInfos)
filtered_frames = [
    filtered_frame
    for frame in frames
    if (filtered_frame := filter_recursive(frame, filters=[all_frames_filter, signal_exclude_filter])) is not None
]

# Example 8: Drop E2E bookkeeping signals (CRC + counter) while keeping the rest of the frame
e2e_drop = E2eSignalsFilter(exclude=True)
filtered_frames = [
    filtered_frame for frame in frames if (filtered_frame := filter_recursive(frame, filters=[all_frames_filter, e2e_drop])) is not None
]

# Example 9: Type checking filters
assert is_frame_filter(all_frames_filter)  # works with frames
assert not is_signal_filter(all_frames_filter)  # doesn't work with signals

assert not is_frame_filter(signal_exclude_filter)  # doesn't work with frames
assert is_signal_filter(signal_exclude_filter)  # works with signals

assert is_frame_filter(sender_filter)  # works with frames
assert is_signal_filter(sender_filter)  # works with signals

assert is_frame_signal_filter(e2e_drop)  # evaluates a signal in the context of its frame
assert not is_frame_filter(e2e_drop)
assert not is_signal_filter(e2e_drop)

# Example 10: All frames sent by an ECU, except a few named frames
# SenderFilter includes every frame sent by ECU1, and the FrameFilter exclusions drop FrameB and FrameC
# from that set. Exclusions always win, so the sender filter cannot re-include the excluded frames.
ecu1_frames = SenderFilter(ecu_name="ECU1")
exclude_frame_b = FrameFilter(frame_name="FrameB", exclude=True)
exclude_frame_c = FrameFilter(frame_name="FrameC", exclude=True)
filtered_frames = [
    filtered_frame
    for frame in frames
    if (filtered_frame := filter_recursive(frame, filters=[ecu1_frames, exclude_frame_b, exclude_frame_c])) is not None
]
  1"""
  2It is possible to filter frames and signals using filter predicates. A filter predicate is any callable that takes a
  3`remotivelabs.broker.frame.FrameInfo` or `remotivelabs.broker.signal.SignalInfo` object and returns a boolean
  4indicating whether the object matches the filter criteria.
  5
  6All filters have an `exclude` flag to indicate whether matches should be excluded (`True`) or
  7included (`False`, default). Filters are callable and can be passed to Python built-in functions that
  8expect a predicate, such as `filter()`, `any()`, or `all()`. The snippet below shows examples
  9using `filter()`:
 10
 11Filter Strategy:
 12
 13    The `filter_recursive()` function applies frame and signal filters with context-dependent behavior.
 14    Frame filtering determines eligibility, then signal filtering applies differently based on frame
 15    inclusion: included frames start with all signals (exclude-only), excluded frames require explicit
 16    signal inclusion. Exclusion filters always take priority over inclusion filters.
 17
 18Examples:
 19
 20```python
 21.. include:: ./_docs/snippets/filters.py
 22```
 23
 24"""
 25
 26from __future__ import annotations
 27
 28from dataclasses import dataclass, replace
 29from typing import Literal, Protocol, Sequence, TypeGuard, Union, overload, runtime_checkable
 30
 31from remotivelabs.broker.frame import FrameInfo
 32from remotivelabs.broker.signal import SignalInfo
 33
 34
 35@runtime_checkable
 36class FrameFilterPredicate(Protocol):
 37    """"""
 38
 39    @property
 40    def exclude(self) -> bool: ...
 41
 42    @property
 43    def type(self) -> Literal["frame", "any"]: ...
 44
 45    def __call__(self, info: FrameInfo) -> bool: ...
 46
 47
 48@runtime_checkable
 49class SignalFilterPredicate(Protocol):
 50    """"""
 51
 52    @property
 53    def exclude(self) -> bool: ...
 54
 55    @property
 56    def type(self) -> Literal["signal", "any"]: ...
 57
 58    def __call__(self, info: SignalInfo) -> bool: ...
 59
 60
 61@runtime_checkable
 62class FrameSignalFilter(Protocol):
 63    """Signal filter that also sees its enclosing frame.
 64
 65    Takes (frame, signal) rather than just (signal), so it cannot be dropped
 66    directly into the signal-filter pipeline. `filter_recursive` binds it to
 67    the current frame, producing a regular signal predicate.
 68    """
 69
 70    @property
 71    def exclude(self) -> bool: ...
 72
 73    @property
 74    def type(self) -> Literal["frame_signal"]: ...
 75
 76    def __call__(self, frame: FrameInfo, signal: SignalInfo) -> bool: ...
 77
 78
 79# Public filter types
 80FilterLike = Union[FrameFilterPredicate, SignalFilterPredicate, FrameSignalFilter]
 81
 82
 83def is_frame_filter(filter: object) -> TypeGuard[FrameFilterPredicate]:
 84    # A filter is a frame filter if it has type "frame" or "any",
 85    # and it can be called with FrameInfo
 86    return hasattr(filter, "type") and getattr(filter, "type", None) in ("frame", "any")
 87
 88
 89def is_signal_filter(filter: object) -> TypeGuard[SignalFilterPredicate]:
 90    # A filter is a signal filter if it has type "signal" or "any",
 91    # and it can be called with SignalInfo
 92    return hasattr(filter, "type") and getattr(filter, "type", None) in ("signal", "any")
 93
 94
 95def is_frame_signal_filter(filter: object) -> TypeGuard[FrameSignalFilter]:
 96    return hasattr(filter, "type") and getattr(filter, "type", None) == "frame_signal"
 97
 98
 99def is_filter(obj: object) -> TypeGuard[FilterLike]:
100    return hasattr(obj, "type") and getattr(obj, "type", None) in ("frame", "signal", "any", "frame_signal")
101
102
103@dataclass(frozen=True)
104class AllFramesFilter:
105    exclude: bool = False
106    type: Literal["frame"] = "frame"
107
108    def __call__(self, info: FrameInfo) -> bool:  # noqa: ARG002
109        return not self.exclude
110
111
112@dataclass(frozen=True)
113class FrameFilter:
114    frame_name: str
115    exclude: bool = False
116    type: Literal["frame"] = "frame"
117
118    def __call__(self, info: FrameInfo) -> bool:
119        matches = info.name == self.frame_name
120        return not matches if self.exclude else matches
121
122
123@dataclass(frozen=True)
124class SignalFilter:
125    signal_name: str
126    exclude: bool = False
127    type: Literal["signal"] = "signal"
128
129    def __call__(self, info: SignalInfo) -> bool:
130        matches = info.name == self.signal_name
131        return not matches if self.exclude else matches
132
133
134@dataclass(frozen=True)
135class ReceiverFilter:
136    ecu_name: str
137    exclude: bool = False
138    type: Literal["any"] = "any"
139
140    @overload
141    def __call__(self, info: FrameInfo) -> bool: ...
142
143    @overload
144    def __call__(self, info: SignalInfo) -> bool: ...
145
146    def __call__(self, info: FrameInfo | SignalInfo) -> bool:
147        if isinstance(info, FrameInfo):
148            receivers = set(info.receiver)
149            receivers.update(r for sig in info.signals.values() for r in sig.receiver)
150            matches = self.ecu_name in receivers
151        elif isinstance(info, SignalInfo):
152            matches = self.ecu_name in info.receiver
153        else:
154            matches = False
155
156        return not matches if self.exclude else matches
157
158
159@dataclass(frozen=True)
160class SenderFilter:
161    ecu_name: str
162    exclude: bool = False
163    type: Literal["any"] = "any"
164
165    @overload
166    def __call__(self, info: FrameInfo) -> bool: ...
167
168    @overload
169    def __call__(self, info: SignalInfo) -> bool: ...
170
171    def __call__(self, info: FrameInfo | SignalInfo) -> bool:
172        if isinstance(info, FrameInfo):
173            senders = set(info.sender)
174            senders.update(s for sig in info.signals.values() for s in sig.sender)
175            matches = self.ecu_name in senders
176        elif isinstance(info, SignalInfo):
177            matches = self.ecu_name in info.sender
178        else:
179            matches = False
180
181        return not matches if self.exclude else matches
182
183
184def _e2e_signal_names(frame: FrameInfo) -> set[str]:
185    names: set[str] = set()
186    if frame.e2e is not None:
187        names.add(frame.e2e.signal_crc)
188        names.add(frame.e2e.signal_counter)
189    for group in frame.groups or []:
190        if group.e2e is not None:
191            names.add(group.e2e.signal_crc)
192            names.add(group.e2e.signal_counter)
193    return names
194
195
196@dataclass(frozen=True)
197class E2eSignalsFilter:
198    """Matches the CRC and counter signals of any E2E profile attached to the frame.
199
200    Inspects both frame-level ``frame.e2e`` and every group-level ``frame.groups[*].e2e``.
201    """
202
203    exclude: bool = False
204    type: Literal["frame_signal"] = "frame_signal"
205
206    def __call__(self, frame: FrameInfo, signal: SignalInfo) -> bool:
207        matches = signal.name in _e2e_signal_names(frame)
208        return not matches if self.exclude else matches
209
210
211@dataclass(frozen=True)
212class _FrameBoundSignalFilter:
213    """Binds a FrameSignalFilter to a frame, producing a unary SignalFilterPredicate.
214
215    ``apply_signal_filters`` reads ``exclude`` and ``type`` directly when partitioning,
216    so both are surfaced here.
217    """
218
219    filter: FrameSignalFilter
220    frame: FrameInfo
221    type: Literal["signal"] = "signal"
222
223    @property
224    def exclude(self) -> bool:
225        return self.filter.exclude
226
227    def __call__(self, info: SignalInfo) -> bool:
228        return self.filter(self.frame, info)
229
230
231def is_frame_excluded(frame_info: FrameInfo, frame_filters: Sequence[FrameFilterPredicate]) -> bool:
232    """Return True if any exclusion filter (exclude=True) explicitly rejects the frame."""
233    return any(not f(frame_info) for f in frame_filters if f.exclude)
234
235
236def apply_frame_filters(frame_info: FrameInfo, frame_filters: Sequence[FrameFilterPredicate]) -> FrameInfo | None:
237    include_filters = [f for f in frame_filters if not f.exclude]
238
239    # Check exclusions first (they have priority)
240    if is_frame_excluded(frame_info, frame_filters):
241        return None
242
243    # And then inclusions
244    if any(f(frame_info) for f in include_filters):
245        return frame_info
246
247    # No match, no inclusion
248    return None
249
250
251def apply_signal_filters(
252    signal_infos: Sequence[SignalInfo], signal_filters: Sequence[SignalFilterPredicate], include_by_default: bool
253) -> list[SignalInfo]:
254    include_filters = [f for f in signal_filters if not f.exclude]
255    exclude_filters = [f for f in signal_filters if f.exclude]
256
257    included_signals = []
258    for signal_info in signal_infos:
259        # Check exclusion filters first (they have priority)
260        is_excluded = any(not f(signal_info) for f in exclude_filters)
261        if is_excluded:
262            continue
263
264        # Handle inclusion logic
265        if include_by_default:
266            # Include unless explicitly excluded (already handled above)
267            included_signals.append(signal_info)
268        else:
269            # Must be explicitly included by an inclusion filter
270            is_included = any(f(signal_info) for f in include_filters)
271            if is_included:
272                included_signals.append(signal_info)
273
274    return included_signals
275
276
277def filter_recursive(frame_info: FrameInfo, filters: Sequence[FilterLike]) -> FrameInfo | None:
278    """
279    Apply filters to a FrameInfo and return filtered result or None.
280
281    Filter Strategy:
282        Frame filtering determines if the frame should be considered at all.
283        Signal filtering then determines which signals to include, with behavior
284        depending on frame inclusion:
285        - Frame included: Include all signals except those explicitly excluded
286        - Frame excluded: Only include signals that are explicitly included
287        - No filters: Returns None (nothing to subscribe to)
288
289    Exclusion Priority:
290        Exclusion filters (exclude=True) always take priority over inclusion filters
291        for both frames and signals.
292
293        A filter of type "any" (e.g. `SenderFilter`, `ReceiverFilter`) acts on both frames and
294        signals. When such a filter includes a frame that is then explicitly excluded by a frame
295        exclusion filter, it will not re-include the frame's signals. This makes
296        "all frames sent by ECU1, except FrameB" work as expected. Only pure signal filters
297        (type "signal" or "frame_signal") can re-include signals of an explicitly excluded frame.
298
299    Returns: Filtered FrameInfo with matching signals, or None if no matches
300    """
301    frame_filters = [f for f in filters if is_frame_filter(f)]
302    signal_filters: list[SignalFilterPredicate] = []
303    for f in filters:
304        if is_signal_filter(f):
305            signal_filters.append(f)
306        elif is_frame_signal_filter(f):
307            signal_filters.append(_FrameBoundSignalFilter(f, frame_info))
308
309    # If we have no filters, there is nothing to subscribe to
310    if not frame_filters and not signal_filters:
311        return None
312
313    # Check if frame passes frame filters
314    # If frame filters exist, frame must pass at least one include filter AND not be excluded
315    frame_included = bool(apply_frame_filters(frame_info, frame_filters))
316
317    if not frame_included and is_frame_excluded(frame_info, frame_filters):
318        # The frame was explicitly excluded. "any"-type filters have already had their say at
319        # frame level and were overruled, so they must not re-include signals of this frame.
320        # Only pure signal filters (and exclusions) remain.
321        signal_filters = [f for f in signal_filters if f.exclude or f.type != "any"]
322
323    # If frame is excluded and we have no signal filters, exclude entirely
324    if not frame_included and not signal_filters:
325        return None
326
327    # If frame is included and no signal filters, include all signals
328    if frame_included and not signal_filters:
329        return frame_info
330
331    # If the frame has no individual signals there is nothing for signal filters to act on.
332    # Return the frame as-is if it was included, otherwise exclude it.
333    if not frame_info.signals:
334        return frame_info if frame_included else None
335
336    # Apply signal filters
337    # If frame is included, start with all signals and apply exclusions (include_by_default=True)
338    # If frame is excluded, only include signals that are explicitly included (include_by_default=False)
339    included_signals = apply_signal_filters(list(frame_info.signals.values()), signal_filters, include_by_default=frame_included)
340    if not included_signals:
341        # No signals matched — exclude the frame.
342        return None
343
344    # Return frame with filtered signals
345    return replace(frame_info, signals={sig.name: sig for sig in included_signals})
@runtime_checkable
class FrameFilterPredicate(typing.Protocol):
36@runtime_checkable
37class FrameFilterPredicate(Protocol):
38    """"""
39
40    @property
41    def exclude(self) -> bool: ...
42
43    @property
44    def type(self) -> Literal["frame", "any"]: ...
45
46    def __call__(self, info: FrameInfo) -> bool: ...
FrameFilterPredicate(*args, **kwargs)
1945def _no_init_or_replace_init(self, *args, **kwargs):
1946    cls = type(self)
1947
1948    if cls._is_protocol:
1949        raise TypeError('Protocols cannot be instantiated')
1950
1951    # Already using a custom `__init__`. No need to calculate correct
1952    # `__init__` to call. This can lead to RecursionError. See bpo-45121.
1953    if cls.__init__ is not _no_init_or_replace_init:
1954        return
1955
1956    # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
1957    # The first instantiation of the subclass will call `_no_init_or_replace_init` which
1958    # searches for a proper new `__init__` in the MRO. The new `__init__`
1959    # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
1960    # instantiation of the protocol subclass will thus use the new
1961    # `__init__` and no longer call `_no_init_or_replace_init`.
1962    for base in cls.__mro__:
1963        init = base.__dict__.get('__init__', _no_init_or_replace_init)
1964        if init is not _no_init_or_replace_init:
1965            cls.__init__ = init
1966            break
1967    else:
1968        # should not happen
1969        cls.__init__ = object.__init__
1970
1971    cls.__init__(self, *args, **kwargs)
exclude: bool
40    @property
41    def exclude(self) -> bool: ...
type: Literal['frame', 'any']
43    @property
44    def type(self) -> Literal["frame", "any"]: ...
@runtime_checkable
class SignalFilterPredicate(typing.Protocol):
49@runtime_checkable
50class SignalFilterPredicate(Protocol):
51    """"""
52
53    @property
54    def exclude(self) -> bool: ...
55
56    @property
57    def type(self) -> Literal["signal", "any"]: ...
58
59    def __call__(self, info: SignalInfo) -> bool: ...
SignalFilterPredicate(*args, **kwargs)
1945def _no_init_or_replace_init(self, *args, **kwargs):
1946    cls = type(self)
1947
1948    if cls._is_protocol:
1949        raise TypeError('Protocols cannot be instantiated')
1950
1951    # Already using a custom `__init__`. No need to calculate correct
1952    # `__init__` to call. This can lead to RecursionError. See bpo-45121.
1953    if cls.__init__ is not _no_init_or_replace_init:
1954        return
1955
1956    # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
1957    # The first instantiation of the subclass will call `_no_init_or_replace_init` which
1958    # searches for a proper new `__init__` in the MRO. The new `__init__`
1959    # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
1960    # instantiation of the protocol subclass will thus use the new
1961    # `__init__` and no longer call `_no_init_or_replace_init`.
1962    for base in cls.__mro__:
1963        init = base.__dict__.get('__init__', _no_init_or_replace_init)
1964        if init is not _no_init_or_replace_init:
1965            cls.__init__ = init
1966            break
1967    else:
1968        # should not happen
1969        cls.__init__ = object.__init__
1970
1971    cls.__init__(self, *args, **kwargs)
exclude: bool
53    @property
54    def exclude(self) -> bool: ...
type: Literal['signal', 'any']
56    @property
57    def type(self) -> Literal["signal", "any"]: ...
@runtime_checkable
class FrameSignalFilter(typing.Protocol):
62@runtime_checkable
63class FrameSignalFilter(Protocol):
64    """Signal filter that also sees its enclosing frame.
65
66    Takes (frame, signal) rather than just (signal), so it cannot be dropped
67    directly into the signal-filter pipeline. `filter_recursive` binds it to
68    the current frame, producing a regular signal predicate.
69    """
70
71    @property
72    def exclude(self) -> bool: ...
73
74    @property
75    def type(self) -> Literal["frame_signal"]: ...
76
77    def __call__(self, frame: FrameInfo, signal: SignalInfo) -> bool: ...

Signal filter that also sees its enclosing frame.

Takes (frame, signal) rather than just (signal), so it cannot be dropped directly into the signal-filter pipeline. filter_recursive binds it to the current frame, producing a regular signal predicate.

FrameSignalFilter(*args, **kwargs)
1945def _no_init_or_replace_init(self, *args, **kwargs):
1946    cls = type(self)
1947
1948    if cls._is_protocol:
1949        raise TypeError('Protocols cannot be instantiated')
1950
1951    # Already using a custom `__init__`. No need to calculate correct
1952    # `__init__` to call. This can lead to RecursionError. See bpo-45121.
1953    if cls.__init__ is not _no_init_or_replace_init:
1954        return
1955
1956    # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
1957    # The first instantiation of the subclass will call `_no_init_or_replace_init` which
1958    # searches for a proper new `__init__` in the MRO. The new `__init__`
1959    # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
1960    # instantiation of the protocol subclass will thus use the new
1961    # `__init__` and no longer call `_no_init_or_replace_init`.
1962    for base in cls.__mro__:
1963        init = base.__dict__.get('__init__', _no_init_or_replace_init)
1964        if init is not _no_init_or_replace_init:
1965            cls.__init__ = init
1966            break
1967    else:
1968        # should not happen
1969        cls.__init__ = object.__init__
1970
1971    cls.__init__(self, *args, **kwargs)
exclude: bool
71    @property
72    def exclude(self) -> bool: ...
type: Literal['frame_signal']
74    @property
75    def type(self) -> Literal["frame_signal"]: ...
def is_frame_filter( filter: object) -> TypeGuard[FrameFilterPredicate]:
84def is_frame_filter(filter: object) -> TypeGuard[FrameFilterPredicate]:
85    # A filter is a frame filter if it has type "frame" or "any",
86    # and it can be called with FrameInfo
87    return hasattr(filter, "type") and getattr(filter, "type", None) in ("frame", "any")
def is_signal_filter( filter: object) -> TypeGuard[SignalFilterPredicate]:
90def is_signal_filter(filter: object) -> TypeGuard[SignalFilterPredicate]:
91    # A filter is a signal filter if it has type "signal" or "any",
92    # and it can be called with SignalInfo
93    return hasattr(filter, "type") and getattr(filter, "type", None) in ("signal", "any")
def is_frame_signal_filter( filter: object) -> TypeGuard[FrameSignalFilter]:
96def is_frame_signal_filter(filter: object) -> TypeGuard[FrameSignalFilter]:
97    return hasattr(filter, "type") and getattr(filter, "type", None) == "frame_signal"
def is_filter( obj: object) -> TypeGuard[Union[FrameFilterPredicate, SignalFilterPredicate, FrameSignalFilter]]:
100def is_filter(obj: object) -> TypeGuard[FilterLike]:
101    return hasattr(obj, "type") and getattr(obj, "type", None) in ("frame", "signal", "any", "frame_signal")
@dataclass(frozen=True)
class AllFramesFilter:
104@dataclass(frozen=True)
105class AllFramesFilter:
106    exclude: bool = False
107    type: Literal["frame"] = "frame"
108
109    def __call__(self, info: FrameInfo) -> bool:  # noqa: ARG002
110        return not self.exclude
AllFramesFilter(exclude: bool = False, type: Literal['frame'] = 'frame')
exclude: bool = False
type: Literal['frame'] = 'frame'
@dataclass(frozen=True)
class FrameFilter:
113@dataclass(frozen=True)
114class FrameFilter:
115    frame_name: str
116    exclude: bool = False
117    type: Literal["frame"] = "frame"
118
119    def __call__(self, info: FrameInfo) -> bool:
120        matches = info.name == self.frame_name
121        return not matches if self.exclude else matches
FrameFilter( frame_name: str, exclude: bool = False, type: Literal['frame'] = 'frame')
frame_name: str
exclude: bool = False
type: Literal['frame'] = 'frame'
@dataclass(frozen=True)
class SignalFilter:
124@dataclass(frozen=True)
125class SignalFilter:
126    signal_name: str
127    exclude: bool = False
128    type: Literal["signal"] = "signal"
129
130    def __call__(self, info: SignalInfo) -> bool:
131        matches = info.name == self.signal_name
132        return not matches if self.exclude else matches
SignalFilter( signal_name: str, exclude: bool = False, type: Literal['signal'] = 'signal')
signal_name: str
exclude: bool = False
type: Literal['signal'] = 'signal'
@dataclass(frozen=True)
class ReceiverFilter:
135@dataclass(frozen=True)
136class ReceiverFilter:
137    ecu_name: str
138    exclude: bool = False
139    type: Literal["any"] = "any"
140
141    @overload
142    def __call__(self, info: FrameInfo) -> bool: ...
143
144    @overload
145    def __call__(self, info: SignalInfo) -> bool: ...
146
147    def __call__(self, info: FrameInfo | SignalInfo) -> bool:
148        if isinstance(info, FrameInfo):
149            receivers = set(info.receiver)
150            receivers.update(r for sig in info.signals.values() for r in sig.receiver)
151            matches = self.ecu_name in receivers
152        elif isinstance(info, SignalInfo):
153            matches = self.ecu_name in info.receiver
154        else:
155            matches = False
156
157        return not matches if self.exclude else matches
ReceiverFilter(ecu_name: str, exclude: bool = False, type: Literal['any'] = 'any')
ecu_name: str
exclude: bool = False
type: Literal['any'] = 'any'
@dataclass(frozen=True)
class SenderFilter:
160@dataclass(frozen=True)
161class SenderFilter:
162    ecu_name: str
163    exclude: bool = False
164    type: Literal["any"] = "any"
165
166    @overload
167    def __call__(self, info: FrameInfo) -> bool: ...
168
169    @overload
170    def __call__(self, info: SignalInfo) -> bool: ...
171
172    def __call__(self, info: FrameInfo | SignalInfo) -> bool:
173        if isinstance(info, FrameInfo):
174            senders = set(info.sender)
175            senders.update(s for sig in info.signals.values() for s in sig.sender)
176            matches = self.ecu_name in senders
177        elif isinstance(info, SignalInfo):
178            matches = self.ecu_name in info.sender
179        else:
180            matches = False
181
182        return not matches if self.exclude else matches
SenderFilter(ecu_name: str, exclude: bool = False, type: Literal['any'] = 'any')
ecu_name: str
exclude: bool = False
type: Literal['any'] = 'any'
@dataclass(frozen=True)
class E2eSignalsFilter:
197@dataclass(frozen=True)
198class E2eSignalsFilter:
199    """Matches the CRC and counter signals of any E2E profile attached to the frame.
200
201    Inspects both frame-level ``frame.e2e`` and every group-level ``frame.groups[*].e2e``.
202    """
203
204    exclude: bool = False
205    type: Literal["frame_signal"] = "frame_signal"
206
207    def __call__(self, frame: FrameInfo, signal: SignalInfo) -> bool:
208        matches = signal.name in _e2e_signal_names(frame)
209        return not matches if self.exclude else matches

Matches the CRC and counter signals of any E2E profile attached to the frame.

Inspects both frame-level frame.e2e and every group-level frame.groups[*].e2e.

E2eSignalsFilter( exclude: bool = False, type: Literal['frame_signal'] = 'frame_signal')
exclude: bool = False
type: Literal['frame_signal'] = 'frame_signal'
def is_frame_excluded( frame_info: remotivelabs.broker.FrameInfo, frame_filters: Sequence[FrameFilterPredicate]) -> bool:
232def is_frame_excluded(frame_info: FrameInfo, frame_filters: Sequence[FrameFilterPredicate]) -> bool:
233    """Return True if any exclusion filter (exclude=True) explicitly rejects the frame."""
234    return any(not f(frame_info) for f in frame_filters if f.exclude)

Return True if any exclusion filter (exclude=True) explicitly rejects the frame.

def apply_frame_filters( frame_info: remotivelabs.broker.FrameInfo, frame_filters: Sequence[FrameFilterPredicate]) -> remotivelabs.broker.FrameInfo | None:
237def apply_frame_filters(frame_info: FrameInfo, frame_filters: Sequence[FrameFilterPredicate]) -> FrameInfo | None:
238    include_filters = [f for f in frame_filters if not f.exclude]
239
240    # Check exclusions first (they have priority)
241    if is_frame_excluded(frame_info, frame_filters):
242        return None
243
244    # And then inclusions
245    if any(f(frame_info) for f in include_filters):
246        return frame_info
247
248    # No match, no inclusion
249    return None
def apply_signal_filters( signal_infos: Sequence[remotivelabs.broker.SignalInfo], signal_filters: Sequence[SignalFilterPredicate], include_by_default: bool) -> list[remotivelabs.broker.SignalInfo]:
252def apply_signal_filters(
253    signal_infos: Sequence[SignalInfo], signal_filters: Sequence[SignalFilterPredicate], include_by_default: bool
254) -> list[SignalInfo]:
255    include_filters = [f for f in signal_filters if not f.exclude]
256    exclude_filters = [f for f in signal_filters if f.exclude]
257
258    included_signals = []
259    for signal_info in signal_infos:
260        # Check exclusion filters first (they have priority)
261        is_excluded = any(not f(signal_info) for f in exclude_filters)
262        if is_excluded:
263            continue
264
265        # Handle inclusion logic
266        if include_by_default:
267            # Include unless explicitly excluded (already handled above)
268            included_signals.append(signal_info)
269        else:
270            # Must be explicitly included by an inclusion filter
271            is_included = any(f(signal_info) for f in include_filters)
272            if is_included:
273                included_signals.append(signal_info)
274
275    return included_signals
def filter_recursive( frame_info: remotivelabs.broker.FrameInfo, filters: Sequence[Union[FrameFilterPredicate, SignalFilterPredicate, FrameSignalFilter]]) -> remotivelabs.broker.FrameInfo | None:
278def filter_recursive(frame_info: FrameInfo, filters: Sequence[FilterLike]) -> FrameInfo | None:
279    """
280    Apply filters to a FrameInfo and return filtered result or None.
281
282    Filter Strategy:
283        Frame filtering determines if the frame should be considered at all.
284        Signal filtering then determines which signals to include, with behavior
285        depending on frame inclusion:
286        - Frame included: Include all signals except those explicitly excluded
287        - Frame excluded: Only include signals that are explicitly included
288        - No filters: Returns None (nothing to subscribe to)
289
290    Exclusion Priority:
291        Exclusion filters (exclude=True) always take priority over inclusion filters
292        for both frames and signals.
293
294        A filter of type "any" (e.g. `SenderFilter`, `ReceiverFilter`) acts on both frames and
295        signals. When such a filter includes a frame that is then explicitly excluded by a frame
296        exclusion filter, it will not re-include the frame's signals. This makes
297        "all frames sent by ECU1, except FrameB" work as expected. Only pure signal filters
298        (type "signal" or "frame_signal") can re-include signals of an explicitly excluded frame.
299
300    Returns: Filtered FrameInfo with matching signals, or None if no matches
301    """
302    frame_filters = [f for f in filters if is_frame_filter(f)]
303    signal_filters: list[SignalFilterPredicate] = []
304    for f in filters:
305        if is_signal_filter(f):
306            signal_filters.append(f)
307        elif is_frame_signal_filter(f):
308            signal_filters.append(_FrameBoundSignalFilter(f, frame_info))
309
310    # If we have no filters, there is nothing to subscribe to
311    if not frame_filters and not signal_filters:
312        return None
313
314    # Check if frame passes frame filters
315    # If frame filters exist, frame must pass at least one include filter AND not be excluded
316    frame_included = bool(apply_frame_filters(frame_info, frame_filters))
317
318    if not frame_included and is_frame_excluded(frame_info, frame_filters):
319        # The frame was explicitly excluded. "any"-type filters have already had their say at
320        # frame level and were overruled, so they must not re-include signals of this frame.
321        # Only pure signal filters (and exclusions) remain.
322        signal_filters = [f for f in signal_filters if f.exclude or f.type != "any"]
323
324    # If frame is excluded and we have no signal filters, exclude entirely
325    if not frame_included and not signal_filters:
326        return None
327
328    # If frame is included and no signal filters, include all signals
329    if frame_included and not signal_filters:
330        return frame_info
331
332    # If the frame has no individual signals there is nothing for signal filters to act on.
333    # Return the frame as-is if it was included, otherwise exclude it.
334    if not frame_info.signals:
335        return frame_info if frame_included else None
336
337    # Apply signal filters
338    # If frame is included, start with all signals and apply exclusions (include_by_default=True)
339    # If frame is excluded, only include signals that are explicitly included (include_by_default=False)
340    included_signals = apply_signal_filters(list(frame_info.signals.values()), signal_filters, include_by_default=frame_included)
341    if not included_signals:
342        # No signals matched — exclude the frame.
343        return None
344
345    # Return frame with filtered signals
346    return replace(frame_info, signals={sig.name: sig for sig in included_signals})

Apply filters to a FrameInfo and return filtered result or None.

Filter Strategy:

Frame filtering determines if the frame should be considered at all. Signal filtering then determines which signals to include, with behavior depending on frame inclusion:

  • Frame included: Include all signals except those explicitly excluded
  • Frame excluded: Only include signals that are explicitly included
  • No filters: Returns None (nothing to subscribe to)
Exclusion Priority:

Exclusion filters (exclude=True) always take priority over inclusion filters for both frames and signals.

A filter of type "any" (e.g. SenderFilter, ReceiverFilter) acts on both frames and signals. When such a filter includes a frame that is then explicitly excluded by a frame exclusion filter, it will not re-include the frame's signals. This makes "all frames sent by ECU1, except FrameB" work as expected. Only pure signal filters (type "signal" or "frame_signal") can re-include signals of an explicitly excluded frame.

Returns: Filtered FrameInfo with matching signals, or None if no matches