remotivelabs.broker.restbus

The RemotiveBroker exposes a Restbus interface for simulating CAN bus traffic.

import asyncio

from remotivelabs.broker import BrokerClient
from remotivelabs.broker.restbus import RestbusFrameConfig, RestbusSignalConfig


async def main() -> None:
    async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
        # Start the restbus on the "DriverCan" namespace with one frame configuration
        await broker_client.restbus.add(
            ("DriverCan", [RestbusFrameConfig(name="EngineData")]),
            start=True,
        )

        # now update some of its signals
        signal_configs: list[RestbusSignalConfig] = [
            RestbusSignalConfig.set(name="EngineData.EngineRpm", value=1500),
            RestbusSignalConfig.set(name="EngineData.EngineTemp", value=90),
        ]
        await broker_client.restbus.update_signals(
            ("DriverCan", signal_configs),
        )


if __name__ == "__main__":
    asyncio.run(main())
 1"""
 2The RemotiveBroker exposes a Restbus interface for simulating CAN bus traffic.
 3
 4```python
 5.. include:: ../_docs/snippets/restbus.py
 6```
 7"""
 8
 9from remotivelabs.broker.restbus.restbus import Restbus
10from remotivelabs.broker.restbus.signal_config import RestbusFrameConfig, RestbusSignalConfig
11
12__all__ = ["Restbus", "RestbusSignalConfig", "RestbusFrameConfig"]
class Restbus:
 21class Restbus:
 22    """
 23    Restbus client for managing Restbus operations on the RemoteLabs Broker.
 24    """
 25
 26    _restbus_stub: restbus_api_pb2_grpc.RestbusServiceStub
 27    _update_call: grpc.aio.StreamStreamCall[restbus_api_pb2.UpdateRequest, common_pb2.StreamError] | None
 28
 29    def __init__(
 30        self,
 31        channel: grpc.aio.Channel,
 32        update_call: grpc.aio.StreamStreamCall[restbus_api_pb2.UpdateRequest, common_pb2.StreamError] | None,
 33        client_name: str,
 34    ):
 35        self._restbus_stub = restbus_api_pb2_grpc.RestbusServiceStub(channel)
 36        self._client_name = client_name
 37        self._update_call: grpc.aio.StreamStreamCall[restbus_api_pb2.UpdateRequest, common_pb2.StreamError] | None = update_call
 38        self._update_lock = asyncio.Lock()
 39
 40    async def close(self, *namespace: NamespaceName) -> None:
 41        """
 42        Removes all configured signals and stops the Restbus on the specified namespace.
 43
 44        Args:
 45            *namespace:
 46                One or more namespaces to close
 47        """
 48
 49        await self._restbus_stub.Remove(restbus_api_pb2.RemoveRequest(namespaces=conv.namespace_to_grpc_namespaces(*namespace)))
 50
 51    async def add(self, *frames: tuple[NamespaceName, list[RestbusFrameConfig]], start: bool = False):
 52        """
 53        Adds one or more frames to the Restbus with optional start flag.
 54
 55        Args:
 56            *frames:
 57                One or more tuples, each containing namespace and list of frame configurations which should be added to the restbus
 58            start: If True, starts the frames after adding. Defaults to False.
 59
 60        Note: The start flag affects all frames running on the namespace, even if they are added since before.
 61        """
 62
 63        items = [
 64            restbus_api_pb2.FrameConfig(
 65                frameId=common_pb2.SignalId(name=frame.name, namespace=common_pb2.NameSpace(name=namespace)),
 66                cycleTime=frame.cycle_time,
 67            )
 68            for namespace, frame_configs in frames
 69            for frame in frame_configs
 70        ]
 71        await self._restbus_stub.Add(
 72            restbus_api_pb2.AddRequest(
 73                clientId=common_pb2.ClientId(id=self._client_name),
 74                frames=restbus_api_pb2.FrameConfigs(items=items),
 75                startOption=restbus_api_pb2.StartOption.START_AFTER_ADD if start else restbus_api_pb2.StartOption.NOP,
 76            )
 77        )
 78
 79    async def start(self, *namespace: NamespaceName):
 80        """
 81        Starts Restbus signal publishing for the specified namespaces.
 82
 83        Args:
 84            *namespace:
 85                One or more namespaces to start
 86        """
 87        await self._restbus_stub.Start(restbus_api_pb2.RestbusRequest(namespaces=conv.namespace_to_grpc_namespaces(*namespace)))
 88
 89    async def stop(self, *namespace: NamespaceName):
 90        """
 91        Stops Restbus signal publishing for the specified namespaces.
 92
 93        Args:
 94            *namespace:
 95                One or more namespaces to stop. A stopped restbus can be started again.
 96        """
 97        await self._restbus_stub.Stop(restbus_api_pb2.RestbusRequest(namespaces=conv.namespace_to_grpc_namespaces(*namespace)))
 98
 99    async def remove(self, *frames: tuple[NamespaceName, list[FrameName]]):
100        """
101        Removes specific frames from the Restbus.
102
103        Args:
104            *frames:
105                One or more tuples, each containing namespace and list of frame names to remove from the restbus
106        """
107
108        await self._restbus_stub.Remove(restbus_api_pb2.RemoveRequest(frameIds=conv.tuple_to_signal_ids(list(frames))))
109
110    async def update_signals(self, *signals: tuple[NamespaceName, list[RestbusSignalConfig]]) -> None:
111        """
112        Updates the configured signals on the Restbus with new values.
113
114        Args:
115            *signals:
116                One or more tuples, each containing namespace and list of signal configurations to apply to the restbus
117        """
118        await self._do_update(restbus_api_pb2.UpdateRequest(signals=conv.signal_configs_to_grpc(list(signals))))
119
120    async def _do_update(self, update_request: restbus_api_pb2.UpdateRequest) -> None:
121        if self._update_call:
122            async with self._update_lock:
123                try:
124                    await self._update_call.write(update_request)
125                    return
126                except (grpc.aio.AioRpcError, asyncio.InvalidStateError):
127                    if self._update_call.done():
128                        self._update_call = None
129                    else:
130                        raise
131
132        await self._restbus_stub.Update(update_request)
133
134    async def reset_signals(self, *signals: tuple[NamespaceName, list[SignalName]]) -> None:
135        """
136        Resets specified signals to their default configured values.
137
138        Args:
139            *signals:
140                One or more tuples, each containing namespace and list of signal names to reset
141        """
142
143        await self._restbus_stub.Reset(restbus_api_pb2.ResetRequest(signalIds=conv.tuple_to_signal_ids(list(signals))))
144
145    async def reset_namespaces(self, *namespace: NamespaceName) -> None:
146        """
147        Resets all configured namespaces and their associated signals to default values.
148        Args:
149            *namespace:
150                One or more namespaces to reset
151        """
152        await self._restbus_stub.Reset(restbus_api_pb2.ResetRequest(namespaces=conv.namespace_to_grpc_namespaces(*namespace)))

Restbus client for managing Restbus operations on the RemoteLabs Broker.

Restbus( channel: grpc.aio._base_channel.Channel, update_call: Optional[grpc.aio._base_call.StreamStreamCall[restbus_api_pb2.UpdateRequest, common_pb2.StreamError]], client_name: str)
29    def __init__(
30        self,
31        channel: grpc.aio.Channel,
32        update_call: grpc.aio.StreamStreamCall[restbus_api_pb2.UpdateRequest, common_pb2.StreamError] | None,
33        client_name: str,
34    ):
35        self._restbus_stub = restbus_api_pb2_grpc.RestbusServiceStub(channel)
36        self._client_name = client_name
37        self._update_call: grpc.aio.StreamStreamCall[restbus_api_pb2.UpdateRequest, common_pb2.StreamError] | None = update_call
38        self._update_lock = asyncio.Lock()
async def close(self, *namespace: str) -> None:
40    async def close(self, *namespace: NamespaceName) -> None:
41        """
42        Removes all configured signals and stops the Restbus on the specified namespace.
43
44        Args:
45            *namespace:
46                One or more namespaces to close
47        """
48
49        await self._restbus_stub.Remove(restbus_api_pb2.RemoveRequest(namespaces=conv.namespace_to_grpc_namespaces(*namespace)))

Removes all configured signals and stops the Restbus on the specified namespace.

Arguments:
  • *namespace: One or more namespaces to close
async def add( self, *frames: tuple[str, list[RestbusFrameConfig]], start: bool = False):
51    async def add(self, *frames: tuple[NamespaceName, list[RestbusFrameConfig]], start: bool = False):
52        """
53        Adds one or more frames to the Restbus with optional start flag.
54
55        Args:
56            *frames:
57                One or more tuples, each containing namespace and list of frame configurations which should be added to the restbus
58            start: If True, starts the frames after adding. Defaults to False.
59
60        Note: The start flag affects all frames running on the namespace, even if they are added since before.
61        """
62
63        items = [
64            restbus_api_pb2.FrameConfig(
65                frameId=common_pb2.SignalId(name=frame.name, namespace=common_pb2.NameSpace(name=namespace)),
66                cycleTime=frame.cycle_time,
67            )
68            for namespace, frame_configs in frames
69            for frame in frame_configs
70        ]
71        await self._restbus_stub.Add(
72            restbus_api_pb2.AddRequest(
73                clientId=common_pb2.ClientId(id=self._client_name),
74                frames=restbus_api_pb2.FrameConfigs(items=items),
75                startOption=restbus_api_pb2.StartOption.START_AFTER_ADD if start else restbus_api_pb2.StartOption.NOP,
76            )
77        )

Adds one or more frames to the Restbus with optional start flag.

Arguments:
  • *frames: One or more tuples, each containing namespace and list of frame configurations which should be added to the restbus
  • start: If True, starts the frames after adding. Defaults to False.

Note: The start flag affects all frames running on the namespace, even if they are added since before.

async def start(self, *namespace: str):
79    async def start(self, *namespace: NamespaceName):
80        """
81        Starts Restbus signal publishing for the specified namespaces.
82
83        Args:
84            *namespace:
85                One or more namespaces to start
86        """
87        await self._restbus_stub.Start(restbus_api_pb2.RestbusRequest(namespaces=conv.namespace_to_grpc_namespaces(*namespace)))

Starts Restbus signal publishing for the specified namespaces.

Arguments:
  • *namespace: One or more namespaces to start
async def stop(self, *namespace: str):
89    async def stop(self, *namespace: NamespaceName):
90        """
91        Stops Restbus signal publishing for the specified namespaces.
92
93        Args:
94            *namespace:
95                One or more namespaces to stop. A stopped restbus can be started again.
96        """
97        await self._restbus_stub.Stop(restbus_api_pb2.RestbusRequest(namespaces=conv.namespace_to_grpc_namespaces(*namespace)))

Stops Restbus signal publishing for the specified namespaces.

Arguments:
  • *namespace: One or more namespaces to stop. A stopped restbus can be started again.
async def remove(self, *frames: tuple[str, list[str]]):
 99    async def remove(self, *frames: tuple[NamespaceName, list[FrameName]]):
100        """
101        Removes specific frames from the Restbus.
102
103        Args:
104            *frames:
105                One or more tuples, each containing namespace and list of frame names to remove from the restbus
106        """
107
108        await self._restbus_stub.Remove(restbus_api_pb2.RemoveRequest(frameIds=conv.tuple_to_signal_ids(list(frames))))

Removes specific frames from the Restbus.

Arguments:
  • *frames: One or more tuples, each containing namespace and list of frame names to remove from the restbus
async def update_signals( self, *signals: tuple[str, list[RestbusSignalConfig]]) -> None:
110    async def update_signals(self, *signals: tuple[NamespaceName, list[RestbusSignalConfig]]) -> None:
111        """
112        Updates the configured signals on the Restbus with new values.
113
114        Args:
115            *signals:
116                One or more tuples, each containing namespace and list of signal configurations to apply to the restbus
117        """
118        await self._do_update(restbus_api_pb2.UpdateRequest(signals=conv.signal_configs_to_grpc(list(signals))))

Updates the configured signals on the Restbus with new values.

Arguments:
  • *signals: One or more tuples, each containing namespace and list of signal configurations to apply to the restbus
async def reset_signals(self, *signals: tuple[str, list[str]]) -> None:
134    async def reset_signals(self, *signals: tuple[NamespaceName, list[SignalName]]) -> None:
135        """
136        Resets specified signals to their default configured values.
137
138        Args:
139            *signals:
140                One or more tuples, each containing namespace and list of signal names to reset
141        """
142
143        await self._restbus_stub.Reset(restbus_api_pb2.ResetRequest(signalIds=conv.tuple_to_signal_ids(list(signals))))

Resets specified signals to their default configured values.

Arguments:
  • *signals: One or more tuples, each containing namespace and list of signal names to reset
async def reset_namespaces(self, *namespace: str) -> None:
145    async def reset_namespaces(self, *namespace: NamespaceName) -> None:
146        """
147        Resets all configured namespaces and their associated signals to default values.
148        Args:
149            *namespace:
150                One or more namespaces to reset
151        """
152        await self._restbus_stub.Reset(restbus_api_pb2.ResetRequest(namespaces=conv.namespace_to_grpc_namespaces(*namespace)))

Resets all configured namespaces and their associated signals to default values.

Arguments:
  • *namespace: One or more namespaces to reset
@dataclass
class RestbusSignalConfig:
25@dataclass
26class RestbusSignalConfig:
27    """
28    Defines how a specific signal should behave when emitted by the Restbus.
29
30    Signal values are driven by a two-phase sequence:
31
32    1. **initial** - values emitted once, in order, before the loop starts. May be empty.
33    2. **loop** - values emitted in order, then repeated from the beginning indefinitely.
34
35    On each Restbus tick the next value in the sequence is used. Once ``initial`` is
36    exhausted the Restbus cycles through ``loop`` forever. A single-element ``loop``
37    (e.g., ``loop=[0]``) produces a constant value after the initial sequence.
38
39    Example - update-bit pattern (sends 1 once, then constant 0):
40
41    ```python
42    RestbusSignalConfig(name="UpdateBit", initial=[1], loop=[0])
43    # equivalent to:
44    RestbusSignalConfig.set_update_bit("UpdateBit")
45    ```
46
47    Attributes:
48        name: The signal name as it appears in the signal database.
49        loop: Values emitted repeatedly after ``initial`` is exhausted. Must not be empty.
50        initial: Values emitted once before ``loop`` starts. Defaults to no initial values.
51    """
52
53    name: SignalName
54    loop: Sequence[SignalValue]
55    initial: Sequence[SignalValue] = field(default_factory=list)
56
57    @classmethod
58    def set(cls, name: SignalName, value: SignalValue) -> RestbusSignalConfig:
59        """
60        Create a SignalConfig with a constant value.
61
62        Args:
63            name: Name of the signal
64            value: Value to set in Restbus
65        """
66        return cls(name=name, loop=[value])
67
68    @classmethod
69    def set_update_bit(cls, name: SignalName) -> RestbusSignalConfig:
70        """
71        Create a SignalConfig for an update-bit pattern (sends 1 once, then constant 0).
72
73        Args:
74            name: Name of the signal
75        """
76        return cls(name=name, loop=[0], initial=[1])

Defines how a specific signal should behave when emitted by the Restbus.

Signal values are driven by a two-phase sequence:

  1. initial - values emitted once, in order, before the loop starts. May be empty.
  2. loop - values emitted in order, then repeated from the beginning indefinitely.

On each Restbus tick the next value in the sequence is used. Once initial is exhausted the Restbus cycles through loop forever. A single-element loop (e.g., loop=[0]) produces a constant value after the initial sequence.

Example - update-bit pattern (sends 1 once, then constant 0):

RestbusSignalConfig(name="UpdateBit", initial=[1], loop=[0])
# equivalent to:
RestbusSignalConfig.set_update_bit("UpdateBit")
Attributes:
  • name: The signal name as it appears in the signal database.
  • loop: Values emitted repeatedly after initial is exhausted. Must not be empty.
  • initial: Values emitted once before loop starts. Defaults to no initial values.
RestbusSignalConfig( name: str, loop: Sequence[Union[int, float, bytes, str, NoneType]], initial: Sequence[Union[int, float, bytes, str, NoneType]] = <factory>)
name: str
loop: Sequence[Union[int, float, bytes, str, NoneType]]
initial: Sequence[Union[int, float, bytes, str, NoneType]]
@classmethod
def set( cls, name: str, value: Union[int, float, bytes, str, NoneType]) -> RestbusSignalConfig:
57    @classmethod
58    def set(cls, name: SignalName, value: SignalValue) -> RestbusSignalConfig:
59        """
60        Create a SignalConfig with a constant value.
61
62        Args:
63            name: Name of the signal
64            value: Value to set in Restbus
65        """
66        return cls(name=name, loop=[value])

Create a SignalConfig with a constant value.

Arguments:
  • name: Name of the signal
  • value: Value to set in Restbus
@classmethod
def set_update_bit( cls, name: str) -> RestbusSignalConfig:
68    @classmethod
69    def set_update_bit(cls, name: SignalName) -> RestbusSignalConfig:
70        """
71        Create a SignalConfig for an update-bit pattern (sends 1 once, then constant 0).
72
73        Args:
74            name: Name of the signal
75        """
76        return cls(name=name, loop=[0], initial=[1])

Create a SignalConfig for an update-bit pattern (sends 1 once, then constant 0).

Arguments:
  • name: Name of the signal
@dataclass
class RestbusFrameConfig:
11@dataclass
12class RestbusFrameConfig:
13    """
14    Configuration for a frame in the Restbus.
15
16    Attributes:
17        name: The name of the frame to configure.
18        cycle_time: Optional cycle time override for the frame in ms. If None, the default from the broker's database is used.
19    """
20
21    name: FrameName
22    cycle_time: float | None = None

Configuration for a frame in the Restbus.

Attributes:
  • name: The name of the frame to configure.
  • cycle_time: Optional cycle time override for the frame in ms. If None, the default from the broker's database is used.
RestbusFrameConfig(name: str, cycle_time: float | None = None)
name: str
cycle_time: float | None = None