Skip to content

Add BusLoadListener to measure the bus load - #2180

Open
physicalfleet-dev-team wants to merge 2 commits into
hardbyte:mainfrom
physicalfleet-dev-team:bus-load-listener
Open

physicalfleet-dev-team wants to merge 2 commits into
hardbyte:mainfrom
physicalfleet-dev-team:bus-load-listener

Conversation

@physicalfleet-dev-team

Copy link
Copy Markdown

Hi python-can team! 👋

We drive a lot of CAN servos and motor controllers from Python, and "how busy is this bus?" keeps coming up. Today that means running canbusload next to the program, or writing the frame-length math again in each project. This PR adds it to python-can as a listener, as requested in #1895 and #972.

Summary of Changes

  • New can.BusLoadListener: plug it into a Notifier and call get_bus_load() to get the bus load in percent over a sliding window (1 s by default).
    • Frames are placed in time by msg.timestamp, so it also works when you feed it messages from a log file. By default the window ends at the newest frame's timestamp plus the time since that frame arrived, so the value falls to 0 when the bus goes quiet. You can also pass an explicit timestamp.
    • Accepts bitrate / data_bitrate or a BitTiming / BitTimingFd as timing, the same names can.Bus uses.
    • Error frames are ignored. It's thread-safe, so the notifier thread and the reader can run at the same time.
  • New can.bus_load.frame_bit_length(msg) and can.bus_load.frame_duration(msg, bitrate, data_bitrate), which the listener uses:
    • standard and extended classical CAN frames, and remote frames (no data field)
    • CAN FD with CRC-17/CRC-21, the stuff count and fixed stuff bits, and data padded to the next valid FD length
    • with bitrate switching, ESI, DLC, the data and the CRC field are timed at the data bitrate and everything else at the nominal bitrate
    • worst-case bit stuffing by default (like canbusload), or bit_stuffing=False to leave dynamic stuff bits out
    • lengths include the 3-bit intermission
  • Docs: a BusLoadListener section in doc/notifier.rst with a usage example. News fragment: doc/changelog.d/1895.added.rst.

Usage:

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} %")

Related Issues / Pull Requests

Type of Change

  • Bug fix
  • New feature
  • Documentation update
  • Refactoring
  • Other (please describe):

Checklist

  • I have followed the contribution guide.
  • I have added or updated tests as appropriate.
  • I have added or updated documentation as appropriate.
  • I have added a news fragment for towncrier.
  • All checks and tests pass (tox). I ran the individual tools rather than tox; see below.

Additional Notes

How I tested it (Python 3.12, M1 Mac):

  • pytest test/test_bus_load.py: 41 new tests, all passing. The expected classical CAN lengths come from the worst-case formula in Davis et al. (2007), e.g. 135 and 160 bits for 8-byte standard and extended frames. The CAN FD values are worked out field by field from ISO 11898-1. The tests also cover FD timing with and without bitrate switching, the listener's window and eviction, out-of-order frames, the clock advancing while the bus is quiet, timing=, argument validation, and a run through Notifier with two virtual buses.
  • Full pytest: 805 passed, 117 skipped. The 5 failures are test_logger.py / test_scripts.py failing on the argparse --help assertion under Python 3.12, and they fail on main here too.
  • black --check ., ruff check can examples doc, pylint can/bus_load.py can/__init__.py (10.00/10), and mypy --python-version 3.11 . / 3.12 / 3.13 / 3.14, all clean.
  • sphinx -b html -Wan: no new warnings. The only warnings are the bcm.rst reference and the can.logger -h program output, and both appear on main too.

Open points you may have views on:

  • Naming: I went with BusLoadListener / get_bus_load() and a new can.bus_load module. Happy to rename, or to move the frame-length functions into can.util.
  • Stuffing is worst-case or off. Counting the exact stuff bits for each frame needs the CRC and a bit-by-bit model. That could come in a follow-up if you'd like it.
  • A natural next step would be showing the value in the can.viewer header. I left that out to keep this PR focused.

Thanks for maintaining python-can, it's a pleasure to build on! 😊

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.
@physicalfleet-dev-team

physicalfleet-dev-team commented Dec 4, 2026 •

Copy link
Copy Markdown
Author

Thanks for approving the workflow run! 🙂 The one red job, test (ubuntu-latest, pypy312), failed in test/back2back_test.py::TestThreadSafeBus::test_send_periodic_duration. No periodic message arrived before the receive timeout, so messages[-1] raised an IndexError. This PR doesn't touch that test or the periodic send code. It's a timing flake that has failed the same way elsewhere, e.g. in the main push runs 46168335717 and 46166955572. The other 20 test jobs passed, including pypy312 on macOS and Windows, and so did docs, packaging and static analysis.

On my machine (macOS, CPython 3.12), the periodic tests in back2back_test.py plus test/test_bus_load.py passed on 3 out of 3 runs. Could you re-run that job when you get a chance?

@zariiii9003

Copy link
Copy Markdown
Collaborator

AI Review: Add BusLoadListener to measure the bus load (#2180)

Checked against ISO 11898-1:2015. Field lengths (§10.4.2), the fixed stuff bits in the FD CRC field (§10.5), CRC-17/21 selection, FD length padding and the 13-bit trailer are correct.

Findings

can/bus_load.py

  • BRS bit and CRC delimiter are both timed at the nominal bitrate (_frame_bits, BRS branch). ISO 11898-1:2015, §11.3.1.1, NOTE: the bit rate switches at the sample points of these two bits, so together they last one nominal plus one data bit time. A 0-byte FBFF frame comes out 2–3 % too long (76.0 µs instead of 74.5 µs at 500 kbit/s / 2 Mbit/s). Fix: return arbitration + _TRAILER_BITS - 1, data + 1, and update the frame_duration docstring and the expected values in test_frame_duration_fd_with_bitrate_switch and test_listener_fd_with_data_bitrate (29 nominal + 550 data bits).
  • get_bus_load(timestamp=...) silently returns wrong values for windows before the newest frame. on_message_received drops frames older than newest timestamp - window. After feeding a 10 s log, get_bus_load(timestamp=5.0) returns 0.0 instead of 2.22 %. The class docstring says the listener works with log files, and the timestamp docs only say it "should not decrease between calls". Fix: document that timestamp must not be earlier than the newest received frame's timestamp, or raise ValueError when it is.
  • "Worst-case number of stuff bits" (docstrings of frame_bit_length, BusLoadListener) is an upper bound that no frame reaches. It is 1 bit too high for CEFF and FBFF and 2 bits too high for FEFF. For FD frames, ISO 11898-1:2015, §10.5 also forbids a dynamic stuff bit directly before the first fixed stuff bit, which (n - 1) // 4 counts when n ≡ 1 (mod 4). Fix: call it an upper bound (Davis et al. 2007) in the docstrings and doc/notifier.rst.

test/test_bus_load.py

  • Remove test_listener_with_notifier_and_virtual_bus. It takes 1.0 s, nearly the whole file's runtime, spent in the Notifier's stop timeout. Every code break it detects is also detected by test_listener_bus_load_with_bit_stuffing.
  • Remove the (-500_000, None) case of test_frame_duration_invalid_bitrate. It exercises the same <= 0 branch as (0, None).
  • Merge test_listener_bus_load into test_listener_window. Every code break the former detects is detected by another test.
  • test_listener_discards_old_frames_on_receive asserts on the private _frames. Check the eviction through get_bus_load instead.
  • test_listener_window does not test the window start in get_bus_load. It stays green when the window start is timestamp - 1.0, because eviction on receive already drops the frames. Query at a timestamp later than the newest frame.
  • Nothing tests the default window end with out-of-order frames. Replacing msg.timestamp >= self._last_timestamp with True keeps all tests green. Extend test_listener_out_of_order_frames to call get_bus_load() without timestamp under a mocked time.monotonic.

Verdict

request changes

- Time the BRS bit and the CRC delimiter as one nominal and one data bit,
  since the bitrate switches at their sample points (ISO 11898-1:2015,
  11.3.1.1). A 0-byte FBFF frame at 500 kbit/s / 2 Mbit/s without
  stuffing now takes 74.5 us instead of 76.0 us.
- get_bus_load() raises ValueError for an explicit timestamp whose window
  starts before frames that were already discarded (earlier than the
  newest frame or a previous call) instead of returning a wrong value.
- Call the stuff bit count an upper bound (Davis et al., 2007) in the
  docstrings and doc/notifier.rst.
- Tests: drop the slow Notifier/virtual bus test and a redundant invalid
  bitrate case, merge test_listener_bus_load into test_listener_window and
  check the window start after the newest frame, check eviction through
  get_bus_load(), cover the default window end with out-of-order frames.
@physicalfleet-dev-team

Copy link
Copy Markdown
Author

Thanks a lot for the careful review, @zariiii9003! Everything is addressed in caef548 :)

  • BRS bit / CRC delimiter: now one nominal plus one data bit (arbitration + _TRAILER_BITS - 1, data + 1). The frame_duration docstring and both FD tests are updated (29 nominal + 550 data bits). A 0-byte FBFF frame at 500 kbit/s / 2 Mbit/s without stuffing now takes 74.5 µs.
  • get_bus_load(timestamp=...) before the newest frame: it now raises ValueError if the window would start before frames that were already discarded, i.e. for a timestamp earlier than the newest frame or than a previous call. The docstring says so too. The default timestamp=None path never raises.
  • Stuff bits: the docstrings and doc/notifier.rst now call it an upper bound (Davis et al. 2007).
  • Tests: I applied all six suggestions. The Notifier/virtual bus test and the (-500_000, None) case are gone, and test_listener_bus_load is merged into test_listener_window, which now also queries after the newest frame. Eviction is checked through get_bus_load(). test_listener_out_of_order_frames now receives the late frame last and calls get_bus_load() under a mocked time.monotonic.

Verified locally on Python 3.12: test/test_bus_load.py 39 passed in 0.04 s. Each of these mutations now fails at least one test: your two (True for the timestamp check, window start timestamp - 1.0), no eviction on receive, and the old BRS split. black, ruff, pylint and mypy are clean on the changed files. The full suite gives the same result as on 062f297: 5 failures in test_logger.py/test_scripts.py, all from an argparse usage assertion in my local Python 3.12 when can.logger formats its help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add CAN bus utilization tracking Calculate Bus-Load

2 participants