Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions can/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"BufferedReader",
"Bus",
"BusABC",
"BusLoadListener",
"BusState",
"CSVReader",
"CSVWriter",
Expand Down Expand Up @@ -57,6 +58,7 @@
"bit_timing",
"broadcastmanager",
"bus",
"bus_load",
"ctypesutil",
"detect_available_configs",
"exceptions",
Expand Down Expand Up @@ -88,6 +90,7 @@
RestartableCyclicTaskABC,
)
from .bus import BusABC, BusState, CanProtocol
from .bus_load import BusLoadListener
from .exceptions import (
CanError,
CanInitializationError,
Expand Down
310 changes: 310 additions & 0 deletions can/bus_load.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,310 @@
"""
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 math
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 an upper bound on the number of stuff bits in a bit stream.

After the first bit, a stuff bit can be needed at most every 4 bits,
e.g. for ``1 1111 0000 1111 0000``. This is the bound from Davis et al.,
"Controller Area Network (CAN) schedulability analysis: Refuted, revisited
and revised" (2007). The fixed bits of the frame format rule out some of
these patterns, so real frames usually have fewer stuff bits.
"""
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:
# The bitrate switches at the sample points of the BRS bit and of the
# CRC delimiter (ISO 11898-1:2015, 11.3.1.1), so these two bits together
# last one nominal and one data bit time. Count the BRS bit at the nominal
# bitrate and the CRC delimiter at the data bitrate.
return arbitration + _TRAILER_BITS - 1, data + 1
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 an upper bound on the number of stuff
bits (Davis et al., 2007). 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 at the sample points of the BRS bit
and the CRC delimiter (ISO 11898-1:2015, 11.3.1.1), so these two bits together
take one nominal and one data bit time.

: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 an upper bound on the 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 an upper bound on the number of stuff
bits (Davis et al., 2007), 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 an upper bound on the 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
# frames up to this timestamp have been discarded
self._discarded_until: float = -math.inf
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 that leave the window are discarded, so ``timestamp`` must not
be earlier than the timestamp of the newest received frame or than
``timestamp`` in a previous call. To follow the bus load of a log
file over time, call this method while feeding the frames in order.
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.
:raises ValueError:
if ``timestamp`` is earlier than the newest received frame or than
``timestamp`` in a previous call, because the frames needed for that
window have already been discarded.
"""
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
)
elif timestamp - self.window < self._discarded_until:
raise ValueError(
f"timestamp {timestamp} is earlier than the newest received "
"frame or a previous call; the frames of that window have "
"already been discarded"
)
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:
self._discarded_until = max(self._discarded_until, timestamp)
while self._frames and self._frames[0][0] <= timestamp:
self._frames.popleft()
1 change: 1 addition & 0 deletions doc/changelog.d/1895.added.rst
Original file line number Diff line number Diff line change
@@ -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.
38 changes: 38 additions & 0 deletions doc/notifier.rst
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,41 @@ 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``.

By default, each frame is counted with an upper bound on its number of stuff bits
(Davis et al., "Controller Area Network (CAN) schedulability analysis: Refuted,
revisited and revised", 2007). Real frames usually have fewer, so the result tends
to be higher than the real bus load. Pass ``bit_stuffing=False`` to leave dynamic
stuff bits out.

.. 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
Loading