From 062f2976e540dadac8490eac90f25112ed54c654 Mon Sep 17 00:00:00 2001 From: PhysicalFleet <360193358+physicalfleet-dev-team@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:47:04 -0800 Subject: [PATCH] Add BusLoadListener to measure the bus load Add can.BusLoadListener, which estimates the bus load in percent over a sliding time window from the frames it receives, similar to canbusload from can-utils. Frames are placed in time by their timestamps, so the listener works with live buses and with log files. The frame lengths are also available as can.bus_load.frame_bit_length() and can.bus_load.frame_duration(). They cover standard and extended classical CAN frames, remote frames and CAN FD frames with and without bitrate switching, with worst-case or without bit stuffing. --- can/__init__.py | 3 + can/bus_load.py | 284 +++++++++++++++++++++++++++++++ doc/changelog.d/1895.added.rst | 1 + doc/notifier.rst | 32 ++++ test/test_bus_load.py | 295 +++++++++++++++++++++++++++++++++ 5 files changed, 615 insertions(+) create mode 100644 can/bus_load.py create mode 100644 doc/changelog.d/1895.added.rst create mode 100644 test/test_bus_load.py diff --git a/can/__init__.py b/can/__init__.py index b1bd636c1..b06ed865d 100644 --- a/can/__init__.py +++ b/can/__init__.py @@ -22,6 +22,7 @@ "BufferedReader", "Bus", "BusABC", + "BusLoadListener", "BusState", "CSVReader", "CSVWriter", @@ -57,6 +58,7 @@ "bit_timing", "broadcastmanager", "bus", + "bus_load", "ctypesutil", "detect_available_configs", "exceptions", @@ -88,6 +90,7 @@ RestartableCyclicTaskABC, ) from .bus import BusABC, BusState, CanProtocol +from .bus_load import BusLoadListener from .exceptions import ( CanError, CanInitializationError, diff --git a/can/bus_load.py b/can/bus_load.py new file mode 100644 index 000000000..e82888767 --- /dev/null +++ b/can/bus_load.py @@ -0,0 +1,284 @@ +""" +Estimate the length of CAN frames on the wire and the resulting bus load. + +The frame lengths follow ISO 11898-1. They include the 3 bit intermission +that separates consecutive frames, because the bus cannot be used during +that time either. +""" + +import threading +import time +from collections import deque + +from can.bit_timing import BitTiming, BitTimingFd +from can.listener import Listener +from can.message import Message +from can.util import dlc2len, len2dlc + +__all__ = ["BusLoadListener", "frame_bit_length", "frame_duration"] + +#: Bits that are subject to bit stuffing, without the data field: +#: SOF, identifier, RTR, IDE, r0, DLC and the 15 bit CRC sequence. +_CC_STUFFED_BITS_SFF = 34 +#: SOF, base identifier, SRR, IDE, identifier extension, RTR, r1, r0, DLC and the CRC sequence. +_CC_STUFFED_BITS_EFF = 54 +#: CAN FD header from SOF up to and including BRS: +#: SOF, identifier, RRS, IDE, FDF, res and BRS. +_FD_ARBITRATION_BITS_SFF = 17 +#: SOF, base identifier, SRR, IDE, identifier extension, RRS, FDF, res and BRS. +_FD_ARBITRATION_BITS_EFF = 36 +#: ESI and DLC, the rest of the CAN FD control field. +_FD_CONTROL_BITS = 5 +#: Stuff count (4 bits), CRC sequence and fixed stuff bits of the CAN FD CRC field +#: for frames with up to 16 data bytes (CRC-17) and with more (CRC-21). +_FD_CRC_FIELD_BITS_CRC17 = 4 + 17 + 6 +_FD_CRC_FIELD_BITS_CRC21 = 4 + 21 + 7 +#: CRC delimiter, ACK slot, ACK delimiter, end of frame (7 bits) and intermission (3 bits). +_TRAILER_BITS = 13 + + +def _worst_case_stuff_bits(nof_bits: int) -> int: + """Return the maximum number of stuff bits in a bit stream of the given length. + + After the first bit, a stuff bit can be needed at most every 4 bits, + e.g. for ``1 1111 0000 1111 0000``. + """ + return max(nof_bits - 1, 0) // 4 + + +def _frame_bits(msg: Message, bit_stuffing: bool) -> tuple[int, int]: + """Return the number of bits sent at the nominal and at the data bitrate.""" + if msg.is_error_frame: + raise ValueError("The length of error frames is not defined") + + if not msg.is_fd: + nof_data_bytes = 0 if msg.is_remote_frame else min(msg.dlc, 8) + stuffed = ( + _CC_STUFFED_BITS_EFF if msg.is_extended_id else _CC_STUFFED_BITS_SFF + ) + 8 * nof_data_bytes + if bit_stuffing: + stuffed += _worst_case_stuff_bits(stuffed) + return stuffed + _TRAILER_BITS, 0 + + # the data field is padded to the next valid CAN FD data length + nof_data_bytes = dlc2len(len2dlc(msg.dlc)) + arbitration = ( + _FD_ARBITRATION_BITS_EFF if msg.is_extended_id else _FD_ARBITRATION_BITS_SFF + ) + data = _FD_CONTROL_BITS + 8 * nof_data_bytes + crc_field = ( + _FD_CRC_FIELD_BITS_CRC17 if nof_data_bytes <= 16 else _FD_CRC_FIELD_BITS_CRC21 + ) + if bit_stuffing: + # Dynamic bit stuffing applies from SOF to the end of the data field. + # The fixed stuff bits of the CRC field are always included above. + stuff_bits = _worst_case_stuff_bits(arbitration + data) + arbitration_stuff_bits = _worst_case_stuff_bits(arbitration) + arbitration += arbitration_stuff_bits + data += stuff_bits - arbitration_stuff_bits + data += crc_field + + if msg.bitrate_switch: + return arbitration + _TRAILER_BITS, data + return arbitration + data + _TRAILER_BITS, 0 + + +def frame_bit_length(msg: Message, bit_stuffing: bool = True) -> int: + """Return the number of bits a frame occupies on the bus. + + The length includes the 3 bit intermission after the frame. For CAN FD + frames with bitrate switching, some of these bits are sent at the data + bitrate; use :func:`~can.bus_load.frame_duration` to get the time the frame takes. + + :param msg: + The frame. Remote frames have no data field. CAN FD frames are padded + to the next valid CAN FD data length. + :param bit_stuffing: + If ``True`` (the default), include the worst-case number of stuff bits. + The actual number depends on the content of the frame and is usually + lower. If ``False``, ignore stuff bits, except for the fixed stuff bits + in the CRC field of CAN FD frames, which are always sent. + :return: The length of the frame in bits. + :raises ValueError: if ``msg`` is an error frame. + """ + return sum(_frame_bits(msg, bit_stuffing)) + + +def frame_duration( + msg: Message, + bitrate: int, + data_bitrate: int | None = None, + bit_stuffing: bool = True, +) -> float: + """Return the time a frame occupies the bus. + + For CAN FD frames with bitrate switching, the control field from ESI on, + the data field and the CRC field are sent at ``data_bitrate``, all other + bits at ``bitrate``. The bitrate switches within the BRS bit and the CRC + delimiter; both are counted at the nominal bitrate. + + :param msg: + The frame, see :func:`~can.bus_load.frame_bit_length`. + :param bitrate: + The nominal (arbitration) bitrate in bit/s. + :param data_bitrate: + The data bitrate in bit/s. It is required for CAN FD frames + with bitrate switching. + :param bit_stuffing: + Whether to include the worst-case number of stuff bits, + see :func:`~can.bus_load.frame_bit_length`. + :return: The duration of the frame in seconds, including the intermission. + :raises ValueError: + if ``msg`` is an error frame, a bitrate is not positive, or ``data_bitrate`` + is missing for a CAN FD frame with bitrate switching. + """ + if bitrate <= 0: + raise ValueError(f"bitrate must be positive, got {bitrate}") + if data_bitrate is not None and data_bitrate <= 0: + raise ValueError(f"data_bitrate must be positive, got {data_bitrate}") + + nominal_bits, data_bits = _frame_bits(msg, bit_stuffing) + if not data_bits: + return nominal_bits / bitrate + if data_bitrate is None: + raise ValueError( + "data_bitrate is required for CAN FD frames with bitrate switching" + ) + return nominal_bits / bitrate + data_bits / data_bitrate + + +class BusLoadListener(Listener): + """Measure the bus load over a sliding time window. + + The listener estimates how long each frame occupied the bus with + :func:`~can.bus_load.frame_duration` and reports the share of the last ``window`` + seconds that the bus was busy:: + + with can.Bus(interface="socketcan", channel="can0") as bus: + bus_load = can.BusLoadListener(bitrate=500_000, window=1.0) + with can.Notifier(bus, [bus_load]): + while True: + time.sleep(1) + print(f"bus load: {bus_load.get_bus_load():.1f} %") + + Frames are placed in time by their :attr:`~can.Message.timestamp`, so the + listener also works with messages from log files. Use one listener per + CAN bus. Frames sent by this node only count if the bus delivers them as + received messages too, e.g. with ``receive_own_messages=True``. Error + frames are ignored. + + By default, frames are counted with the worst-case number of stuff bits, + like ``canbusload`` from can-utils. The result can therefore be higher than + the real bus load and even exceed 100 % on a very busy bus. + """ + + def __init__( + self, + bitrate: int | None = None, + data_bitrate: int | None = None, + *, + timing: BitTiming | BitTimingFd | None = None, + window: float = 1.0, + bit_stuffing: bool = True, + ) -> None: + """ + :param bitrate: + The nominal (arbitration) bitrate of the bus in bit/s. + :param data_bitrate: + The CAN FD data bitrate in bit/s. It is required to measure CAN FD + frames with bitrate switching. + :param timing: + The bit timing of the bus, as an alternative to ``bitrate`` and + ``data_bitrate``. + :param window: + The length of the sliding window in seconds. + :param bit_stuffing: + Whether to count the worst-case number of stuff bits, + see :func:`~can.bus_load.frame_bit_length`. + :raises ValueError: + if neither ``bitrate`` nor ``timing`` is given, a bitrate is not + positive or ``window`` is not positive. + """ + if timing is not None: + if bitrate is not None or data_bitrate is not None: + raise ValueError( + "Pass either timing or bitrate and data_bitrate, not both" + ) + if isinstance(timing, BitTimingFd): + bitrate = timing.nom_bitrate + data_bitrate = timing.data_bitrate + else: + bitrate = timing.bitrate + if bitrate is None: + raise ValueError("Either bitrate or timing is required") + if bitrate <= 0: + raise ValueError(f"bitrate must be positive, got {bitrate}") + if data_bitrate is not None and data_bitrate <= 0: + raise ValueError(f"data_bitrate must be positive, got {data_bitrate}") + if window <= 0: + raise ValueError(f"window must be positive, got {window}") + + self.bitrate: int = bitrate + self.data_bitrate: int | None = data_bitrate + self.window: float = window + self.bit_stuffing: bool = bit_stuffing + + # (timestamp, duration) of the frames in the window, oldest first + self._frames: deque[tuple[float, float]] = deque() + self._last_timestamp: float | None = None + self._last_received: float = 0.0 + self._lock = threading.Lock() + + def on_message_received(self, msg: Message) -> None: + """Add the frame to the measurement. + + :raises ValueError: + if ``msg`` is a CAN FD frame with bitrate switching and + no data bitrate was given. + """ + if msg.is_error_frame: + return + duration = frame_duration( + msg, self.bitrate, self.data_bitrate, self.bit_stuffing + ) + with self._lock: + self._frames.append((msg.timestamp, duration)) + if self._last_timestamp is None or msg.timestamp >= self._last_timestamp: + self._last_timestamp = msg.timestamp + self._last_received = time.monotonic() + self._discard_before(self._last_timestamp - self.window) + + def get_bus_load(self, timestamp: float | None = None) -> float: + """Return the bus load in percent over the window ending at ``timestamp``. + + :param timestamp: + The end of the window, in the time base of the message timestamps. + Frames older than the window are discarded, so ``timestamp`` should + not decrease between calls. By default, the window ends at the + timestamp of the most recent frame plus the time that has passed + since that frame was received, so the bus load drops when the + bus falls silent. + :return: + The share of the window in which the bus was busy, in percent. + ``0.0`` if no frame was received yet. + """ + with self._lock: + if self._last_timestamp is None: + return 0.0 + if timestamp is None: + timestamp = self._last_timestamp + ( + time.monotonic() - self._last_received + ) + start = timestamp - self.window + self._discard_before(start) + # frames can arrive slightly out of order, so check both ends + busy_time = sum( + duration + for frame_timestamp, duration in self._frames + if start < frame_timestamp <= timestamp + ) + return 100.0 * busy_time / self.window + + def _discard_before(self, timestamp: float) -> None: + while self._frames and self._frames[0][0] <= timestamp: + self._frames.popleft() diff --git a/doc/changelog.d/1895.added.rst b/doc/changelog.d/1895.added.rst new file mode 100644 index 000000000..79b602193 --- /dev/null +++ b/doc/changelog.d/1895.added.rst @@ -0,0 +1 @@ +Added ``can.BusLoadListener`` to measure the bus load over a sliding time window, and ``can.bus_load.frame_bit_length()`` and ``can.bus_load.frame_duration()`` to estimate the length of CAN and CAN FD frames on the bus. diff --git a/doc/notifier.rst b/doc/notifier.rst index db1273827..221079a85 100644 --- a/doc/notifier.rst +++ b/doc/notifier.rst @@ -94,3 +94,35 @@ RedirectReader .. autoclass:: can.RedirectReader :members: + + +BusLoadListener +--------------- + +The :class:`~can.BusLoadListener` estimates how busy the bus is from the frames it +receives, similar to ``canbusload`` from can-utils. The bus load is the share of a +sliding time window during which frames occupied the bus:: + + import time + + import can + + with can.Bus(interface="socketcan", channel="can0") as bus: + bus_load = can.BusLoadListener(bitrate=500_000, window=1.0) + with can.Notifier(bus, [bus_load]): + while True: + time.sleep(1) + print(f"bus load: {bus_load.get_bus_load():.1f} %") + +For CAN FD buses with bitrate switching, pass the data bitrate as well, e.g. +``can.BusLoadListener(bitrate=500_000, data_bitrate=2_000_000)``, or the +:class:`~can.BitTimingFd` of the bus as ``timing``. + +.. autoclass:: can.BusLoadListener + :members: + +The frame lengths that the listener uses are also available as functions: + +.. autofunction:: can.bus_load.frame_bit_length + +.. autofunction:: can.bus_load.frame_duration diff --git a/test/test_bus_load.py b/test/test_bus_load.py new file mode 100644 index 000000000..5015c1c09 --- /dev/null +++ b/test/test_bus_load.py @@ -0,0 +1,295 @@ +""" +Tests for frame length calculation and the bus load listener in can.bus_load. +""" + +from unittest import mock + +import pytest + +import can +from can.bus_load import BusLoadListener, frame_bit_length, frame_duration + + +def _msg(**kwargs) -> can.Message: + kwargs.setdefault("arbitration_id", 0x123) + kwargs.setdefault("is_extended_id", False) + return can.Message(**kwargs) + + +# Classical CAN frames including the 3 bit intermission. The values with bit stuffing +# match the well-known worst-case formula from Davis et al., "Controller Area Network +# (CAN) schedulability analysis: Refuted, revisited and revised" (2007), e.g. 135 bits +# for a standard and 160 bits for an extended frame with 8 data bytes. +@pytest.mark.parametrize( + ("is_extended_id", "nof_bytes", "without_stuffing", "with_stuffing"), + [ + (False, 0, 47, 55), + (False, 1, 55, 65), + (False, 4, 79, 95), + (False, 8, 111, 135), + (True, 0, 67, 80), + (True, 1, 75, 90), + (True, 8, 131, 160), + ], +) +def test_classic_frame_bit_length( + is_extended_id, nof_bytes, without_stuffing, with_stuffing +): + msg = _msg(is_extended_id=is_extended_id, data=bytes(nof_bytes)) + assert frame_bit_length(msg, bit_stuffing=False) == without_stuffing + assert frame_bit_length(msg) == with_stuffing + + +def test_remote_frame_has_no_data_field(): + remote = _msg(is_remote_frame=True, dlc=8) + empty = _msg(data=b"") + assert frame_bit_length(remote) == frame_bit_length(empty) == 55 + assert frame_bit_length(remote, bit_stuffing=False) == 47 + + +def test_classic_frame_dlc_above_8_sends_8_bytes(): + msg = can.Message(arbitration_id=0x123, is_extended_id=False, dlc=15, check=False) + assert frame_bit_length(msg, bit_stuffing=False) == 111 + + +# CAN FD frames: header (22 or 41 bits), data, CRC field with stuff count and +# fixed stuff bits (27 bits with CRC-17, 32 bits with CRC-21) and 13 bits for +# CRC delimiter, ACK, EOF and intermission. Worst-case dynamic stuff bits are +# added for the header and the data field only. +@pytest.mark.parametrize( + ("is_extended_id", "nof_bytes", "without_stuffing", "with_stuffing"), + [ + (False, 0, 62, 67), + (False, 8, 126, 147), + (False, 16, 190, 227), + (False, 20, 227, 272), + (False, 64, 579, 712), + (True, 0, 81, 91), + (True, 64, 598, 736), + ], +) +def test_fd_frame_bit_length( + is_extended_id, nof_bytes, without_stuffing, with_stuffing +): + for bitrate_switch in (False, True): + msg = _msg( + is_extended_id=is_extended_id, + is_fd=True, + bitrate_switch=bitrate_switch, + data=bytes(nof_bytes), + ) + assert frame_bit_length(msg, bit_stuffing=False) == without_stuffing + assert frame_bit_length(msg) == with_stuffing + + +def test_fd_frame_is_padded_to_valid_length(): + padded = _msg(is_fd=True, data=bytes(10)) + assert frame_bit_length(padded) == frame_bit_length( + _msg(is_fd=True, data=bytes(12)) + ) + + +def test_error_frame_has_no_length(): + with pytest.raises(ValueError, match="error frames"): + frame_bit_length(_msg(is_error_frame=True)) + + +def test_frame_duration_classic(): + msg = _msg(data=bytes(8)) + assert frame_duration(msg, 500_000) == pytest.approx(135 / 500_000) + assert frame_duration(msg, 500_000, bit_stuffing=False) == pytest.approx( + 111 / 500_000 + ) + # the data bitrate is not used without bitrate switching + assert frame_duration(msg, 500_000, 2_000_000) == pytest.approx(135 / 500_000) + + +def test_frame_duration_fd_without_bitrate_switch(): + msg = _msg(is_fd=True, bitrate_switch=False, data=bytes(64)) + assert frame_duration(msg, 500_000, 2_000_000) == pytest.approx(712 / 500_000) + assert frame_duration(msg, 500_000) == pytest.approx(712 / 500_000) + + +def test_frame_duration_fd_with_bitrate_switch(): + msg = _msg(is_fd=True, bitrate_switch=True, data=bytes(64)) + # SOF to BRS (17 bits) and CRC delimiter to intermission (13 bits) at the + # nominal bitrate, ESI, DLC, 64 data bytes and the CRC field (5 + 512 + 32 bits) + # at the data bitrate + assert frame_duration(msg, 500_000, 2_000_000, bit_stuffing=False) == pytest.approx( + 30 / 500_000 + 549 / 2_000_000 + ) + # 133 worst-case stuff bits, 4 of them in the first 17 bits + assert frame_duration(msg, 500_000, 2_000_000) == pytest.approx( + 34 / 500_000 + 678 / 2_000_000 + ) + + +def test_frame_duration_fd_with_bitrate_switch_needs_data_bitrate(): + msg = _msg(is_fd=True, bitrate_switch=True, data=bytes(8)) + with pytest.raises(ValueError, match="data_bitrate is required"): + frame_duration(msg, 500_000) + + +@pytest.mark.parametrize( + ("bitrate", "data_bitrate"), [(0, None), (-500_000, None), (500_000, 0)] +) +def test_frame_duration_invalid_bitrate(bitrate, data_bitrate): + with pytest.raises(ValueError, match="must be positive"): + frame_duration(_msg(), bitrate, data_bitrate) + + +def _feed(listener: BusLoadListener, timestamps, **kwargs) -> None: + for timestamp in timestamps: + listener.on_message_received(_msg(timestamp=timestamp, **kwargs)) + + +# 111 bits at 500 kbit/s without bit stuffing +CLASSIC_8_BYTES_DURATION = 111 / 500_000 + + +def test_listener_bus_load(): + listener = BusLoadListener(bitrate=500_000, window=1.0, bit_stuffing=False) + assert listener.get_bus_load() == 0.0 + + # one frame every 10 ms + _feed(listener, [i / 100 for i in range(100)], data=bytes(8)) + expected = 100 * 100 * CLASSIC_8_BYTES_DURATION / 1.0 + assert listener.get_bus_load(timestamp=0.995) == pytest.approx(expected) + + # half of the frames have left the window + expected = 100 * 49 * CLASSIC_8_BYTES_DURATION / 1.0 + assert listener.get_bus_load(timestamp=1.5) == pytest.approx(expected) + + assert listener.get_bus_load(timestamp=2.0) == 0.0 + + +def test_listener_window(): + listener = BusLoadListener(bitrate=500_000, window=0.1, bit_stuffing=False) + _feed(listener, [i / 100 for i in range(100)], data=bytes(8)) + # frames at 0.90 to 0.99 + expected = 100 * 10 * CLASSIC_8_BYTES_DURATION / 0.1 + assert listener.get_bus_load(timestamp=0.995) == pytest.approx(expected) + + +def test_listener_discards_old_frames_on_receive(): + listener = BusLoadListener(bitrate=500_000, window=0.95) + _feed(listener, [i / 10 for i in range(100)]) + # only the frames within the window before the newest frame are kept + assert len(listener._frames) == 10 + + +def test_listener_bus_load_with_bit_stuffing(): + listener = BusLoadListener(bitrate=500_000, window=1.0) + _feed(listener, [0.5], data=bytes(8)) + assert listener.get_bus_load(timestamp=1.0) == pytest.approx(100 * 135 / 500_000) + + +def test_listener_out_of_order_frames(): + listener = BusLoadListener(bitrate=500_000, window=1.0, bit_stuffing=False) + _feed(listener, [5.0, 3.0, 5.5], data=bytes(8)) + # the late frame at 3.0 is outside the window + assert listener.get_bus_load(timestamp=5.6) == pytest.approx( + 100 * 2 * CLASSIC_8_BYTES_DURATION + ) + + +def test_listener_ignores_error_frames(): + listener = BusLoadListener(bitrate=500_000) + _feed(listener, [0.0, 0.1], is_error_frame=True) + assert listener.get_bus_load(timestamp=0.5) == 0.0 + + +def test_listener_default_timestamp_advances_while_bus_is_silent(): + listener = BusLoadListener(bitrate=500_000, window=1.0, bit_stuffing=False) + with mock.patch("can.bus_load.time.monotonic", return_value=1000.0): + # message timestamps need not use the same clock as time.monotonic() + _feed(listener, [10.0, 10.5], data=bytes(8)) + assert listener.get_bus_load() == pytest.approx( + 100 * 2 * CLASSIC_8_BYTES_DURATION + ) + with mock.patch("can.bus_load.time.monotonic", return_value=1000.7): + # the window now ends at 11.2, so the frame at 10.0 has left it + assert listener.get_bus_load() == pytest.approx(100 * CLASSIC_8_BYTES_DURATION) + with mock.patch("can.bus_load.time.monotonic", return_value=1001.6): + assert listener.get_bus_load() == 0.0 + + +def test_listener_fd_with_data_bitrate(): + listener = BusLoadListener( + bitrate=500_000, data_bitrate=2_000_000, bit_stuffing=False + ) + _feed(listener, [0.0], is_fd=True, bitrate_switch=True, data=bytes(64)) + assert listener.get_bus_load(timestamp=0.5) == pytest.approx( + 100 * (30 / 500_000 + 549 / 2_000_000) + ) + + +def test_listener_fd_with_bitrate_switch_needs_data_bitrate(): + listener = BusLoadListener(bitrate=500_000) + with pytest.raises(ValueError, match="data_bitrate is required"): + _feed(listener, [0.0], is_fd=True, bitrate_switch=True) + + +def test_listener_from_timing(): + timing = can.BitTiming.from_sample_point( + f_clock=8_000_000, bitrate=250_000, sample_point=87.5 + ) + listener = BusLoadListener(timing=timing) + assert listener.bitrate == 250_000 + assert listener.data_bitrate is None + + timing_fd = can.BitTimingFd.from_sample_point( + f_clock=80_000_000, + nom_bitrate=500_000, + nom_sample_point=80.0, + data_bitrate=2_000_000, + data_sample_point=80.0, + ) + listener = BusLoadListener(timing=timing_fd) + assert listener.bitrate == 500_000 + assert listener.data_bitrate == 2_000_000 + + +@pytest.mark.parametrize( + ("kwargs", "match"), + [ + ({}, "Either bitrate or timing"), + ({"bitrate": 0}, "bitrate must be positive"), + ({"bitrate": 500_000, "data_bitrate": -1}, "data_bitrate must be positive"), + ({"bitrate": 500_000, "window": 0}, "window must be positive"), + ( + { + "bitrate": 500_000, + "timing": can.BitTiming.from_sample_point( + f_clock=8_000_000, bitrate=500_000, sample_point=87.5 + ), + }, + "not both", + ), + ], +) +def test_listener_invalid_arguments(kwargs, match): + with pytest.raises(ValueError, match=match): + BusLoadListener(**kwargs) + + +def test_listener_with_notifier_and_virtual_bus(): + channel = "test_bus_load_virtual" + with ( + can.Bus(interface="virtual", channel=channel) as sender, + can.Bus(interface="virtual", channel=channel) as receiver, + ): + bus_load = can.BusLoadListener(bitrate=500_000, window=10.0) + reader = can.BufferedReader() + with can.Notifier(receiver, [bus_load, reader]): + for i in range(10): + sender.send( + can.Message(arbitration_id=i, is_extended_id=False, data=bytes(8)) + ) + received = [reader.get_message(timeout=1.0) for _ in range(10)] + + assert all(received) + expected = 100 * 10 * (135 / 500_000) / 10.0 + assert bus_load.get_bus_load(timestamp=received[-1].timestamp) == pytest.approx( + expected + )