remotivelabs.topology.namespaces.can

CAN namespace package.

Enables publishing and subscribing to frames and signals using the CAN protocol.

This example creates and configures a CAN namespace, but does not start the restbus. It is not really useful as is; in a real application you would likely either use it together with a BehavioralModel or start the restbus to send periodic messages.

import asyncio

from remotivelabs.broker import BrokerClient

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,
        CanNamespace(
            "HazardLightControlUnit-DriverCan0",
            broker_client,
            restbus_configs=[RestbusConfig([filters.SenderFilter(ecu_name="HazardLightControlUnit")])],
        ),
    ):
        # wait until cancelled
        await asyncio.Future()


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

It is common to use namespaces together with a behavioral model, as shown in the example below.

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:
            # The behavioral model is now running, with an active namespace restbus, until cancelled
            await bm.run_forever()


if __name__ == "__main__":
    asyncio.run(main())
 1"""
 2# CAN namespace package.
 3
 4<!-- start-include -->
 5Enables publishing and subscribing to frames and signals using the CAN protocol.
 6
 7This example creates and configures a CAN namespace, but does not start the restbus.
 8It is not really useful as is; in a real application you would likely either use it together with a `BehavioralModel`
 9or start the restbus to send periodic messages.
10
11```python
12.. include:: ../_docs/snippets/can_namespace.py
13```
14
15It is common to use namespaces together with a behavioral model, as shown in the example below.
16
17```python
18.. include:: ../_docs/snippets/can_namespace_bm.py
19```
20<!-- end-include -->
21"""
22
23from __future__ import annotations
24
25from remotivelabs.broker import NamespaceInfo
26
27from remotivelabs.topology.namespaces.generic import GenericNamespace, InputHandlerSpec, Restbus, RestbusConfig
28
29__all__ = ["CanNamespace", "InputHandlerSpec", "Restbus", "RestbusConfig"]
30
31
32class CanNamespace(GenericNamespace):
33    """
34    Used to represent a CAN (Controller Area Network) namespace in a simulation or
35    testing environment.
36
37    It inherits all behavior from `GenericNamespace` without modification, but serves
38    as a semantic identifier for CAN-specific configurations or extensions.
39    """
40
41    async def _on_open(self, info: NamespaceInfo) -> None:
42        if info.type not in ("can", "canfd", "udp"):
43            raise ValueError(f"Namespace '{self.name}' is not of type 'can', 'canfd' or 'udp'")
44        await super()._on_open(info)
33class CanNamespace(GenericNamespace):
34    """
35    Used to represent a CAN (Controller Area Network) namespace in a simulation or
36    testing environment.
37
38    It inherits all behavior from `GenericNamespace` without modification, but serves
39    as a semantic identifier for CAN-specific configurations or extensions.
40    """
41
42    async def _on_open(self, info: NamespaceInfo) -> None:
43        if info.type not in ("can", "canfd", "udp"):
44            raise ValueError(f"Namespace '{self.name}' is not of type 'can', 'canfd' or 'udp'")
45        await super()._on_open(info)

Used to represent a CAN (Controller Area Network) namespace in a simulation or testing environment.

It inherits all behavior from GenericNamespace without modification, but serves as a semantic identifier for CAN-specific configurations or extensions.

InputHandlerSpec = tuple[typing.Sequence[typing.Union[remotivelabs.broker.filters.FrameFilterPredicate, remotivelabs.broker.filters.SignalFilterPredicate, remotivelabs.broker.filters.FrameSignalFilter]], typing.Callable[[remotivelabs.broker.frame.Frame], typing.Awaitable[NoneType]]]
class Restbus:
234class Restbus:
235    """
236    Restbus provides a way to publish frames according to their cycle time.
237    Sending recurring frames is common with for example CAN or LIN. Notice that each Namespace has its own Restbus.
238    It allows configuring frame publishing behavior, applying filters, and controlling the restbus lifecycle.
239
240    Also notice that new frames can be added or removed in order to emulate how different
241    frames are sent depending on the state of the model.
242
243    The broker runs one restbus per namespace, shared by every client using that namespace. Each `Restbus`
244    keeps track of the frames it added and only removes those on `close` and resets those on `reset`. Frames
245    are keyed by name, so if two clients add the same frame, removing or resetting it affects both.
246
247    Usage:
248        Should be used with through a `Namespace` implementation such as `GenericNamespace`, but can be used standalone.
249
250        ```python
251        async with Restbus(namespace, broker_client, restbus_configs) as restbus:
252            await restbus.start()
253        ```
254    Args:
255        namespace: The namespace to operate in.
256        broker_client: The broker client to communicate with.
257        restbus_configs: Optional list of configurations with filters for the restbus.
258            Applied in order; if multiple filters match the same frame, the last matching configuration takes precedence.
259    """
260
261    def __init__(self, namespace: NamespaceName, broker_client: BrokerClient, restbus_configs: list[RestbusConfig] | None = None):
262        self._namespace = namespace
263        self._broker_client = broker_client
264        self._restbus_configs = restbus_configs or []
265        self._is_open = False
266        self._frames: set[FrameName] = set()
267
268    async def open(self) -> Self:
269        """
270        Open the restbus and initialize it with configured frames.
271        This is an idempotent operation - calling it multiple times has no additional effect.
272        """
273        if self._is_open:
274            return self
275
276        frame_infos = await self._broker_client.list_frame_infos(self._namespace)
277        frames: dict[FrameName, RestbusFrameConfig] = {}
278        for config in self._restbus_configs:
279            matched_filters: set[FilterLike] = set()
280            for frame_info in frame_infos:
281                for filter in config.restbus_filters:
282                    if is_frame_filter(filter) and filter(frame_info):
283                        matched_filters.add(filter)
284                        cycle_time = (config.cycle_time_millis or frame_info.cycle_time_millis) * config.delay_multiplier
285                        if cycle_time:
286                            frame_config = RestbusFrameConfig(name=frame_info.name, cycle_time=cycle_time)
287                            frames[frame_info.name] = frame_config
288            for filter in config.restbus_filters:
289                if filter not in matched_filters:
290                    raise ValueError(f"Filter {filter} did not match any frames")
291
292        if frames:
293            await self.add(*frames.values())
294
295        self._is_open = True
296        return self
297
298    async def close(self) -> None:
299        """
300        Close the restbus by removing the frames this instance added, whether from `restbus_configs` or `add`.
301        Frames added by other clients on the same namespace keep running, and the namespace's running state
302        is left as it is.
303        This is an idempotent operation - calling it multiple times has no additional effect.
304        """
305        if self._frames:
306            await self._broker_client.restbus.remove((self._namespace, sorted(self._frames)))
307            self._frames.clear()
308        self._is_open = False
309
310    async def __aenter__(self) -> Self:
311        return await self.open()
312
313    async def __aexit__(self, exc_type, exc_value, traceback) -> None:
314        await self.close()
315
316    async def add(self, *frame_configs: RestbusFrameConfig, start: bool = False):
317        """
318        Add frames by configuration to the restbus.
319
320        Args:
321            *frame_configs: One or more frame configurations
322            start: Whether to start the restbus publishing immediately.
323                Note: this flag controls a global state for the entire restbus, not individual frames.
324        """
325        await self._broker_client.restbus.add((self._namespace, list(frame_configs)), start=start)
326        self._frames.update(fc.name for fc in frame_configs)
327
328    async def start(self):
329        """Start restbus publishing for this namespace."""
330        await self._broker_client.restbus.start(self._namespace)
331
332    async def stop(self):
333        """
334        Stop restbus publishing for this namespace.
335        Note: this stops the entire namespace, including frames added by other clients.
336        """
337        await self._broker_client.restbus.stop(self._namespace)
338
339    async def remove(self, *frames: FrameName):
340        """
341        Remove frames from the restbus.
342
343        Args:
344            *frames: One or more frame names to remove
345        """
346        await self._broker_client.restbus.remove((self._namespace, list(frames)))
347        self._frames.difference_update(frames)
348
349    async def update_signals(self, *signal_configs: RestbusSignalConfig | tuple[SignalName, SignalValue]) -> None:
350        """
351        Update signal configurations for the restbus.
352
353        Args:
354            *signal_configs: Signal configurations to update, or a tuple of signal name and value.
355        """
356        remapped_configs = [RestbusSignalConfig.set(sc[0], sc[1]) if isinstance(sc, tuple) else sc for sc in signal_configs]
357        await self._broker_client.restbus.update_signals((self._namespace, list(remapped_configs)))
358
359    async def reset_signals(self, *signals: SignalName) -> None:
360        """
361        Reset specified signals in the restbus to their original values.
362
363        Args:
364            *signals: Signal names to reset.
365        """
366        await self._broker_client.restbus.reset_signals((self._namespace, list(signals)))
367
368    async def reset(self) -> None:
369        """
370        Reset all signals of the frames this instance added to their default values.
371        Frames added by other clients on the same namespace are left as they are.
372        """
373        if not self._frames:
374            return
375        frame_infos = await self._broker_client.list_frame_infos(self._namespace)
376        signals = [signal for fi in frame_infos if fi.name in self._frames for signal in fi.signals]
377        if signals:
378            await self.reset_signals(*signals)
379
380    @asynccontextmanager
381    async def transaction(self) -> AsyncGenerator[TransactionContext, None]:
382        """
383        Context manager for batching signal updates and resets.
384
385        Usage:
386            ```python
387            async with restbus.transaction() as tx:
388                tx.updates.append(...)
389                tx.resets.append(...)
390            ```
391        """
392        tc = TransactionContext()
393        yield tc
394        if len(tc.resets) > 0:
395            await self.reset_signals(*tc.resets)
396        if len(tc.updates) > 0:
397            await self.update_signals(*tc.updates)

Restbus provides a way to publish frames according to their cycle time. Sending recurring frames is common with for example CAN or LIN. Notice that each Namespace has its own Restbus. It allows configuring frame publishing behavior, applying filters, and controlling the restbus lifecycle.

Also notice that new frames can be added or removed in order to emulate how different frames are sent depending on the state of the model.

The broker runs one restbus per namespace, shared by every client using that namespace. Each Restbus keeps track of the frames it added and only removes those on close and resets those on reset. Frames are keyed by name, so if two clients add the same frame, removing or resetting it affects both.

Usage:

Should be used with through a Namespace implementation such as GenericNamespace, but can be used standalone.

async with Restbus(namespace, broker_client, restbus_configs) as restbus:
    await restbus.start()
Arguments:
  • namespace: The namespace to operate in.
  • broker_client: The broker client to communicate with.
  • restbus_configs: Optional list of configurations with filters for the restbus. Applied in order; if multiple filters match the same frame, the last matching configuration takes precedence.
Restbus( namespace: str, broker_client: remotivelabs.broker.client.BrokerClient, restbus_configs: list[RestbusConfig] | None = None)
261    def __init__(self, namespace: NamespaceName, broker_client: BrokerClient, restbus_configs: list[RestbusConfig] | None = None):
262        self._namespace = namespace
263        self._broker_client = broker_client
264        self._restbus_configs = restbus_configs or []
265        self._is_open = False
266        self._frames: set[FrameName] = set()
async def open(self) -> Self:
268    async def open(self) -> Self:
269        """
270        Open the restbus and initialize it with configured frames.
271        This is an idempotent operation - calling it multiple times has no additional effect.
272        """
273        if self._is_open:
274            return self
275
276        frame_infos = await self._broker_client.list_frame_infos(self._namespace)
277        frames: dict[FrameName, RestbusFrameConfig] = {}
278        for config in self._restbus_configs:
279            matched_filters: set[FilterLike] = set()
280            for frame_info in frame_infos:
281                for filter in config.restbus_filters:
282                    if is_frame_filter(filter) and filter(frame_info):
283                        matched_filters.add(filter)
284                        cycle_time = (config.cycle_time_millis or frame_info.cycle_time_millis) * config.delay_multiplier
285                        if cycle_time:
286                            frame_config = RestbusFrameConfig(name=frame_info.name, cycle_time=cycle_time)
287                            frames[frame_info.name] = frame_config
288            for filter in config.restbus_filters:
289                if filter not in matched_filters:
290                    raise ValueError(f"Filter {filter} did not match any frames")
291
292        if frames:
293            await self.add(*frames.values())
294
295        self._is_open = True
296        return self

Open the restbus and initialize it with configured frames. This is an idempotent operation - calling it multiple times has no additional effect.

async def close(self) -> None:
298    async def close(self) -> None:
299        """
300        Close the restbus by removing the frames this instance added, whether from `restbus_configs` or `add`.
301        Frames added by other clients on the same namespace keep running, and the namespace's running state
302        is left as it is.
303        This is an idempotent operation - calling it multiple times has no additional effect.
304        """
305        if self._frames:
306            await self._broker_client.restbus.remove((self._namespace, sorted(self._frames)))
307            self._frames.clear()
308        self._is_open = False

Close the restbus by removing the frames this instance added, whether from restbus_configs or add. Frames added by other clients on the same namespace keep running, and the namespace's running state is left as it is. This is an idempotent operation - calling it multiple times has no additional effect.

async def add( self, *frame_configs: remotivelabs.broker.restbus.signal_config.RestbusFrameConfig, start: bool = False):
316    async def add(self, *frame_configs: RestbusFrameConfig, start: bool = False):
317        """
318        Add frames by configuration to the restbus.
319
320        Args:
321            *frame_configs: One or more frame configurations
322            start: Whether to start the restbus publishing immediately.
323                Note: this flag controls a global state for the entire restbus, not individual frames.
324        """
325        await self._broker_client.restbus.add((self._namespace, list(frame_configs)), start=start)
326        self._frames.update(fc.name for fc in frame_configs)

Add frames by configuration to the restbus.

Arguments:
  • *frame_configs: One or more frame configurations
  • start: Whether to start the restbus publishing immediately. Note: this flag controls a global state for the entire restbus, not individual frames.
async def start(self):
328    async def start(self):
329        """Start restbus publishing for this namespace."""
330        await self._broker_client.restbus.start(self._namespace)

Start restbus publishing for this namespace.

async def stop(self):
332    async def stop(self):
333        """
334        Stop restbus publishing for this namespace.
335        Note: this stops the entire namespace, including frames added by other clients.
336        """
337        await self._broker_client.restbus.stop(self._namespace)

Stop restbus publishing for this namespace. Note: this stops the entire namespace, including frames added by other clients.

async def remove(self, *frames: str):
339    async def remove(self, *frames: FrameName):
340        """
341        Remove frames from the restbus.
342
343        Args:
344            *frames: One or more frame names to remove
345        """
346        await self._broker_client.restbus.remove((self._namespace, list(frames)))
347        self._frames.difference_update(frames)

Remove frames from the restbus.

Arguments:
  • *frames: One or more frame names to remove
async def update_signals( self, *signal_configs: remotivelabs.broker.restbus.signal_config.RestbusSignalConfig | tuple[str, typing.Union[int, float, bytes, str, NoneType]]) -> None:
349    async def update_signals(self, *signal_configs: RestbusSignalConfig | tuple[SignalName, SignalValue]) -> None:
350        """
351        Update signal configurations for the restbus.
352
353        Args:
354            *signal_configs: Signal configurations to update, or a tuple of signal name and value.
355        """
356        remapped_configs = [RestbusSignalConfig.set(sc[0], sc[1]) if isinstance(sc, tuple) else sc for sc in signal_configs]
357        await self._broker_client.restbus.update_signals((self._namespace, list(remapped_configs)))

Update signal configurations for the restbus.

Arguments:
  • *signal_configs: Signal configurations to update, or a tuple of signal name and value.
async def reset_signals(self, *signals: str) -> None:
359    async def reset_signals(self, *signals: SignalName) -> None:
360        """
361        Reset specified signals in the restbus to their original values.
362
363        Args:
364            *signals: Signal names to reset.
365        """
366        await self._broker_client.restbus.reset_signals((self._namespace, list(signals)))

Reset specified signals in the restbus to their original values.

Arguments:
  • *signals: Signal names to reset.
async def reset(self) -> None:
368    async def reset(self) -> None:
369        """
370        Reset all signals of the frames this instance added to their default values.
371        Frames added by other clients on the same namespace are left as they are.
372        """
373        if not self._frames:
374            return
375        frame_infos = await self._broker_client.list_frame_infos(self._namespace)
376        signals = [signal for fi in frame_infos if fi.name in self._frames for signal in fi.signals]
377        if signals:
378            await self.reset_signals(*signals)

Reset all signals of the frames this instance added to their default values. Frames added by other clients on the same namespace are left as they are.

@asynccontextmanager
async def transaction( self) -> AsyncGenerator[remotivelabs.topology.namespaces.generic.TransactionContext, NoneType]:
380    @asynccontextmanager
381    async def transaction(self) -> AsyncGenerator[TransactionContext, None]:
382        """
383        Context manager for batching signal updates and resets.
384
385        Usage:
386            ```python
387            async with restbus.transaction() as tx:
388                tx.updates.append(...)
389                tx.resets.append(...)
390            ```
391        """
392        tc = TransactionContext()
393        yield tc
394        if len(tc.resets) > 0:
395            await self.reset_signals(*tc.resets)
396        if len(tc.updates) > 0:
397            await self.update_signals(*tc.updates)

Context manager for batching signal updates and resets.

Usage:
async with restbus.transaction() as tx:
    tx.updates.append(...)
    tx.resets.append(...)
@dataclass
class RestbusConfig:
217@dataclass
218class RestbusConfig:
219    """
220    Configuration for the Restbus
221
222    Attributes:
223        restbus_filters: List of filters used to select frames; matching frames will be configured and managed by the restbus.
224        delay_multiplier: Multiplier for applying artificial delays; default is 1 (no delay).
225        cycle_time_millis: Optional fixed cycle time in milliseconds for publishing.
226            By default the cycle time from the signal database is used.
227    """
228
229    restbus_filters: list[FilterLike]
230    delay_multiplier: float = 1
231    cycle_time_millis: float | None = None

Configuration for the Restbus

Attributes:
  • restbus_filters: List of filters used to select frames; matching frames will be configured and managed by the restbus.
  • delay_multiplier: Multiplier for applying artificial delays; default is 1 (no delay).
  • cycle_time_millis: Optional fixed cycle time in milliseconds for publishing. By default the cycle time from the signal database is used.
RestbusConfig( restbus_filters: list[typing.Union[remotivelabs.broker.filters.FrameFilterPredicate, remotivelabs.broker.filters.SignalFilterPredicate, remotivelabs.broker.filters.FrameSignalFilter]], delay_multiplier: float = 1, cycle_time_millis: float | None = None)
restbus_filters: list[typing.Union[remotivelabs.broker.filters.FrameFilterPredicate, remotivelabs.broker.filters.SignalFilterPredicate, remotivelabs.broker.filters.FrameSignalFilter]]
delay_multiplier: float = 1
cycle_time_millis: float | None = None