remotivelabs.topology.behavioral_model

Examples

remotivelabs.topology.behavioral_model.BehavioralModel instances in RemotiveTopology run on top of RemotiveBroker, allowing them to use real network protocols such as CAN buses or SOME/IP networks.

The example below shows the simplest possible behavioral model - it connects to a broker and handles built-in control messages (ping, reboot), but performs no other work:

from remotivelabs.broker import BrokerClient

from remotivelabs.topology.behavioral_model import BehavioralModel
from remotivelabs.topology.cli import run


async def main():
    async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
        async with BehavioralModel(
            "BodyCanModule",
            broker_client=broker_client,
        ) as bm:
            await bm.run_forever()


if __name__ == "__main__":
    run(main())

Adding namespaces

To interact with a network, provide one or more namespaces (see remotivelabs.topology.namespaces). The example below adds a remotivelabs.topology.namespaces.can.CanNamespace configured with a remotivelabs.topology.namespaces.generic.RestbusConfig that periodically sends all CAN frames the ECU is listed as sender of:

import asyncio

from remotivelabs.broker import BrokerClient

from remotivelabs.topology.behavioral_model import BehavioralModel
from remotivelabs.topology.namespaces import filters
from remotivelabs.topology.namespaces.can import CanNamespace, RestbusConfig


async def main():
    async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
        driver_can_0 = CanNamespace(
            "HazardLightControlUnit-DriverCan0",
            broker_client,
            restbus_configs=[RestbusConfig([filters.SenderFilter(ecu_name="HazardLightControlUnit")])],
        )
        async with BehavioralModel(
            "HazardLightControlUnit",
            namespaces=[driver_can_0],
            broker_client=broker_client,
        ) as bm:
            await bm.run_forever()


if __name__ == "__main__":
    asyncio.run(main())

Reacting to incoming frames

The examples so far only send frames. To react to incoming frames, attach an input handler. A namespace builds one with its create_input_handler() method: given a set of filters (see remotivelabs.topology.namespaces.filters), the handler subscribes to every matching frame and invokes the provided async callback each time one arrives. Passing the handler to BehavioralModel(input_handlers=[...]) wires it into the lifecycle - it starts with the model and stops with it.

By default, BehavioralModel delivers frames to input handlers only when at least one of their signals has changed (on_change=True). The delivered frame still contains all signals, unchanged ones included. Pass on_change=False if a handler needs to fire on every transmission.

The example below reacts to a single CAN frame:

import asyncio

from remotivelabs.broker import BrokerClient, Frame
from remotivelabs.broker.filters import FrameFilter

from remotivelabs.topology.behavioral_model import BehavioralModel
from remotivelabs.topology.namespaces.can import CanNamespace


async def _on_hazard_button_pressed(frame: Frame) -> None:
    print(f"Hazard light frame received: {frame}")


async def main():
    async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
        driver_can_0 = CanNamespace("BodyCanModule-DriverCan0", broker_client)

        async with BehavioralModel(
            "BodyCanModule",
            namespaces=[driver_can_0],
            broker_client=broker_client,
            input_handlers=[
                driver_can_0.create_input_handler(
                    [FrameFilter("HazardLightButton")],
                    _on_hazard_button_pressed,
                )
            ],
        ) as bm:
            await bm.run_forever()


if __name__ == "__main__":
    asyncio.run(main())

Excluding noisy signals

Some frames carry signals that change on every transmission but aren't particularly interesting to user code - E2E counters and CRCs are a common example. With on-change delivery, those signals can be enough on their own to wake an input handler on every cycle, even when the rest of the payload is unchanged.

One way to avoid that is to attach a filter to BehavioralModel(input_filters=[...]), which is applied to every input handler on the model. For E2E, passing remotivelabs.broker.filters.E2eSignalsFilter with exclude=True drops the CRC and counter entirely - they no longer take part in change detection, and they don't appear on the frames delivered to your callbacks either.

Per-handler filters remain available on create_input_handler(...) when a single handler needs different treatment.

import asyncio

from remotivelabs.broker import BrokerClient, Frame
from remotivelabs.broker.filters import FrameFilter

from remotivelabs.topology.behavioral_model import BehavioralModel
from remotivelabs.topology.namespaces.can import CanNamespace
from remotivelabs.topology.namespaces.filters import E2eSignalsFilter


async def _on_brake_pedal(frame: Frame) -> None:
    # Callback fires only when payload signals change, not when the E2E
    # counter ticks or the CRC is recomputed on an otherwise identical frame.
    print(f"Brake pedal frame received: {frame}")


async def main():
    async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
        driver_can_0 = CanNamespace("BodyCanModule-DriverCan0", broker_client)

        async with BehavioralModel(
            "BodyCanModule",
            namespaces=[driver_can_0],
            broker_client=broker_client,
            input_filters=[E2eSignalsFilter(exclude=True)],
            input_handlers=[
                driver_can_0.create_input_handler(
                    [FrameFilter("BrakePedalPositionSensor")],
                    _on_brake_pedal,
                )
            ],
        ) as bm:
            await bm.run_forever()


if __name__ == "__main__":
    asyncio.run(main())

Subclassing for custom control handlers

For a more advanced pattern, subclass remotivelabs.topology.behavioral_model.BehavioralModel to encapsulate namespaces and custom control handlers. Note that adding custom control messages introduces behaviour that cannot be replicated on real hardware:

import asyncio
from dataclasses import dataclass
from typing import Final

from remotivelabs.broker import BrokerClient

from remotivelabs.topology.behavioral_model import BehavioralModel
from remotivelabs.topology.control.request import ControlRequest
from remotivelabs.topology.control.response import ControlResponse
from remotivelabs.topology.namespaces import filters
from remotivelabs.topology.namespaces.can import CanNamespace, RestbusConfig


@dataclass
class ResetRestbus(ControlRequest):
    """Custom control request to reset the restbus to signal database defaults."""

    type: str = "reset_restbus"


class HazardLightControlUnit(BehavioralModel):
    """Behavioral model for the HazardLightControlUnit ECU."""

    ecu_name: Final[str] = "HazardLightControlUnit"

    def __init__(self, broker_client: BrokerClient) -> None:
        self._can_ns = CanNamespace(
            name=f"{self.ecu_name}-DriverCan0",
            broker_client=broker_client,
            restbus_configs=[RestbusConfig([filters.SenderFilter(ecu_name=self.ecu_name)])],
        )
        super().__init__(
            name=self.ecu_name,
            broker_client=broker_client,
            namespaces=[self._can_ns],
            control_handlers=[
                (ResetRestbus.type, self.on_reset_restbus),
            ],
        )

    async def on_reset_restbus(self, request: ControlRequest) -> ControlResponse:  # noqa: ARG002
        await self._can_ns.restbus.reset()
        return ControlResponse(status="ok")


async def main():
    async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
        async with HazardLightControlUnit(broker_client=broker_client) as bm:
            await bm.run_forever()


if __name__ == "__main__":
    asyncio.run(main())
 1"""
 2# Examples
 3<!-- start-include -->
 4
 5`remotivelabs.topology.behavioral_model.BehavioralModel` instances in RemotiveTopology run on top of RemotiveBroker, allowing them to use
 6real network protocols such as CAN buses or SOME/IP networks.
 7
 8The example below shows the simplest possible behavioral model - it connects to a broker and handles
 9built-in control messages (ping, reboot), but performs no other work:
10
11```python
12.. include:: ../_docs/snippets/behavioral_model.py
13```
14
15<!-- end-include -->
16
17## Adding namespaces
18
19To interact with a network, provide one or more namespaces (see `remotivelabs.topology.namespaces`).
20The example below adds a `remotivelabs.topology.namespaces.can.CanNamespace` configured with a
21`remotivelabs.topology.namespaces.generic.RestbusConfig` that periodically sends all CAN frames the
22ECU is listed as sender of:
23
24```python
25.. include:: ../_docs/snippets/behavioral_model_ns.py
26```
27
28## Reacting to incoming frames
29
30The examples so far only send frames. To react to incoming frames, attach an input handler. A
31namespace builds one with its `create_input_handler()` method: given a set of filters (see
32`remotivelabs.topology.namespaces.filters`), the handler subscribes to every matching frame and
33invokes the provided async callback each time one arrives. Passing the handler to
34`BehavioralModel(input_handlers=[...])` wires it into the lifecycle - it starts with the model and
35stops with it.
36
37By default, `BehavioralModel` delivers frames to input handlers only when at least one of their
38signals has changed (`on_change=True`). The delivered frame still contains all signals, unchanged
39ones included. Pass `on_change=False` if a handler needs to fire on every transmission.
40
41The example below reacts to a single CAN frame:
42
43```python
44.. include:: ../_docs/snippets/input_handlers.py
45```
46
47## Excluding noisy signals
48
49Some frames carry signals that change on every transmission but aren't particularly interesting to
50user code - E2E counters and CRCs are a common example. With on-change delivery, those signals can
51be enough on their own to wake an input handler on every cycle, even when the rest of the payload
52is unchanged.
53
54One way to avoid that is to attach a filter to `BehavioralModel(input_filters=[...])`, which is
55applied to every input handler on the model. For E2E, passing
56`remotivelabs.broker.filters.E2eSignalsFilter` with `exclude=True` drops the CRC and
57counter entirely - they no longer take part in change detection, and they don't appear on the
58frames delivered to your callbacks either.
59
60Per-handler filters remain available on
61`create_input_handler(...)` when a single handler needs different treatment.
62
63```python
64.. include:: ../_docs/snippets/behavioral_model_e2e_filter.py
65```
66
67## Subclassing for custom control handlers
68
69For a more advanced pattern, subclass `remotivelabs.topology.behavioral_model.BehavioralModel` to encapsulate namespaces and custom control
70handlers. Note that adding custom control messages introduces behaviour that cannot be replicated on
71real hardware:
72
73```python
74.. include:: ../_docs/snippets/behavioral_model_class_control.py
75```
76"""
77
78import logging
79
80from remotivelabs.topology.behavioral_model.behavioral_model import (
81    BehavioralModel,
82    PingRequest,
83    RebootRequest,
84)
85
86# Disable library logging by default
87_logger = logging.getLogger("remotivelabs.topology")
88_logger.addHandler(logging.NullHandler())
89
90__all__ = [
91    "BehavioralModel",
92    "PingRequest",
93    "RebootRequest",
94]
class BehavioralModel:
 60class BehavioralModel:
 61    """
 62    A BehavioralModel is used to emulate some behavior instead of a real ECU.
 63
 64    It manages lifecycle operations for namespaces (e.g., `CanNamespace`, `SomeIPNamespace`), handles inputs,
 65    routes control requests, and provides a unified interface for testing setups.
 66    """
 67
 68    _control_server: ControlServer
 69    _control_server_task: asyncio.Task | None
 70    _namespace_tasks: list[asyncio.Task]
 71    _name: str
 72
 73    def __init__(  # noqa: PLR0913
 74        self,
 75        name: str,
 76        broker_client: BrokerClient,
 77        namespaces: list[Namespace] | None = None,
 78        input_handlers: list[tuple[NamespaceName, InputHandler]] | None = None,
 79        control_handlers: list[tuple[str, Handler]] | None = None,
 80        input_filters: Sequence[FilterLike] | None = None,
 81        on_change: bool = True,
 82    ):
 83        """
 84        Initialize the BehavioralModel instance.
 85
 86        Prometheus metrics are opt-in: set the ``METRICS_PORT`` environment variable to
 87        enable a process-wide exporter that serves ``/metrics`` on that port.
 88
 89        Args:
 90            name: Identifier for the ECU stub instance, then name which receives control messages.
 91            broker_client: The client used for communication with the broker.
 92            namespaces: list of Namespace instances (`CanNamespace`, `SomeIPNamespace`, etc.).
 93            input_handlers: Optional list of (namespace, handler) pairs to receive callbacks
 94                on inputs. Create these using the namespace's `create_input_handler` method.
 95            control_handlers: Optional list of (command, handler) pairs for routing control messages.
 96            input_filters: Optional filters applied to every input handler across all namespaces.
 97                                            Useful for cross-cutting concerns like excluding E2E signals:
 98                                            `input_filters=[E2eSignalsFilter(exclude=True)]`.
 99            on_change: When `True` (default), a frame is only delivered when at least one of its signals
100                       has changed. The delivered frame always contains all signals, including unchanged
101                       ones. When `False`, every frame is delivered regardless of whether its signals
102                       have changed.
103
104        Note:
105            Start the instance using a context manager:
106                ```python
107                async with BehavioralModel(...) as bm:
108                    ...
109                    await bm.run_forever()
110                ```
111            Or use the start/stop methods directly:
112                ```python
113                bm = BehavioralModel(...)
114                await bm.start()
115                # ...
116                await bm.stop()
117                ```
118        """
119        self._broker_client = broker_client
120        self._namespaces = {ns.name: ns for ns in namespaces or []}
121        self._input_handlers = input_handlers or []
122        self._on_change = OnChangeMode.MERGED if on_change else OnChangeMode.OFF
123        self._name = name
124        self._control_server_task = None
125        self._namespace_tasks = []
126
127        missing = sorted({ns_name for ns_name, _ in self._input_handlers} - set(self._namespaces))
128        if missing:
129            raise ValueError(
130                f"Input handlers registered for unknown namespace(s) {missing}. "
131                f"Add the corresponding Namespace instance(s) to `namespaces=`."
132            )
133
134        if input_filters and self._input_handlers:
135            for _, h in self._input_handlers:
136                h.extend_filters(input_filters)
137
138        router = Router(
139            fallback_handler=Router(
140                [
141                    (str(PingRequest.type), self._ping_v1),
142                    (str(RebootRequest.type), self._reboot_v1),
143                ]
144            )
145        )
146        router.add_routes(control_handlers or [])
147        self._control_server = ControlServer(name=name, broker_client=broker_client, handler=router)
148
149        _logger.debug(f"BehavioralModel {self._name} using broker at {broker_client.url}")
150
151    def is_running(self) -> bool:
152        """Has the BehavioralModel been started?"""
153        return self._control_server_task is not None
154
155    async def start(self) -> None:
156        """
157        Start the behavioral model, open all namespaces, and initialize input handlers.
158        This is an idempotent operation - calling it multiple times has no additional effect.
159        """
160        if self.is_running():
161            return
162
163        try:
164            ready_event = asyncio.get_running_loop().create_future()
165            self._control_server_task = asyncio.create_task(self._control_server.serve_forever(ready_event))
166            await ready_event
167
168            for ns in self._namespaces.values():
169                await ns.open()
170
171            for namespace_name, handler in self._input_handlers:
172                frame_infos = await self._broker_client.list_frame_infos(namespace_name)
173                for fi in frame_infos:
174                    handler.add(fi)
175                subs = handler.subscriptions()
176                if not subs:
177                    raise ValueError(f"Input handler {handler} did not yield any subscriptions on namespace '{namespace_name}'")
178                ns = self._namespaces[namespace_name]
179
180                async def _wrapped(frame: Frame, h: InputHandler = handler) -> None:
181                    result = await h.handle(frame)
182                    if result is not None:
183                        await self._broker_client.publish(result)
184
185                await ns._subscribe(
186                    subs,
187                    _wrapped,
188                    on_change=self._on_change,
189                    decode_named_values=False,
190                    callback_label=handler.callback_label,
191                )
192
193            self._namespace_tasks = [asyncio.create_task(ns.run_forever()) for ns in self._namespaces.values()]
194
195            await self._broker_client.restbus.start(*(ns.name for ns in self._namespaces.values() if isinstance(ns, GenericNamespace)))
196
197            _logger.debug(f"BehavioralModel '{self._name}' opened using: {__version__}")
198        except Exception as e:
199            await self._teardown()
200            raise BehavioralModelStartError(name=self._name) from e
201
202    async def stop(self) -> None:
203        """
204        Stop the behavioral model, close all namespaces, and clean up resources.
205        This is an idempotent operation - calling it multiple times has no additional effect.
206        """
207        if not self.is_running():
208            return
209        await self._teardown()
210
211    async def _teardown(self) -> None:
212        """Cancel tasks, close namespaces, reset state. Idempotent; safe to call from a partially-started state."""
213        tasks = list(self._namespace_tasks)
214        if self._control_server_task is not None:
215            tasks.append(self._control_server_task)
216
217        for task in tasks:
218            if not task.done():
219                task.cancel()
220
221        if tasks:
222            await asyncio.gather(*tasks, return_exceptions=True)
223
224        self._namespace_tasks = []
225        self._control_server_task = None
226
227        for ns in self._namespaces.values():
228            try:
229                await ns.close()
230            except Exception:
231                _logger.exception(f"Error closing namespace '{ns.name}' during teardown")
232
233        _logger.debug(f"BehavioralModel '{self._name}' closed")
234
235    async def __aenter__(self) -> Self:
236        await self.start()
237        return self
238
239    async def __aexit__(self, exc_type, exc_value, traceback) -> None:
240        await self.stop()
241
242    async def run_forever(self) -> None:
243        """Run the BehavioralModel indefinitely, processing inputs and control requests."""
244        if self._control_server_task is None:
245            raise RuntimeError("BehavioralModel must be started before calling run_forever")
246
247        _logger.debug(f"BehavioralModel '{self._name}' running")
248        await asyncio.gather(*self._namespace_tasks, self._control_server_task)
249
250    async def reset_restbuses(self) -> None:
251        """Reset the restbus frames this model added, in all namespaces, to their default values."""
252        for ns in self._namespaces.values():
253            if isinstance(ns, GenericNamespace):
254                await ns.restbus.reset()
255
256    # Control request handlers
257    async def _ping_v1(self, request: ControlRequest) -> ControlResponse:  # noqa: ARG002
258        return ControlResponse(status="ok", data=None)
259
260    async def _reboot_v1(self, request: ControlRequest) -> ControlResponse:  # noqa: ARG002
261        await self.reset_restbuses()
262        return ControlResponse(status="ok", data=None)

A BehavioralModel is used to emulate some behavior instead of a real ECU.

It manages lifecycle operations for namespaces (e.g., CanNamespace, SomeIPNamespace), handles inputs, routes control requests, and provides a unified interface for testing setups.

BehavioralModel( name: str, broker_client: remotivelabs.broker.client.BrokerClient, namespaces: list[remotivelabs.topology.namespaces.namespace.Namespace] | None = None, input_handlers: list[tuple[str, remotivelabs.topology.namespaces.input_handlers.InputHandler]] | None = None, control_handlers: list[tuple[str, remotivelabs.topology.control.Handler]] | None = None, input_filters: Optional[Sequence[Union[remotivelabs.broker.filters.FrameFilterPredicate, remotivelabs.broker.filters.SignalFilterPredicate, remotivelabs.broker.filters.FrameSignalFilter]]] = None, on_change: bool = True)
 73    def __init__(  # noqa: PLR0913
 74        self,
 75        name: str,
 76        broker_client: BrokerClient,
 77        namespaces: list[Namespace] | None = None,
 78        input_handlers: list[tuple[NamespaceName, InputHandler]] | None = None,
 79        control_handlers: list[tuple[str, Handler]] | None = None,
 80        input_filters: Sequence[FilterLike] | None = None,
 81        on_change: bool = True,
 82    ):
 83        """
 84        Initialize the BehavioralModel instance.
 85
 86        Prometheus metrics are opt-in: set the ``METRICS_PORT`` environment variable to
 87        enable a process-wide exporter that serves ``/metrics`` on that port.
 88
 89        Args:
 90            name: Identifier for the ECU stub instance, then name which receives control messages.
 91            broker_client: The client used for communication with the broker.
 92            namespaces: list of Namespace instances (`CanNamespace`, `SomeIPNamespace`, etc.).
 93            input_handlers: Optional list of (namespace, handler) pairs to receive callbacks
 94                on inputs. Create these using the namespace's `create_input_handler` method.
 95            control_handlers: Optional list of (command, handler) pairs for routing control messages.
 96            input_filters: Optional filters applied to every input handler across all namespaces.
 97                                            Useful for cross-cutting concerns like excluding E2E signals:
 98                                            `input_filters=[E2eSignalsFilter(exclude=True)]`.
 99            on_change: When `True` (default), a frame is only delivered when at least one of its signals
100                       has changed. The delivered frame always contains all signals, including unchanged
101                       ones. When `False`, every frame is delivered regardless of whether its signals
102                       have changed.
103
104        Note:
105            Start the instance using a context manager:
106                ```python
107                async with BehavioralModel(...) as bm:
108                    ...
109                    await bm.run_forever()
110                ```
111            Or use the start/stop methods directly:
112                ```python
113                bm = BehavioralModel(...)
114                await bm.start()
115                # ...
116                await bm.stop()
117                ```
118        """
119        self._broker_client = broker_client
120        self._namespaces = {ns.name: ns for ns in namespaces or []}
121        self._input_handlers = input_handlers or []
122        self._on_change = OnChangeMode.MERGED if on_change else OnChangeMode.OFF
123        self._name = name
124        self._control_server_task = None
125        self._namespace_tasks = []
126
127        missing = sorted({ns_name for ns_name, _ in self._input_handlers} - set(self._namespaces))
128        if missing:
129            raise ValueError(
130                f"Input handlers registered for unknown namespace(s) {missing}. "
131                f"Add the corresponding Namespace instance(s) to `namespaces=`."
132            )
133
134        if input_filters and self._input_handlers:
135            for _, h in self._input_handlers:
136                h.extend_filters(input_filters)
137
138        router = Router(
139            fallback_handler=Router(
140                [
141                    (str(PingRequest.type), self._ping_v1),
142                    (str(RebootRequest.type), self._reboot_v1),
143                ]
144            )
145        )
146        router.add_routes(control_handlers or [])
147        self._control_server = ControlServer(name=name, broker_client=broker_client, handler=router)
148
149        _logger.debug(f"BehavioralModel {self._name} using broker at {broker_client.url}")

Initialize the BehavioralModel instance.

Prometheus metrics are opt-in: set the METRICS_PORT environment variable to enable a process-wide exporter that serves /metrics on that port.

Arguments:
  • name: Identifier for the ECU stub instance, then name which receives control messages.
  • broker_client: The client used for communication with the broker.
  • namespaces: list of Namespace instances (CanNamespace, SomeIPNamespace, etc.).
  • input_handlers: Optional list of (namespace, handler) pairs to receive callbacks on inputs. Create these using the namespace's create_input_handler method.
  • control_handlers: Optional list of (command, handler) pairs for routing control messages.
  • input_filters: Optional filters applied to every input handler across all namespaces. Useful for cross-cutting concerns like excluding E2E signals: input_filters=[E2eSignalsFilter(exclude=True)].
  • on_change: When True (default), a frame is only delivered when at least one of its signals has changed. The delivered frame always contains all signals, including unchanged ones. When False, every frame is delivered regardless of whether its signals have changed.
Note:

Start the instance using a context manager:

async with BehavioralModel(...) as bm:
    ...
    await bm.run_forever()

Or use the start/stop methods directly:

bm = BehavioralModel(...)
await bm.start()
# ...
await bm.stop()

def is_running(self) -> bool:
151    def is_running(self) -> bool:
152        """Has the BehavioralModel been started?"""
153        return self._control_server_task is not None

Has the BehavioralModel been started?

async def start(self) -> None:
155    async def start(self) -> None:
156        """
157        Start the behavioral model, open all namespaces, and initialize input handlers.
158        This is an idempotent operation - calling it multiple times has no additional effect.
159        """
160        if self.is_running():
161            return
162
163        try:
164            ready_event = asyncio.get_running_loop().create_future()
165            self._control_server_task = asyncio.create_task(self._control_server.serve_forever(ready_event))
166            await ready_event
167
168            for ns in self._namespaces.values():
169                await ns.open()
170
171            for namespace_name, handler in self._input_handlers:
172                frame_infos = await self._broker_client.list_frame_infos(namespace_name)
173                for fi in frame_infos:
174                    handler.add(fi)
175                subs = handler.subscriptions()
176                if not subs:
177                    raise ValueError(f"Input handler {handler} did not yield any subscriptions on namespace '{namespace_name}'")
178                ns = self._namespaces[namespace_name]
179
180                async def _wrapped(frame: Frame, h: InputHandler = handler) -> None:
181                    result = await h.handle(frame)
182                    if result is not None:
183                        await self._broker_client.publish(result)
184
185                await ns._subscribe(
186                    subs,
187                    _wrapped,
188                    on_change=self._on_change,
189                    decode_named_values=False,
190                    callback_label=handler.callback_label,
191                )
192
193            self._namespace_tasks = [asyncio.create_task(ns.run_forever()) for ns in self._namespaces.values()]
194
195            await self._broker_client.restbus.start(*(ns.name for ns in self._namespaces.values() if isinstance(ns, GenericNamespace)))
196
197            _logger.debug(f"BehavioralModel '{self._name}' opened using: {__version__}")
198        except Exception as e:
199            await self._teardown()
200            raise BehavioralModelStartError(name=self._name) from e

Start the behavioral model, open all namespaces, and initialize input handlers. This is an idempotent operation - calling it multiple times has no additional effect.

async def stop(self) -> None:
202    async def stop(self) -> None:
203        """
204        Stop the behavioral model, close all namespaces, and clean up resources.
205        This is an idempotent operation - calling it multiple times has no additional effect.
206        """
207        if not self.is_running():
208            return
209        await self._teardown()

Stop the behavioral model, close all namespaces, and clean up resources. This is an idempotent operation - calling it multiple times has no additional effect.

async def run_forever(self) -> None:
242    async def run_forever(self) -> None:
243        """Run the BehavioralModel indefinitely, processing inputs and control requests."""
244        if self._control_server_task is None:
245            raise RuntimeError("BehavioralModel must be started before calling run_forever")
246
247        _logger.debug(f"BehavioralModel '{self._name}' running")
248        await asyncio.gather(*self._namespace_tasks, self._control_server_task)

Run the BehavioralModel indefinitely, processing inputs and control requests.

async def reset_restbuses(self) -> None:
250    async def reset_restbuses(self) -> None:
251        """Reset the restbus frames this model added, in all namespaces, to their default values."""
252        for ns in self._namespaces.values():
253            if isinstance(ns, GenericNamespace):
254                await ns.restbus.reset()

Reset the restbus frames this model added, in all namespaces, to their default values.

@dataclass
class PingRequest(remotivelabs.topology.control.request.ControlRequest):
28@dataclass
29class PingRequest(ControlRequest):
30    """
31    Control request to check if the `BehavioralModel` is alive and responsive.
32
33    Use `remotivelabs.topology.control.ControlClient` to send control requests.
34    """
35
36    type: str = "ping_v1"

Control request to check if the BehavioralModel is alive and responsive.

Use remotivelabs.topology.control.ControlClient to send control requests.

PingRequest(type: str = 'ping_v1', argument: typing.Any | None = None)
type: str = 'ping_v1'
@dataclass
class RebootRequest(remotivelabs.topology.control.request.ControlRequest):
39@dataclass
40class RebootRequest(ControlRequest):
41    """
42    Control request to reset all namespace restbus to default values.
43
44    Use `remotivelabs.topology.control.ControlClient` to send control requests.
45    """
46
47    type: str = "reboot_v1"

Control request to reset all namespace restbus to default values.

Use remotivelabs.topology.control.ControlClient to send control requests.

RebootRequest(type: str = 'reboot_v1', argument: typing.Any | None = None)
type: str = 'reboot_v1'