Skip to main content

Behavioral models

A behavioral model is a reusable component that emulates the behavior of a real ECU. It receives frames, reacts to them, and sends frames, like the ECU does. Use one when a mock isn't enough, because the tests need the ECU to react to its inputs.

Behavioral models are typically written in Python with the RemotiveTopology framework, remotivelabs-topology. An FMU can also run as a behavioral model.

A behavioral model runs in its own container, next to the RemotiveBroker of the ECU, and communicates with the channels through that RemotiveBroker. See What runs in a topology.

A hazard light model for the BCM​

This model implements the hazard light function of the BCM in the sample vehicle. When the hazard light button frame from SCCM arrives on DriverCan, it sets both turn light requests on BodyCan to the state of the button:

The model is a Python package with the logic in model.py and the setup in __main__.py:

models/bcm/
├── Dockerfile
└── bcm/
├── __init__.py
├── __main__.py
└── model.py

bcm/model.py contains the logic:

from dataclasses import dataclass

from remotivelabs.broker import Frame
from remotivelabs.topology.namespaces.can import CanNamespace


@dataclass
class BCM:
body_can: CanNamespace

async def on_hazard_light(self, frame: Frame) -> None:
hazard_signal = frame.signals["HazardLightButton.HazardLightButton"]
await self.body_can.restbus.update_signals(
("TurnLightControl.RightTurnLightRequest", hazard_signal),
("TurnLightControl.LeftTurnLightRequest", hazard_signal),
)

bcm/__main__.py connects the logic to the topology:

import logging

from remotivelabs.broker import BrokerClient
from remotivelabs.topology.behavioral_model import BehavioralModel
from remotivelabs.topology.cli import run
from remotivelabs.topology.cli.behavioral_model import BehavioralModelArgs
from remotivelabs.topology.namespaces import filters
from remotivelabs.topology.namespaces.can import CanNamespace, RestbusConfig

from bcm.model import BCM


async def main(args: BehavioralModelArgs) -> None:
async with BrokerClient(url=args.url, auth=args.auth) as broker_client:
# Sends the frames that BCM sends on BodyCan, at their cycle times
body_can = CanNamespace(
"BCM-BodyCan",
broker_client,
restbus_configs=[
RestbusConfig([filters.SenderFilter(ecu_name="BCM")], delay_multiplier=args.delay_multiplier)
],
)
# Only used to receive frames
driver_can = CanNamespace("BCM-DriverCan", broker_client)

bcm = BCM(body_can)

async with BehavioralModel(
"BCM",
broker_client=broker_client,
namespaces=[body_can, driver_can],
input_handlers=[
driver_can.create_input_handler(
[filters.FrameFilter("HazardLightButton")],
bcm.on_hazard_light,
)
],
) as bm:
await bm.run_forever()


if __name__ == "__main__":
args = BehavioralModelArgs.parse()
logging.basicConfig(level=args.loglevel)
run(main(args))

bcm/__init__.py is empty.

Structure of a model​

Most behavioral models have the same parts as the example.

BehavioralModelArgs​

When RemotiveTopology runs the model, it passes settings from the topology to the container, such as the URL of the RemotiveBroker of the ECU. BehavioralModelArgs.parse() reads them into a data class, with url, auth, delay_multiplier, and loglevel. Use these instead of hard-coding a URL, so the same model runs in any topology.

Start the model with run from remotivelabs.topology.cli instead of asyncio.run. It works the same, but also stops the model cleanly when the container stops.

BrokerClient​

BrokerClient, from the remotivelabs-broker library, is the connection to the RemotiveBroker of the ECU. Use it as an async context manager, so the connection closes when the model stops.

CanNamespace​

A namespace is how the ECU sees a channel, named <ECU>-<Channel>, see Namespaces. Create one namespace object for each channel the model uses. CanNamespace uses the signal databases of the namespace to encode and decode frames, so the model works with signal names, such as TurnLightControl.LeftTurnLightRequest, instead of bytes. Signal names include the frame name.

A namespace can have a restbus, which sends frames at their cycle time from the signal database. RestbusConfig chooses which frames, with filters: filters.SenderFilter(ecu_name="BCM") selects all frames that BCM sends. The restbus starts with the default values from the signal database, and restbus.update_signals changes the values it sends from then on.

There are namespace classes for other protocols too, such as LinNamespace and SomeIPNamespace. See remotivelabs.topology.namespaces.

BehavioralModel​

BehavioralModel runs the model. It opens the namespaces and starts their restbuses, calls your callbacks when frames arrive, and answers control requests. run_forever() keeps it running until the container stops.

  • Input handlers connect frames to callbacks. create_input_handler takes filters, such as filters.FrameFilter("HazardLightButton"), and an async callback that receives the Frame. By default a callback is only called when a signal in the frame has changed, not for every cyclic frame. Pass on_change=False to BehavioralModel to get every frame.
  • Control requests are messages that tests send to the model to set it up, which don't exist in the vehicle. The name of the model, "BCM", is the ECU that receives them. Every model answers a PingRequest, which tests use to wait until the model has started, and a RebootRequest, which resets its restbuses to their default values. See Writing tests.

You can add your own control requests with control_handlers, for example to put the model in a specific state. Use them carefully: a test that depends on them can't run against the real ECU or hardware.

The logic​

Keep the logic of the model in a class of its own, like BCM in the example, separate from the setup code. That makes it easier to read, and to unit test.

Run the model in the topology​

Build the model into a container image. models/bcm/Dockerfile:

FROM python:3.12-slim
RUN pip install remotivelabs-topology
WORKDIR /app
COPY bcm/ bcm/

Then add the model to its ECU in an instance file. An ECU can have several models, but each model must have a unique name:

ecus:
BCM:
models:
bcm:
type: container
container:
build:
context: ../models/bcm
dockerfile: ../models/bcm/Dockerfile
command: python -m bcm

The container properties are described in the container schema. They mirror the service properties in Docker Compose.

After you change the Python code, rebuild the container image when you start the topology, with docker compose -f output/my-vehicle/docker-compose.yml up --build. You don't need to run remotive topology build again.

To combine models with a mock on the same ECU, see Combining mocks and behavioral models.

Unit test a model​

The tests that run in the topology check the model together with the other ECUs. For logic with many cases, also write unit tests that run without a topology, in milliseconds.

Since the logic is separate from the setup code, a unit test can give it a fake namespace and a fake frame. models/bcm/tests/test_model.py:

from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock

import pytest

from bcm.model import BCM


@pytest.mark.asyncio
async def test_hazard_button_turns_on_both_turn_lights():
body_can = MagicMock()
body_can.restbus.update_signals = AsyncMock()
bcm = BCM(body_can)

await bcm.on_hazard_light(SimpleNamespace(signals={"HazardLightButton.HazardLightButton": 1}))

body_can.restbus.update_signals.assert_awaited_once_with(
("TurnLightControl.RightTurnLightRequest", 1),
("TurnLightControl.LeftTurnLightRequest", 1),
)

Run it with python -m pytest in models/bcm, with remotivelabs-topology, pytest, and pytest-asyncio installed.

For larger models, go further: keep the state of the ECU, such as a state machine for the turn lights, in plain Python classes that don't use the framework at all, and let the callbacks only translate between frames and those classes. The RemotiveCar example in the examples repository has behavioral models built this way, with unit tests.

Learn more​