remotivelabs.broker
RemotiveLabs Broker API
This module handles communication with the RemotiveBroker.
The RemotiveBroker can run locally or in RemotiveCloud. Connecting to a RemotiveCloud instance requires additional
authentication parameters—see the remotivelabs.broker.auth module for details.
Installation
pip install remotivelabs-broker
Project Links
Usage
Connecting to a RemotiveBroker is straightforward using the BrokerClient class:
import asyncio
from remotivelabs.broker import BrokerClient
async def main() -> None:
# Create a BrokerClient instance and list all namespaces available on that broker.
async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
ns = await broker_client.list_namespaces()
print(f"Namespaces: {ns}")
if __name__ == "__main__":
asyncio.run(main())
Listing frames and signals:
import asyncio
from remotivelabs.broker import BrokerClient, FrameInfo
async def main() -> None:
async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
# list all available frames in the "DriverCan" namespace
frame_infos: list[FrameInfo] = await broker_client.list_frame_infos("DriverCan")
# simply print all frames and their signals
for frame_info in frame_infos:
print(f"{frame_info.name}")
for signal_info in frame_info.signals.values():
print(f" {signal_info.name}")
if __name__ == "__main__":
asyncio.run(main())
Subscribing to frames or signals on a specific namespace:
import asyncio
from typing import AsyncIterator
from remotivelabs.broker import BrokerClient, Frame
async def main() -> None:
async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
# subscribe to a frame named "EngineData" (including all its signals) in the "DriverCan" namespace
stream: AsyncIterator[Frame] = await broker_client.subscribe_frames(
("DriverCan", ["EngineData"]),
)
# will receive frames until stream is closed by broker or an error occurs
async for frame in stream:
print(f"Received frame: {frame}")
if __name__ == "__main__":
asyncio.run(main())
Filters
It is possible to filter frames and signals using filter predicates. A filter predicate is any callable that takes a
remotivelabs.broker.frame.FrameInfo or remotivelabs.broker.signal.SignalInfo object and returns a boolean
indicating whether the object matches the filter criteria.
All filters have an exclude flag to indicate whether matches should be excluded (True) or
included (False, default). Filters are callable and can be passed to Python built-in functions that
expect a predicate, such as filter(), any(), or all(). The snippet below shows examples
using filter():
Filter Strategy:
The
filter_recursive()function applies frame and signal filters with context-dependent behavior. Frame filtering determines eligibility, then signal filtering applies differently based on frame inclusion: included frames start with all signals (exclude-only), excluded frames require explicit signal inclusion. Exclusion filters always take priority over inclusion filters.
Examples:
from remotivelabs.broker import FrameInfo, SignalInfo
from remotivelabs.broker.filters import (
AllFramesFilter,
E2eSignalsFilter,
FrameFilter,
ReceiverFilter,
SenderFilter,
SignalFilter,
filter_recursive,
is_frame_filter,
is_frame_signal_filter,
is_signal_filter,
)
# assume frames and signals are populated elsewhere
frames: list[FrameInfo] = []
signals: list[SignalInfo] = []
# Example 1: Include all frames
all_frames_filter = AllFramesFilter()
filtered_frames = list(filter(all_frames_filter, frames))
# Example 2: Include all frames but exclude a specific frame
frame_exclude_filter = FrameFilter(frame_name="Frame1", exclude=True)
filtered_frames = list(filter(frame_exclude_filter, frames))
# Example 3: Filter frames sent by a specific ECU
sender_filter = SenderFilter(ecu_name="ECU1")
filtered_frames = list(filter(sender_filter, frames))
# Example 4: Filter frames received by a specific ECU, excluding one signal
receiver_filter = ReceiverFilter(ecu_name="ECU2")
signal_exclude_filter = SignalFilter(signal_name="SignalA", exclude=True)
filtered_frames = list(filter(receiver_filter, frames))
filtered_signals = list(filter(signal_exclude_filter, signals))
# Example 5: Chaining filters
frame_include = FrameFilter(frame_name="FrameA")
frame_exclude = FrameFilter(frame_name="FrameB", exclude=True)
filtered_frames = list(filter(frame_exclude, filter(frame_include, frames)))
# Example 6: Combining inclusion and exclusion with AllFramesFilter and FrameFilter
all_frames_filter = AllFramesFilter()
frame_exclude_filter = FrameFilter(frame_name="FrameC", exclude=True)
filtered_frames = list(filter(frame_exclude_filter, filter(all_frames_filter, frames)))
# Example 7: Recursive filtering of signals (SignalInfos) in frames (FrameInfos)
filtered_frames = [
filtered_frame
for frame in frames
if (filtered_frame := filter_recursive(frame, filters=[all_frames_filter, signal_exclude_filter])) is not None
]
# Example 8: Drop E2E bookkeeping signals (CRC + counter) while keeping the rest of the frame
e2e_drop = E2eSignalsFilter(exclude=True)
filtered_frames = [
filtered_frame for frame in frames if (filtered_frame := filter_recursive(frame, filters=[all_frames_filter, e2e_drop])) is not None
]
# Example 9: Type checking filters
assert is_frame_filter(all_frames_filter) # works with frames
assert not is_signal_filter(all_frames_filter) # doesn't work with signals
assert not is_frame_filter(signal_exclude_filter) # doesn't work with frames
assert is_signal_filter(signal_exclude_filter) # works with signals
assert is_frame_filter(sender_filter) # works with frames
assert is_signal_filter(sender_filter) # works with signals
assert is_frame_signal_filter(e2e_drop) # evaluates a signal in the context of its frame
assert not is_frame_filter(e2e_drop)
assert not is_signal_filter(e2e_drop)
# Example 10: All frames sent by an ECU, except a few named frames
# SenderFilter includes every frame sent by ECU1, and the FrameFilter exclusions drop FrameB and FrameC
# from that set. Exclusions always win, so the sender filter cannot re-include the excluded frames.
ecu1_frames = SenderFilter(ecu_name="ECU1")
exclude_frame_b = FrameFilter(frame_name="FrameB", exclude=True)
exclude_frame_c = FrameFilter(frame_name="FrameC", exclude=True)
filtered_frames = [
filtered_frame
for frame in frames
if (filtered_frame := filter_recursive(frame, filters=[ecu1_frames, exclude_frame_b, exclude_frame_c])) is not None
]
Filtered frames can be used when subscribing:
import asyncio
from typing import AsyncIterator
from remotivelabs.broker import BrokerClient, Frame, FrameInfo
from remotivelabs.broker.filters import ReceiverFilter
async def main() -> None:
async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
# list frames in the "DriverCan" namespace
frame_infos: list[FrameInfo] = await broker_client.list_frame_infos("DriverCan")
# filter according to some critera
filtered_frame_infos = list(filter(ReceiverFilter(ecu_name="ECU2"), frame_infos))
# subscribe using the filtered frame infos
stream: AsyncIterator[Frame] = await broker_client.subscribe_frames(
("DriverCan", filtered_frame_infos),
)
# will receive frames until stream is closed by broker or an error occurs
async for frame in stream:
print(f"Received frame: {frame}")
if __name__ == "__main__":
asyncio.run(main())
Filters can also be used directly when subscribing:
import asyncio
from typing import AsyncIterator
from remotivelabs.broker import BrokerClient, Frame
from remotivelabs.broker.filters import ReceiverFilter
async def main() -> None:
async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
# subscribe using the ReceiverFilter to only receive frames from ECU named "ECU2" in the "DriverCan" namespace
stream: AsyncIterator[Frame] = await broker_client.subscribe_frames(
("DriverCan", [ReceiverFilter(ecu_name="ECU2")]),
)
# will receive frames until stream is closed by broker or an error occurs
async for frame in stream:
print(f"Received frame: {frame}")
if __name__ == "__main__":
asyncio.run(main())
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())
Recording session
There is a RecordingSessionClient for managing recording session playback on the broker.
import asyncio
from remotivelabs.broker.recording_session import RecordingSessionClient
async def main() -> None:
# Create a recording session client
async with RecordingSessionClient(url="http://127.0.0.1:50051") as rs_client:
# List available recording files on the broker
files = await rs_client.list_recording_files()
print(f"Available recording files: {files}")
# open a recording session with the first file
rs_ref = rs_client.get_session(str(files[0]))
async with rs_ref as session:
# start playback
status = await session.play()
print(f"Playback started with status: {status}")
# exiting the async with block will close the session, but playback will continue if other sessions are open
if __name__ == "__main__":
asyncio.run(main())
SecOC
RemotiveLabsBroker supports multiple SecOC properties. These properties can be set via the RemotiveBroker API to configure SecOC behavior for testing purposes.
import asyncio
from remotivelabs.broker import BrokerClient
from remotivelabs.broker.secoc import SecocFreshnessValue
async def main() -> None:
async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
prop = SecocFreshnessValue(fv=b"\x00\x00\x12\x34")
await broker_client.set_secoc_property(namespace="MyNamespace", property=prop)
if __name__ == "__main__":
asyncio.run(main())
Logging
This library uses Python's standard logging module. By default, the library does not configure any logging handlers,
allowing applications to fully control their logging setup.
To enable logs from this library in your application or tests, configure logging as follows:
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger("remotivelabs.broker").setLevel(logging.DEBUG)
For more advanced configurations, refer to the Python logging documentation.
1''' 2# RemotiveLabs Broker API 3 4This module handles communication with the RemotiveBroker. 5 6The RemotiveBroker can run locally or in RemotiveCloud. Connecting to a RemotiveCloud instance requires additional 7authentication parameters—see the `remotivelabs.broker.auth` module for details. 8 9## Installation 10 11```bash 12pip install remotivelabs-broker 13``` 14 15## Project Links 16 17- [Documentation](https://docs.remotivelabs.com/) 18- [Examples](https://github.com/remotivelabs/remotivelabs-topology-examples) 19- [Issues](mailto:support@remotivelabs.com) 20 21## Usage 22 23Connecting to a RemotiveBroker is straightforward using the `BrokerClient` class: 24 25```python 26.. include:: _docs/snippets/client.py 27``` 28 29Listing frames and signals: 30 31```python 32.. include:: _docs/snippets/client_list_frames.py 33``` 34 35Subscribing to frames or signals on a specific namespace: 36 37```python 38.. include:: _docs/snippets/client_subscribe.py 39``` 40 41### Filters 42 43.. include:: filters.py 44 :start-after: """ 45 :end-line: 23 46 47Filtered frames can be used when subscribing: 48 49```python 50.. include:: _docs/snippets/client_subscribe_filtered_frames.py 51``` 52 53Filters can also be used directly when subscribing: 54 55```python 56.. include:: _docs/snippets/client_subscribe_filters.py 57``` 58 59### Restbus 60 61.. include:: restbus/__init__.py 62 :start-after: """ 63 :end-line: 6 64 65### Recording session 66 67.. include:: recording_session/__init__.py 68 :start-after: """ 69 :end-line: 6 70 71### SecOC 72 73.. include:: secoc.py 74 :start-after: """ 75 :end-line: 7 76 77## Logging 78 79This library uses Python's standard `logging` module. By default, the library does not configure any logging handlers, 80allowing applications to fully control their logging setup. 81 82To enable logs from this library in your application or tests, configure logging as follows: 83 84```python 85import logging 86 87logging.basicConfig(level=logging.INFO) 88logging.getLogger("remotivelabs.broker").setLevel(logging.DEBUG) 89``` 90 91For more advanced configurations, refer to the [Python logging documentation](https://docs.python.org/3/library/logging.html). 92 93''' 94 95import logging 96 97from remotivelabs.broker import auth, exceptions, filters, recording_session, restbus 98from remotivelabs.broker.__about__ import __version__ 99from remotivelabs.broker.client import BrokerClient, OnChangeMode 100from remotivelabs.broker.frame import E2eProfile, Frame, FrameInfo, FrameName, FrameSubscription, Header 101from remotivelabs.broker.namespace import NamespaceInfo, NamespaceName 102from remotivelabs.broker.restbus import RestbusFrameConfig, RestbusSignalConfig 103from remotivelabs.broker.secoc import SecocCmac0, SecocFreshnessValue, SecocKey, SecocProperty, SecocTimeDiff 104from remotivelabs.broker.signal import ( 105 MultiplexInfo, 106 MultiplexInfoFilter, 107 MultiplexInfoSelector, 108 Signal, 109 SignalInfo, 110 SignalName, 111 SignalValue, 112 WriteSignal, 113) 114 115__all__ = [ 116 "__version__", 117 "auth", 118 "exceptions", 119 "recording_session", 120 "restbus", 121 "filters", 122 "BrokerClient", 123 "Frame", 124 "FrameInfo", 125 "FrameName", 126 "FrameSubscription", 127 "Header", 128 "NamespaceInfo", 129 "NamespaceName", 130 "OnChangeMode", 131 "RestbusFrameConfig", 132 "RestbusSignalConfig", 133 "SecocCmac0", 134 "SecocFreshnessValue", 135 "SecocKey", 136 "SecocProperty", 137 "SecocTimeDiff", 138 "MultiplexInfo", 139 "MultiplexInfoFilter", 140 "MultiplexInfoSelector", 141 "Signal", 142 "SignalInfo", 143 "SignalName", 144 "SignalValue", 145 "WriteSignal", 146] 147 148# Hide internal modules from pdoc-generated API docs. pdoc skips 149# underscore-prefixed names by default, but be explicit for clarity. 150__pdoc__ = { 151 "_generated": False, 152 "_docs": False, 153} 154 155 156logging.getLogger("remotivelabs.broker").addHandler(logging.NullHandler())
146class BrokerClient(BrokerClientConnection): 147 """ 148 Client for signal-related operations. 149 """ 150 151 _network_service: network_api_pb2_grpc.NetworkServiceStub 152 _traffic_service: traffic_api_pb2_grpc.TrafficServiceStub 153 _recording_session_service: recordingsession_api_pb2_grpc.RecordingSessionServiceStub 154 _cache: dict[str, common_pb2.Frames] 155 _namespace_cache: dict[str, NamespaceInfo] 156 _publish_call: grpc.aio.StreamStreamCall[network_api_pb2.PublisherConfig, common_pb2.StreamError] | None 157 restbus: Restbus 158 159 def __init__(self, url: str, client_id: str | None = None, auth: AuthMethod = NoAuth()): 160 """ 161 Initializes a new BrokerClient instance. 162 163 Args: 164 url: The RemotiveBroker URL to connect to. 165 client_id: Optional client ID. If None, a random ID is generated. 166 auth: Authentication method to use. Defaults to NoAuth. 167 168 Note: 169 Start the instance using a context manager: 170 ```python 171 async with BrokerClient(...) as client: 172 ... 173 ``` 174 175 Or use the connect/disconnect methods directly: 176 ```python 177 client = await BrokerClient(...).connect() 178 # ... 179 await client.disconnect() 180 ``` 181 """ 182 super().__init__(url=url, client_id=client_id, auth=auth) 183 184 self._traffic_service = traffic_api_pb2_grpc.TrafficServiceStub(self._channel) 185 self._recording_session_service = recordingsession_api_pb2_grpc.RecordingSessionServiceStub(self._channel) 186 self.restbus = Restbus(self._channel, self._restbus_update_call, self._client_id) 187 self._cache: dict[str, common_pb2.Frames] = {} 188 self._namespace_cache: dict[str, NamespaceInfo] = {} 189 190 async def broker_version(self) -> str: 191 """ 192 Returns the broker version 193 """ 194 config = await self._system_service.GetConfiguration(common_pb2.Empty()) 195 return str(config.serverVersion.lstrip("v")) 196 197 async def topology_instance_id(self) -> str | None: 198 """ 199 Returns the topology instance ID used to generate the configuration for this broker, 200 or None if broker is not part of a topology. 201 """ 202 config = await self._system_service.GetConfiguration(common_pb2.Empty()) 203 return config.topologyInstanceId or None 204 205 async def read_signals(self, *values: tuple[NamespaceName, list[str]]) -> list[Signal]: 206 """ 207 Read signals from signal cache 208 209 Args: 210 *values: 211 One or more tuples, each containing a namespace and a list of signal names of the signals to read. 212 213 Raises: 214 ValueError: If the list of values is empty. 215 """ 216 217 if not values: 218 raise ValueError("No signals provided") 219 signals = await self._network_service.ReadSignals(conv.tuple_to_signal_ids(list(values))) 220 return [conv.grpc_to_signal(signal) for signal in signals.signal if not signal.HasField("arbitration")] 221 222 async def publish(self, *values: tuple[NamespaceName, list[WriteSignal]]) -> None: 223 """ 224 Publish a list of signals to the broker. 225 226 Args: 227 *values: 228 One or more tuples, each containing a namespace and a list of signals to publish. 229 230 Raises: 231 ValueError: If the list of values is empty. 232 """ 233 234 if not values: 235 raise ValueError("No signals provided") 236 237 await self._do_publish(conv.write_signal_to_grpc_publisher_config(list(values), self.client_id)) 238 239 async def publish_header(self, *headers: tuple[NamespaceName, list[FrameName]]) -> None: 240 """ 241 Publish a list of headers to the broker. 242 243 Args: 244 *headers: 245 One or more tuples, each containing a namespace and a list of frame names of which headers to publish. 246 247 Raises: 248 ValueError: If the list of values is empty. 249 """ 250 251 if not headers: 252 raise ValueError("No signals provided") 253 254 await self._do_publish(conv.header_to_grpc_publisher_config(list(headers), self.client_id)) 255 256 async def _do_publish(self, publisher_info: network_api_pb2.PublisherConfig) -> None: 257 if self._publish_call: 258 async with self._publish_lock: 259 try: 260 await self._publish_call.write(publisher_info) 261 return 262 except (grpc.aio.AioRpcError, asyncio.InvalidStateError): 263 if self._publish_call.done(): 264 self._publish_call = None 265 else: 266 raise 267 268 await self._network_service.PublishSignals(publisher_info) 269 270 async def subscribe( 271 self, 272 *signals: tuple[NamespaceName, Sequence[SignalName | SignalInfo | SignalFilterPredicate]], 273 on_change: bool = False, 274 initial_empty: bool = False, 275 ) -> AsyncIterator[list[Signal]]: 276 """ 277 Subscribe to individual signals by name, metadata, or filter predicate. 278 279 Each positional argument is a ``(namespace, items)`` tuple. Items can be freely mixed: 280 281 - ``str`` - subscribe to the named signal. 282 - `SignalInfo` - subscribe using a metadata object returned by `list_signal_infos()`. 283 - `remotivelabs.broker.filters.SignalFilterPredicate` - subscribe to all signals matching the predicate; resolved 284 at call time via `list_signal_infos()`. 285 286 For frame-level subscriptions (receiving signals grouped by frame with a timestamp), 287 use `subscribe_frames()` instead. 288 289 Args: 290 *signals: 291 One or more ``(namespace, items)`` tuples describing which signals to subscribe to. 292 on_change: Whether to receive updates only on change. 293 initial_empty: If ``True``, the first broker message (an empty sync marker) is 294 consumed internally before the iterator is returned, ensuring the broker is 295 ready before the first real value arrives. Useful when you need to guarantee 296 the subscription is live before publishing something. 297 298 Returns: 299 An async iterator yielding batches of `Signal` objects. 300 301 Raises: 302 ValueError: If no signals are provided. 303 """ 304 if not signals: 305 raise ValueError("No subscription info provided") 306 307 processed_signals = await self._process_signal_subscriptions([(ns, list(sigs)) for ns, sigs in signals]) 308 309 config = conv.signal_ids_to_grpc_subscriber_config(processed_signals, self.client_id, on_change, initial_empty) 310 stream = self._network_service.SubscribeToSignals(config) 311 312 # if initial_empty is set; drop the first message 313 if initial_empty: 314 await anext(stream.__aiter__()) 315 316 async def async_generator() -> AsyncIterator[list[Signal]]: 317 async for signal_batch in stream: 318 signals = [conv.grpc_to_signal(signal) for signal in signal_batch.signal if not signal.HasField("arbitration")] 319 if signals: 320 yield signals 321 322 return async_generator() 323 324 async def subscribe_header( 325 self, 326 *headers: tuple[NamespaceName, Sequence[FrameName]], 327 initial_empty: bool = False, 328 ) -> AsyncIterator[Header]: 329 """ 330 Subscribe to frame headers. 331 332 Headers carry only the frame identifier - no signal values. This is used in 333 bus protocols where a master publishes a header and a slave responds with data, 334 such as LIN. Subscribing to headers lets you observe which frames are being 335 requested on the bus. 336 337 Args: 338 *headers: 339 One or more ``(namespace, frame_names)`` tuples. Each ``frame_names`` list 340 contains the names of the frames whose headers to subscribe to. 341 initial_empty: If ``True``, the first broker message (an empty sync marker) is 342 consumed internally before the iterator is returned, ensuring the broker is 343 ready before the first real value arrives. Useful when you need to guarantee 344 the subscription is live before publishing something. 345 346 Returns: 347 An async iterator yielding one `Header` per received frame header. 348 349 Raises: 350 ValueError: If no headers are provided. 351 """ 352 if not headers: 353 raise ValueError("No subscription info provided") 354 355 config = conv.signal_ids_to_grpc_subscriber_config([(ns, list(hdrs)) for ns, hdrs in headers], self.client_id, False, initial_empty) 356 stream = self._network_service.SubscribeToSignals(config) 357 358 # if initial_empty is set; drop the first message 359 if initial_empty: 360 await anext(stream.__aiter__()) 361 362 async def async_generator() -> AsyncIterator[Header]: 363 async for signal_batch in stream: 364 signal: network_api_pb2.Signal 365 for signal in signal_batch.signal: 366 if signal.HasField("arbitration") and signal.arbitration: 367 yield Header( 368 frame_name=signal.id.name, 369 namespace=signal.id.namespace.name, 370 ) 371 372 return async_generator() 373 374 async def subscribe_frames( 375 self, 376 *frames: tuple[NamespaceName, Sequence[str | FrameSubscription | FrameInfo | FilterLike]], 377 on_change: bool | OnChangeMode = False, 378 initial_empty: bool = False, 379 decode_named_values: bool = False, 380 ) -> AsyncIterator[Frame]: 381 """ 382 Subscribe to frames and their signals. 383 384 Each positional argument is a `(namespace, items)` tuple. The items sequence 385 accepts four types that can be freely mixed in the same list: 386 387 - `str` - subscribe to the named frame and all its signals. 388 - `FrameSubscription` - subscribe to a frame with explicit signal selection: 389 `signals=None` subscribes to all signals; `signals=[]` subscribes to the 390 frame identifier only. 391 - `FrameInfo` - subscribe using the signal list embedded in the metadata object, 392 as returned by `list_frame_infos()`. 393 - `FilterLike` - a `FrameFilterPredicate`, `SignalFilterPredicate`, or 394 `FrameSignalFilter`. All filter kinds in a single call are combined via 395 `filter_recursive()`, resolved at call time via `list_frame_infos()`. 396 397 Args: 398 *frames: 399 One or more `(namespace, items)` tuples describing what to subscribe to. 400 on_change: Delivery filtering. `False` (default) delivers every frame 401 transmission. `True` or `OnChangeMode.CHANGED` delivers only frames with 402 changed signals (yielded Frame contains only changed signals). 403 `OnChangeMode.MERGED` additionally maintains a client-side cache so the 404 yielded Frame always contains all signals seen so far. 405 initial_empty: If `True`, the first broker message (an empty sync marker) is 406 consumed internally before the iterator is returned, ensuring the broker is 407 ready before the first real value arrives. Useful when you need to guarantee 408 the subscription is live before publishing something. 409 decode_named_values: If `True`, integer signal values that have a named-value 410 mapping in the database (e.g. `{0: "OFF", 1: "ON"}`) are decoded to their 411 string names in the yielded `Frame.signals`. 412 413 Returns: 414 An async iterator yielding `Frame` objects, one per received frame transmission. 415 """ 416 if not frames: 417 raise ValueError("No subscription info provided") 418 419 mode = _resolve_on_change_mode(on_change) 420 grpc_on_change = mode in (OnChangeMode.CHANGED, OnChangeMode.MERGED) 421 422 processed_frames = await self._process_frame_subscriptions([(ns, list(frms)) for ns, frms in frames]) 423 signal_ids, signal_meta, frame_keys, signal_to_frame = await self._collect_subscription_metadata(processed_frames) 424 425 config = conv.signal_ids_to_grpc_subscriber_config( 426 [(ns, list(sigs)) for ns, sigs in signal_ids.items()], self.client_id, grpc_on_change, initial_empty 427 ) 428 stream: AsyncIterator[network_api_pb2.Signals] = self._network_service.SubscribeToSignals(config) 429 430 # if initial_empty is set; drop the first message 431 if initial_empty: 432 await anext(stream.__aiter__()) 433 434 only_frame_subscription: set[tuple[NamespaceName, FrameName]] = { 435 (ns, sub.name) for ns, subs in processed_frames for sub in subs if sub.signals == [] 436 } 437 processor = _FrameSubscriptionProcessor( 438 signal_to_frame=signal_to_frame, 439 signal_meta=signal_meta, 440 frame_keys=frame_keys, 441 only_frame_subscription=only_frame_subscription, 442 mode=mode, 443 decode_named_values=decode_named_values, 444 ) 445 446 async def async_generator() -> AsyncIterator[Frame]: 447 async for batch in stream: 448 frame = processor.process_batch(batch) 449 if frame is not None: 450 yield frame 451 452 return async_generator() 453 454 async def set_secoc_property(self, namespace: NamespaceName | NamespaceInfo, property: SecocProperty) -> None: 455 """ 456 Set a SecOC property on the broker. 457 458 Args: 459 namespace: Target namespace 460 property: The SecOC property to set. 461 """ 462 ns: str = namespace.name if isinstance(namespace, NamespaceInfo) else namespace 463 property_value = conv.property_to_grpc(ns, property) 464 await self._system_service.SetProperty(property_value) 465 466 async def switch_lin_schedule(self, namespace: NamespaceName | NamespaceInfo, schedule_table_name: str) -> None: 467 """ 468 Switch the active schedule for a LIN master namespace. 469 470 Args: 471 namespace: Target LIN namespace (must be a LIN master) 472 schedule_table_name: Name of the schedule table to activate 473 """ 474 ns: str = namespace.name if isinstance(namespace, NamespaceInfo) else namespace 475 request = system_api_pb2.LinScheduleSwitch(namespace=common_pb2.NameSpace(name=ns), schedule_table_name=schedule_table_name) 476 await self._system_service.SwitchLinSchedule(request) 477 478 async def list_namespaces(self) -> list[NamespaceInfo]: 479 """ 480 List all namespaces configured in the broker. 481 482 Returns: 483 A list of namespaces. 484 """ 485 namespaces = await self._get_namespaces() 486 return list(namespaces.values()) 487 488 async def get_namespace(self, name: NamespaceName) -> NamespaceInfo | None: 489 """ 490 Get a namespace by name. 491 492 Returns: 493 The namespace if found, otherwise None. 494 """ 495 namespaces = await self._get_namespaces() 496 return namespaces.get(name) 497 498 async def list_frame_infos(self, *namespaces: NamespaceName | NamespaceInfo) -> list[FrameInfo]: 499 """ 500 List all frame infos in one or more namespaces. 501 502 Args: 503 namespaces: One or more NamespaceName or NamespaceInfo objects. 504 505 Returns: 506 A list of FrameInfo objects. 507 """ 508 rets = await asyncio.gather(*(self._list_frame_infos(namespace) for namespace in namespaces)) 509 510 return [conv.grpc_to_frame_info(frame) for ret in rets for frame in ret.frame] 511 512 async def get_frame_info(self, name: FrameName, namespace: NamespaceName | NamespaceInfo) -> FrameInfo | None: 513 """ 514 Get a frame by name in a specific namespace. 515 516 Args: 517 name: The name of the frame. 518 namespace: The namespace name or NamespaceInfo object. 519 520 Returns: 521 The FrameInfo object if found, otherwise None. 522 """ 523 frames = await self.list_frame_infos(namespace) 524 for frame in frames: 525 if frame.name == name: 526 return frame 527 return None 528 529 async def list_signal_infos(self, *namespaces: NamespaceName | NamespaceInfo) -> list[SignalInfo]: 530 """ 531 List all signal infos in one or more namespaces. 532 533 Args: 534 namespaces: One or more NamespaceName or NamespaceInfo objects. 535 536 Returns: 537 A list of SignalInfo objects. 538 """ 539 rets = await asyncio.gather(*(self._list_frame_infos(namespace) for namespace in namespaces)) 540 541 all_signals = [] 542 for ret in rets: 543 frames_as_signals = [conv.grpc_frame_to_signal_info(frame) for frame in ret.frame] 544 signals = [conv.grpc_to_signal_info(child) for frame in ret.frame for child in frame.childInfo] 545 all_signals.extend(frames_as_signals + signals) 546 547 return all_signals 548 549 async def get_signal_info(self, name: SignalName, namespace: NamespaceName | NamespaceInfo) -> SignalInfo | None: 550 """ 551 Get a signal info by name in a specific namespace. 552 553 Args: 554 name: The name of the signal. 555 namespace: The namespace name or NamespaceInfo object. 556 557 Returns: 558 The SignalInfo object if found, otherwise None. 559 """ 560 signals = await self.list_signal_infos(namespace) 561 for signal in signals: 562 if signal.name == name: 563 return signal 564 return None 565 566 def is_ready(self) -> bool: 567 """ 568 Check if the broker client is ready. 569 570 Returns: 571 True if the broker client is ready, otherwise False. 572 """ 573 return self._get_state() == grpc.ChannelConnectivity.READY 574 575 def is_closed(self) -> bool: 576 """ 577 Check if the broker client is closed. 578 579 Returns: 580 True if the broker client is closed, otherwise False. 581 """ 582 return self._get_state() == grpc.ChannelConnectivity.SHUTDOWN 583 584 async def _process_signal_subscriptions( 585 self, 586 signals: list[tuple[NamespaceName, list[SignalName | SignalInfo | SignalFilterPredicate]]], 587 ) -> list[tuple[NamespaceName, list[SignalName]]]: 588 """ 589 Process signal subscriptions by resolving SignalInfo and applying SignalFilterPredicates. 590 """ 591 result = [] 592 593 for namespace, signal_list in signals: 594 # Partition items by type 595 signal_infos: list[SignalInfo] = [item for item in signal_list if isinstance(item, SignalInfo)] 596 predicates: list[SignalFilterPredicate] = [item for item in signal_list if is_signal_filter(item)] 597 signal_names: list[str] = [item for item in signal_list if isinstance(item, str)] 598 599 # Apply predicates to get SignalInfos 600 if predicates: 601 all_signal_infos = await self.list_signal_infos(namespace) # list is cached per namespace 602 # Use include_by_default=False since we want explicit inclusion via filters 603 filtered = apply_signal_filters(all_signal_infos, predicates, include_by_default=False) 604 signal_infos.extend(filtered) 605 606 # Convert SignalInfos to names 607 names_from_infos = [info.name for info in signal_infos] 608 609 # Combine all names 610 all_names = signal_names + names_from_infos 611 612 result.append((namespace, all_names)) 613 614 return result 615 616 async def _process_frame_subscriptions( 617 self, 618 frames: list[tuple[NamespaceName, Sequence[str | FrameSubscription | FrameInfo | FilterLike]]], 619 ) -> list[tuple[NamespaceName, list[FrameSubscription]]]: 620 """ 621 Process frame subscriptions by resolving FrameInfo and applying filter predicates via filter_recursive. 622 """ 623 result = [] 624 625 for namespace, frame_list in frames: 626 # Partition items by type 627 existing_subscriptions = [item for item in frame_list if isinstance(item, FrameSubscription)] 628 frame_infos: list[FrameInfo] = [item for item in frame_list if isinstance(item, FrameInfo)] 629 predicates: list[FilterLike] = [item for item in frame_list if is_filter(item)] 630 frame_names = [item for item in frame_list if isinstance(item, str)] 631 632 # Apply predicates to get FrameInfos 633 if predicates: 634 all_frame_infos = await self.list_frame_infos(namespace) # list is cached per namespace 635 # Apply filters to each frame and collect non-None results (signal-trimmed when applicable) 636 filtered = [f for frame in all_frame_infos if (f := filter_recursive(frame, predicates)) is not None] 637 frame_infos.extend(filtered) 638 639 # Convert FrameInfos to FrameSubscriptions 640 subscriptions_from_infos = [FrameSubscription(name=info.name, signals=list(info.signals.keys())) for info in frame_infos] 641 642 # Convert str to FrameSubscriptions 643 subscriptions_from_names = [FrameSubscription(name=name) for name in frame_names] 644 645 # Combine all subscriptions 646 all_subscriptions = existing_subscriptions + subscriptions_from_infos + subscriptions_from_names 647 648 result.append((namespace, all_subscriptions)) 649 650 return result 651 652 async def _collect_subscription_metadata( 653 self, 654 frames: list[tuple[NamespaceName, list[FrameSubscription]]], 655 ) -> tuple[ 656 dict[NamespaceName, set[SignalName]], 657 dict[tuple[NamespaceName, FrameName, SignalName], SignalInfo], 658 set[tuple[NamespaceName, FrameName]], 659 dict[tuple[NamespaceName, SignalName], FrameName], 660 ]: 661 """ 662 Collect signal metadata for frame subscriptions. 663 """ 664 signal_ids = defaultdict(set) 665 signal_meta = {} 666 frame_keys = set() 667 signal_to_frame: dict[tuple[NamespaceName, SignalName], FrameName] = {} 668 669 for ns, subs in frames: 670 for sub in subs: 671 info = await self.get_frame_info(sub.name, ns) 672 if not info: 673 _logger.warning(f"Frame {sub.name} not found in namespace {ns}") 674 continue 675 676 sigs = list(info.signals) if sub.signals is None else sub.signals 677 signal_ids[ns].update([sub.name, *sigs]) 678 frame_keys.add((ns, sub.name)) 679 680 # Collect signal metadata (only for valid signals in frame) 681 signal_meta.update({(ns, sub.name, s): info.signals[s] for s in sigs if s in info.signals}) 682 683 signal_to_frame[(ns, sub.name)] = sub.name 684 for s in sigs: 685 signal_to_frame[(ns, s)] = sub.name 686 687 return signal_ids, signal_meta, frame_keys, signal_to_frame 688 689 async def _list_frame_infos(self, namespace: NamespaceName | NamespaceInfo) -> common_pb2.Frames: 690 if isinstance(namespace, NamespaceInfo): 691 namespace = namespace.name 692 if namespace not in self._cache: 693 self._cache[namespace] = await self._system_service.ListSignals(conv.namespace_to_grpc(namespace)) 694 return self._cache[namespace] 695 696 async def _get_namespaces(self) -> dict[str, NamespaceInfo]: 697 if len(self._namespace_cache) == 0: 698 configs = await self._system_service.GetConfiguration(common_pb2.Empty()) 699 for ns in [conv.grpc_to_namespace_info(info) for info in configs.networkInfo]: 700 self._namespace_cache[ns.name] = ns 701 702 return self._namespace_cache
Client for signal-related operations.
159 def __init__(self, url: str, client_id: str | None = None, auth: AuthMethod = NoAuth()): 160 """ 161 Initializes a new BrokerClient instance. 162 163 Args: 164 url: The RemotiveBroker URL to connect to. 165 client_id: Optional client ID. If None, a random ID is generated. 166 auth: Authentication method to use. Defaults to NoAuth. 167 168 Note: 169 Start the instance using a context manager: 170 ```python 171 async with BrokerClient(...) as client: 172 ... 173 ``` 174 175 Or use the connect/disconnect methods directly: 176 ```python 177 client = await BrokerClient(...).connect() 178 # ... 179 await client.disconnect() 180 ``` 181 """ 182 super().__init__(url=url, client_id=client_id, auth=auth) 183 184 self._traffic_service = traffic_api_pb2_grpc.TrafficServiceStub(self._channel) 185 self._recording_session_service = recordingsession_api_pb2_grpc.RecordingSessionServiceStub(self._channel) 186 self.restbus = Restbus(self._channel, self._restbus_update_call, self._client_id) 187 self._cache: dict[str, common_pb2.Frames] = {} 188 self._namespace_cache: dict[str, NamespaceInfo] = {}
Initializes a new BrokerClient instance.
Arguments:
- url: The RemotiveBroker URL to connect to.
- client_id: Optional client ID. If None, a random ID is generated.
- auth: Authentication method to use. Defaults to NoAuth.
Note:
Start the instance using a context manager:
async with BrokerClient(...) as client: ...Or use the connect/disconnect methods directly:
client = await BrokerClient(...).connect() # ... await client.disconnect()
190 async def broker_version(self) -> str: 191 """ 192 Returns the broker version 193 """ 194 config = await self._system_service.GetConfiguration(common_pb2.Empty()) 195 return str(config.serverVersion.lstrip("v"))
Returns the broker version
197 async def topology_instance_id(self) -> str | None: 198 """ 199 Returns the topology instance ID used to generate the configuration for this broker, 200 or None if broker is not part of a topology. 201 """ 202 config = await self._system_service.GetConfiguration(common_pb2.Empty()) 203 return config.topologyInstanceId or None
Returns the topology instance ID used to generate the configuration for this broker, or None if broker is not part of a topology.
205 async def read_signals(self, *values: tuple[NamespaceName, list[str]]) -> list[Signal]: 206 """ 207 Read signals from signal cache 208 209 Args: 210 *values: 211 One or more tuples, each containing a namespace and a list of signal names of the signals to read. 212 213 Raises: 214 ValueError: If the list of values is empty. 215 """ 216 217 if not values: 218 raise ValueError("No signals provided") 219 signals = await self._network_service.ReadSignals(conv.tuple_to_signal_ids(list(values))) 220 return [conv.grpc_to_signal(signal) for signal in signals.signal if not signal.HasField("arbitration")]
Read signals from signal cache
Arguments:
- *values: One or more tuples, each containing a namespace and a list of signal names of the signals to read.
Raises:
- ValueError: If the list of values is empty.
222 async def publish(self, *values: tuple[NamespaceName, list[WriteSignal]]) -> None: 223 """ 224 Publish a list of signals to the broker. 225 226 Args: 227 *values: 228 One or more tuples, each containing a namespace and a list of signals to publish. 229 230 Raises: 231 ValueError: If the list of values is empty. 232 """ 233 234 if not values: 235 raise ValueError("No signals provided") 236 237 await self._do_publish(conv.write_signal_to_grpc_publisher_config(list(values), self.client_id))
Publish a list of signals to the broker.
Arguments:
- *values: One or more tuples, each containing a namespace and a list of signals to publish.
Raises:
- ValueError: If the list of values is empty.
239 async def publish_header(self, *headers: tuple[NamespaceName, list[FrameName]]) -> None: 240 """ 241 Publish a list of headers to the broker. 242 243 Args: 244 *headers: 245 One or more tuples, each containing a namespace and a list of frame names of which headers to publish. 246 247 Raises: 248 ValueError: If the list of values is empty. 249 """ 250 251 if not headers: 252 raise ValueError("No signals provided") 253 254 await self._do_publish(conv.header_to_grpc_publisher_config(list(headers), self.client_id))
Publish a list of headers to the broker.
Arguments:
- *headers: One or more tuples, each containing a namespace and a list of frame names of which headers to publish.
Raises:
- ValueError: If the list of values is empty.
270 async def subscribe( 271 self, 272 *signals: tuple[NamespaceName, Sequence[SignalName | SignalInfo | SignalFilterPredicate]], 273 on_change: bool = False, 274 initial_empty: bool = False, 275 ) -> AsyncIterator[list[Signal]]: 276 """ 277 Subscribe to individual signals by name, metadata, or filter predicate. 278 279 Each positional argument is a ``(namespace, items)`` tuple. Items can be freely mixed: 280 281 - ``str`` - subscribe to the named signal. 282 - `SignalInfo` - subscribe using a metadata object returned by `list_signal_infos()`. 283 - `remotivelabs.broker.filters.SignalFilterPredicate` - subscribe to all signals matching the predicate; resolved 284 at call time via `list_signal_infos()`. 285 286 For frame-level subscriptions (receiving signals grouped by frame with a timestamp), 287 use `subscribe_frames()` instead. 288 289 Args: 290 *signals: 291 One or more ``(namespace, items)`` tuples describing which signals to subscribe to. 292 on_change: Whether to receive updates only on change. 293 initial_empty: If ``True``, the first broker message (an empty sync marker) is 294 consumed internally before the iterator is returned, ensuring the broker is 295 ready before the first real value arrives. Useful when you need to guarantee 296 the subscription is live before publishing something. 297 298 Returns: 299 An async iterator yielding batches of `Signal` objects. 300 301 Raises: 302 ValueError: If no signals are provided. 303 """ 304 if not signals: 305 raise ValueError("No subscription info provided") 306 307 processed_signals = await self._process_signal_subscriptions([(ns, list(sigs)) for ns, sigs in signals]) 308 309 config = conv.signal_ids_to_grpc_subscriber_config(processed_signals, self.client_id, on_change, initial_empty) 310 stream = self._network_service.SubscribeToSignals(config) 311 312 # if initial_empty is set; drop the first message 313 if initial_empty: 314 await anext(stream.__aiter__()) 315 316 async def async_generator() -> AsyncIterator[list[Signal]]: 317 async for signal_batch in stream: 318 signals = [conv.grpc_to_signal(signal) for signal in signal_batch.signal if not signal.HasField("arbitration")] 319 if signals: 320 yield signals 321 322 return async_generator()
Subscribe to individual signals by name, metadata, or filter predicate.
Each positional argument is a (namespace, items) tuple. Items can be freely mixed:
str- subscribe to the named signal.SignalInfo- subscribe using a metadata object returned bylist_signal_infos().remotivelabs.broker.filters.SignalFilterPredicate- subscribe to all signals matching the predicate; resolved at call time vialist_signal_infos().
For frame-level subscriptions (receiving signals grouped by frame with a timestamp),
use subscribe_frames() instead.
Arguments:
- *signals: One or more
(namespace, items)tuples describing which signals to subscribe to. - on_change: Whether to receive updates only on change.
- initial_empty: If
True, the first broker message (an empty sync marker) is consumed internally before the iterator is returned, ensuring the broker is ready before the first real value arrives. Useful when you need to guarantee the subscription is live before publishing something.
Returns:
An async iterator yielding batches of
Signalobjects.
Raises:
- ValueError: If no signals are provided.
324 async def subscribe_header( 325 self, 326 *headers: tuple[NamespaceName, Sequence[FrameName]], 327 initial_empty: bool = False, 328 ) -> AsyncIterator[Header]: 329 """ 330 Subscribe to frame headers. 331 332 Headers carry only the frame identifier - no signal values. This is used in 333 bus protocols where a master publishes a header and a slave responds with data, 334 such as LIN. Subscribing to headers lets you observe which frames are being 335 requested on the bus. 336 337 Args: 338 *headers: 339 One or more ``(namespace, frame_names)`` tuples. Each ``frame_names`` list 340 contains the names of the frames whose headers to subscribe to. 341 initial_empty: If ``True``, the first broker message (an empty sync marker) is 342 consumed internally before the iterator is returned, ensuring the broker is 343 ready before the first real value arrives. Useful when you need to guarantee 344 the subscription is live before publishing something. 345 346 Returns: 347 An async iterator yielding one `Header` per received frame header. 348 349 Raises: 350 ValueError: If no headers are provided. 351 """ 352 if not headers: 353 raise ValueError("No subscription info provided") 354 355 config = conv.signal_ids_to_grpc_subscriber_config([(ns, list(hdrs)) for ns, hdrs in headers], self.client_id, False, initial_empty) 356 stream = self._network_service.SubscribeToSignals(config) 357 358 # if initial_empty is set; drop the first message 359 if initial_empty: 360 await anext(stream.__aiter__()) 361 362 async def async_generator() -> AsyncIterator[Header]: 363 async for signal_batch in stream: 364 signal: network_api_pb2.Signal 365 for signal in signal_batch.signal: 366 if signal.HasField("arbitration") and signal.arbitration: 367 yield Header( 368 frame_name=signal.id.name, 369 namespace=signal.id.namespace.name, 370 ) 371 372 return async_generator()
Subscribe to frame headers.
Headers carry only the frame identifier - no signal values. This is used in bus protocols where a master publishes a header and a slave responds with data, such as LIN. Subscribing to headers lets you observe which frames are being requested on the bus.
Arguments:
- *headers: One or more
(namespace, frame_names)tuples. Eachframe_nameslist contains the names of the frames whose headers to subscribe to. - initial_empty: If
True, the first broker message (an empty sync marker) is consumed internally before the iterator is returned, ensuring the broker is ready before the first real value arrives. Useful when you need to guarantee the subscription is live before publishing something.
Returns:
An async iterator yielding one
Headerper received frame header.
Raises:
- ValueError: If no headers are provided.
374 async def subscribe_frames( 375 self, 376 *frames: tuple[NamespaceName, Sequence[str | FrameSubscription | FrameInfo | FilterLike]], 377 on_change: bool | OnChangeMode = False, 378 initial_empty: bool = False, 379 decode_named_values: bool = False, 380 ) -> AsyncIterator[Frame]: 381 """ 382 Subscribe to frames and their signals. 383 384 Each positional argument is a `(namespace, items)` tuple. The items sequence 385 accepts four types that can be freely mixed in the same list: 386 387 - `str` - subscribe to the named frame and all its signals. 388 - `FrameSubscription` - subscribe to a frame with explicit signal selection: 389 `signals=None` subscribes to all signals; `signals=[]` subscribes to the 390 frame identifier only. 391 - `FrameInfo` - subscribe using the signal list embedded in the metadata object, 392 as returned by `list_frame_infos()`. 393 - `FilterLike` - a `FrameFilterPredicate`, `SignalFilterPredicate`, or 394 `FrameSignalFilter`. All filter kinds in a single call are combined via 395 `filter_recursive()`, resolved at call time via `list_frame_infos()`. 396 397 Args: 398 *frames: 399 One or more `(namespace, items)` tuples describing what to subscribe to. 400 on_change: Delivery filtering. `False` (default) delivers every frame 401 transmission. `True` or `OnChangeMode.CHANGED` delivers only frames with 402 changed signals (yielded Frame contains only changed signals). 403 `OnChangeMode.MERGED` additionally maintains a client-side cache so the 404 yielded Frame always contains all signals seen so far. 405 initial_empty: If `True`, the first broker message (an empty sync marker) is 406 consumed internally before the iterator is returned, ensuring the broker is 407 ready before the first real value arrives. Useful when you need to guarantee 408 the subscription is live before publishing something. 409 decode_named_values: If `True`, integer signal values that have a named-value 410 mapping in the database (e.g. `{0: "OFF", 1: "ON"}`) are decoded to their 411 string names in the yielded `Frame.signals`. 412 413 Returns: 414 An async iterator yielding `Frame` objects, one per received frame transmission. 415 """ 416 if not frames: 417 raise ValueError("No subscription info provided") 418 419 mode = _resolve_on_change_mode(on_change) 420 grpc_on_change = mode in (OnChangeMode.CHANGED, OnChangeMode.MERGED) 421 422 processed_frames = await self._process_frame_subscriptions([(ns, list(frms)) for ns, frms in frames]) 423 signal_ids, signal_meta, frame_keys, signal_to_frame = await self._collect_subscription_metadata(processed_frames) 424 425 config = conv.signal_ids_to_grpc_subscriber_config( 426 [(ns, list(sigs)) for ns, sigs in signal_ids.items()], self.client_id, grpc_on_change, initial_empty 427 ) 428 stream: AsyncIterator[network_api_pb2.Signals] = self._network_service.SubscribeToSignals(config) 429 430 # if initial_empty is set; drop the first message 431 if initial_empty: 432 await anext(stream.__aiter__()) 433 434 only_frame_subscription: set[tuple[NamespaceName, FrameName]] = { 435 (ns, sub.name) for ns, subs in processed_frames for sub in subs if sub.signals == [] 436 } 437 processor = _FrameSubscriptionProcessor( 438 signal_to_frame=signal_to_frame, 439 signal_meta=signal_meta, 440 frame_keys=frame_keys, 441 only_frame_subscription=only_frame_subscription, 442 mode=mode, 443 decode_named_values=decode_named_values, 444 ) 445 446 async def async_generator() -> AsyncIterator[Frame]: 447 async for batch in stream: 448 frame = processor.process_batch(batch) 449 if frame is not None: 450 yield frame 451 452 return async_generator()
Subscribe to frames and their signals.
Each positional argument is a (namespace, items) tuple. The items sequence
accepts four types that can be freely mixed in the same list:
str- subscribe to the named frame and all its signals.FrameSubscription- subscribe to a frame with explicit signal selection:signals=Nonesubscribes to all signals;signals=[]subscribes to the frame identifier only.FrameInfo- subscribe using the signal list embedded in the metadata object, as returned bylist_frame_infos().FilterLike- aFrameFilterPredicate,SignalFilterPredicate, orFrameSignalFilter. All filter kinds in a single call are combined viafilter_recursive(), resolved at call time vialist_frame_infos().
Arguments:
- *frames: One or more
(namespace, items)tuples describing what to subscribe to. - on_change: Delivery filtering.
False(default) delivers every frame transmission.TrueorOnChangeMode.CHANGEDdelivers only frames with changed signals (yielded Frame contains only changed signals).OnChangeMode.MERGEDadditionally maintains a client-side cache so the yielded Frame always contains all signals seen so far. - initial_empty: If
True, the first broker message (an empty sync marker) is consumed internally before the iterator is returned, ensuring the broker is ready before the first real value arrives. Useful when you need to guarantee the subscription is live before publishing something. - decode_named_values: If
True, integer signal values that have a named-value mapping in the database (e.g.{0: "OFF", 1: "ON"}) are decoded to their string names in the yieldedFrame.signals.
Returns:
An async iterator yielding
Frameobjects, one per received frame transmission.
454 async def set_secoc_property(self, namespace: NamespaceName | NamespaceInfo, property: SecocProperty) -> None: 455 """ 456 Set a SecOC property on the broker. 457 458 Args: 459 namespace: Target namespace 460 property: The SecOC property to set. 461 """ 462 ns: str = namespace.name if isinstance(namespace, NamespaceInfo) else namespace 463 property_value = conv.property_to_grpc(ns, property) 464 await self._system_service.SetProperty(property_value)
Set a SecOC property on the broker.
Arguments:
- namespace: Target namespace
- property: The SecOC property to set.
466 async def switch_lin_schedule(self, namespace: NamespaceName | NamespaceInfo, schedule_table_name: str) -> None: 467 """ 468 Switch the active schedule for a LIN master namespace. 469 470 Args: 471 namespace: Target LIN namespace (must be a LIN master) 472 schedule_table_name: Name of the schedule table to activate 473 """ 474 ns: str = namespace.name if isinstance(namespace, NamespaceInfo) else namespace 475 request = system_api_pb2.LinScheduleSwitch(namespace=common_pb2.NameSpace(name=ns), schedule_table_name=schedule_table_name) 476 await self._system_service.SwitchLinSchedule(request)
Switch the active schedule for a LIN master namespace.
Arguments:
- namespace: Target LIN namespace (must be a LIN master)
- schedule_table_name: Name of the schedule table to activate
478 async def list_namespaces(self) -> list[NamespaceInfo]: 479 """ 480 List all namespaces configured in the broker. 481 482 Returns: 483 A list of namespaces. 484 """ 485 namespaces = await self._get_namespaces() 486 return list(namespaces.values())
List all namespaces configured in the broker.
Returns:
A list of namespaces.
488 async def get_namespace(self, name: NamespaceName) -> NamespaceInfo | None: 489 """ 490 Get a namespace by name. 491 492 Returns: 493 The namespace if found, otherwise None. 494 """ 495 namespaces = await self._get_namespaces() 496 return namespaces.get(name)
Get a namespace by name.
Returns:
The namespace if found, otherwise None.
498 async def list_frame_infos(self, *namespaces: NamespaceName | NamespaceInfo) -> list[FrameInfo]: 499 """ 500 List all frame infos in one or more namespaces. 501 502 Args: 503 namespaces: One or more NamespaceName or NamespaceInfo objects. 504 505 Returns: 506 A list of FrameInfo objects. 507 """ 508 rets = await asyncio.gather(*(self._list_frame_infos(namespace) for namespace in namespaces)) 509 510 return [conv.grpc_to_frame_info(frame) for ret in rets for frame in ret.frame]
List all frame infos in one or more namespaces.
Arguments:
- namespaces: One or more NamespaceName or NamespaceInfo objects.
Returns:
A list of FrameInfo objects.
512 async def get_frame_info(self, name: FrameName, namespace: NamespaceName | NamespaceInfo) -> FrameInfo | None: 513 """ 514 Get a frame by name in a specific namespace. 515 516 Args: 517 name: The name of the frame. 518 namespace: The namespace name or NamespaceInfo object. 519 520 Returns: 521 The FrameInfo object if found, otherwise None. 522 """ 523 frames = await self.list_frame_infos(namespace) 524 for frame in frames: 525 if frame.name == name: 526 return frame 527 return None
Get a frame by name in a specific namespace.
Arguments:
- name: The name of the frame.
- namespace: The namespace name or NamespaceInfo object.
Returns:
The FrameInfo object if found, otherwise None.
529 async def list_signal_infos(self, *namespaces: NamespaceName | NamespaceInfo) -> list[SignalInfo]: 530 """ 531 List all signal infos in one or more namespaces. 532 533 Args: 534 namespaces: One or more NamespaceName or NamespaceInfo objects. 535 536 Returns: 537 A list of SignalInfo objects. 538 """ 539 rets = await asyncio.gather(*(self._list_frame_infos(namespace) for namespace in namespaces)) 540 541 all_signals = [] 542 for ret in rets: 543 frames_as_signals = [conv.grpc_frame_to_signal_info(frame) for frame in ret.frame] 544 signals = [conv.grpc_to_signal_info(child) for frame in ret.frame for child in frame.childInfo] 545 all_signals.extend(frames_as_signals + signals) 546 547 return all_signals
List all signal infos in one or more namespaces.
Arguments:
- namespaces: One or more NamespaceName or NamespaceInfo objects.
Returns:
A list of SignalInfo objects.
549 async def get_signal_info(self, name: SignalName, namespace: NamespaceName | NamespaceInfo) -> SignalInfo | None: 550 """ 551 Get a signal info by name in a specific namespace. 552 553 Args: 554 name: The name of the signal. 555 namespace: The namespace name or NamespaceInfo object. 556 557 Returns: 558 The SignalInfo object if found, otherwise None. 559 """ 560 signals = await self.list_signal_infos(namespace) 561 for signal in signals: 562 if signal.name == name: 563 return signal 564 return None
Get a signal info by name in a specific namespace.
Arguments:
- name: The name of the signal.
- namespace: The namespace name or NamespaceInfo object.
Returns:
The SignalInfo object if found, otherwise None.
566 def is_ready(self) -> bool: 567 """ 568 Check if the broker client is ready. 569 570 Returns: 571 True if the broker client is ready, otherwise False. 572 """ 573 return self._get_state() == grpc.ChannelConnectivity.READY
Check if the broker client is ready.
Returns:
True if the broker client is ready, otherwise False.
575 def is_closed(self) -> bool: 576 """ 577 Check if the broker client is closed. 578 579 Returns: 580 True if the broker client is closed, otherwise False. 581 """ 582 return self._get_state() == grpc.ChannelConnectivity.SHUTDOWN
Check if the broker client is closed.
Returns:
True if the broker client is closed, otherwise False.
136@dataclass(frozen=True) 137class Frame: 138 """ 139 A live snapshot of a frame carrying actual signal values and a timestamp. 140 141 Yielded by `BrokerClient.subscribe_frames()`. Shares the same ``name`` and 142 ``namespace`` as `FrameInfo`, but ``signals`` contains decoded values. 143 144 Attributes: 145 timestamp: Time of first reception in microseconds. 146 name: Name of the frame. 147 namespace: Namespace to which the frame belongs. 148 signals: Dict mapping signal names to their current decoded values. 149 value: Raw frame value (e.g. the serialized byte payload). 150 """ 151 152 timestamp: int 153 name: FrameName 154 namespace: NamespaceName 155 signals: dict[str, SignalValue] 156 value: SignalValue 157 158 def __str__(self) -> str: 159 signals_str = ", ".join(f"{k}={v!r}" for k, v in self.signals.items()) 160 return f"{self.namespace}.{self.name}: {self.value!r} @ {self.timestamp}µs, signals={{ {signals_str} }}"
A live snapshot of a frame carrying actual signal values and a timestamp.
Yielded by BrokerClient.subscribe_frames(). Shares the same name and
namespace as FrameInfo, but signals contains decoded values.
Attributes:
- timestamp: Time of first reception in microseconds.
- name: Name of the frame.
- namespace: Namespace to which the frame belongs.
- signals: Dict mapping signal names to their current decoded values.
- value: Raw frame value (e.g. the serialized byte payload).
97@dataclass 98class FrameInfo: 99 """ 100 Static metadata about a frame as defined in the signal database. 101 102 Returned by `BrokerClient.list_frame_infos()` and `BrokerClient.get_frame_info()`. 103 Use it to introspect the database, build filter predicates, or construct a 104 `FrameSubscription`. It does not carry live signal values - see `Frame` for that. 105 106 Attributes: 107 id: Frame identifier. 108 name: Name of the frame. 109 namespace: Namespace to which the frame belongs. 110 signals: Dict of signal names and their corresponding `SignalInfo` metadata. 111 sender: List of entities that send this frame. 112 receiver: List of entities that receive this frame. 113 cycle_time_millis: Frame cycle time in milliseconds. 114 description: Human-readable description of the frame. 115 payload_size: Frame payload size in bits. 116 e2e: End-to-end protection configuration for the frame. 117 groups: List of byte groups within the frame, each optionally E2E-protected. 118 """ 119 120 id: int 121 name: FrameName 122 namespace: NamespaceName 123 signals: dict[SignalName, SignalInfo] 124 sender: list[str] 125 receiver: list[str] 126 cycle_time_millis: float 127 description: Optional[str] = None 128 payload_size: Optional[int] = None 129 e2e: Optional[E2eProfile] = None 130 groups: Optional[list[GroupInfo]] = None 131 132 def __str__(self) -> str: 133 return f"{self.namespace}.{self.name}, signals={len(self.signals)}, cycle={self.cycle_time_millis}ms"
Static metadata about a frame as defined in the signal database.
Returned by BrokerClient.list_frame_infos() and BrokerClient.get_frame_info().
Use it to introspect the database, build filter predicates, or construct a
FrameSubscription. It does not carry live signal values - see Frame for that.
Attributes:
- id: Frame identifier.
- name: Name of the frame.
- namespace: Namespace to which the frame belongs.
- signals: Dict of signal names and their corresponding
SignalInfometadata. - sender: List of entities that send this frame.
- receiver: List of entities that receive this frame.
- cycle_time_millis: Frame cycle time in milliseconds.
- description: Human-readable description of the frame.
- payload_size: Frame payload size in bits.
- e2e: End-to-end protection configuration for the frame.
- groups: List of byte groups within the frame, each optionally E2E-protected.
184@dataclass(frozen=True) 185class FrameSubscription: 186 """ 187 Describes which frame and signals to subscribe to in `BrokerClient.subscribe_frames()`. 188 189 Attributes: 190 name: Name of the frame to subscribe to. 191 signals: Controls which signals are included: 192 193 - ``None`` (default) - subscribe to all signals in the frame. 194 - ``[]`` - subscribe to the frame identifier only, with no signals 195 (useful for receiving LIN headers without payload). 196 - ``["sig1", "sig2"]`` - subscribe to the listed signals only. 197 """ 198 199 name: str 200 signals: list[SignalName] | None = None
Describes which frame and signals to subscribe to in BrokerClient.subscribe_frames().
Attributes:
- name: Name of the frame to subscribe to.
signals: Controls which signals are included:
None(default) - subscribe to all signals in the frame.[]- subscribe to the frame identifier only, with no signals (useful for receiving LIN headers without payload).["sig1", "sig2"]- subscribe to the listed signals only.
163@dataclass(frozen=True) 164class Header: 165 """ 166 A frame header (arbitration identifier) without payload signals. 167 168 Used in protocols where a master publishes an identifier and a slave responds 169 with data, such as LIN. Yielded by `BrokerClient.subscribe_header()` and 170 passed to `BrokerClient.publish_header()`. 171 172 Attributes: 173 frame_name: The name of the frame whose header to publish or that was received. 174 namespace: The namespace the header belongs to. 175 """ 176 177 frame_name: FrameName 178 namespace: NamespaceName 179 180 def __str__(self) -> str: 181 return f"{self.namespace}.{self.frame_name}"
A frame header (arbitration identifier) without payload signals.
Used in protocols where a master publishes an identifier and a slave responds
with data, such as LIN. Yielded by BrokerClient.subscribe_header() and
passed to BrokerClient.publish_header().
Attributes:
- frame_name: The name of the frame whose header to publish or that was received.
- namespace: The namespace the header belongs to.
41class OnChangeMode(Enum): 42 """ 43 Controls how signal changes are reported by a frame subscription. 44 45 - OFF: Every frame transmission is delivered regardless of whether any signal value 46 changed. This is the default and mirrors raw bus behavior. 47 48 - CHANGED: The yielded `Frame` contains **only the signals that changed** in that delivery 49 unchanged signals are absent from `Frame.signals`. 50 51 - MERGED: Like `CHANGED`, the broker only sends frames with changed signals. 52 In addition, this client maintains a per-frame signal cache. Before yielding, 53 it merges the incoming changed signals into the cache and yields a `Frame` 54 whose `Frame.signals` dict always contains **all signals seen so far**, not just 55 the ones that changed in the latest delivery. 56 """ 57 58 OFF = "off" 59 CHANGED = "changed" 60 MERGED = "merged"
Controls how signal changes are reported by a frame subscription.
OFF: Every frame transmission is delivered regardless of whether any signal value changed. This is the default and mirrors raw bus behavior.
CHANGED: The yielded
Framecontains only the signals that changed in that delivery unchanged signals are absent fromFrame.signals.MERGED: Like
CHANGED, the broker only sends frames with changed signals. In addition, this client maintains a per-frame signal cache. Before yielding, it merges the incoming changed signals into the cache and yields aFramewhoseFrame.signalsdict always contains all signals seen so far, not just the ones that changed in the latest delivery.
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.
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:
- initial - values emitted once, in order, before the loop starts. May be empty.
- 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:
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
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
49@dataclass(frozen=True) 50class SecocCmac0: 51 """ 52 Use CMAC0 for SecOC in the RemotiveBroker. 53 """ 54 55 enabled: bool
Use CMAC0 for SecOC in the RemotiveBroker.
17@dataclass(frozen=True) 18class SecocFreshnessValue: 19 """ 20 Set SecOC binary freshness value to be used by freshness manager. 21 Property is limited to SecOC on a given name space. 22 """ 23 24 fv: bytes
Set SecOC binary freshness value to be used by freshness manager. Property is limited to SecOC on a given name space.
37@dataclass(frozen=True) 38class SecocKey: 39 """ 40 Set binary 128-bit key to be used for SecOC in the RemotiveBroker. 41 42 Multiple keys can be set and are separated by key ID's. 43 """ 44 45 key_id: int 46 key: bytes
Set binary 128-bit key to be used for SecOC in the RemotiveBroker.
Multiple keys can be set and are separated by key ID's.
27@dataclass(frozen=True) 28class SecocTimeDiff: 29 """ 30 Set a time delta to use in real time clock for SecOC freshness value. Time 31 difference is in floating point seconds and is limited to a name space. 32 """ 33 34 time_diff: float
Set a time delta to use in real time clock for SecOC freshness value. Time difference is in floating point seconds and is limited to a name space.
24@dataclass(frozen=True) 25class MultiplexInfoFilter: 26 """ 27 Marks a signal as a mux filter. 28 29 The signal is only active when the selector equals filter_value. 30 31 Attributes: 32 filter_value: The selector value that activates this signal. 33 """ 34 35 filter_value: int
Marks a signal as a mux filter.
The signal is only active when the selector equals filter_value.
Attributes:
- filter_value: The selector value that activates this signal.
14@dataclass(frozen=True) 15class MultiplexInfoSelector: 16 """ 17 Marks a signal as the mux selector. 18 19 The value of this signal determines which filter signals are active. 20 A selector carries no filter value. 21 """
Marks a signal as the mux selector.
The value of this signal determines which filter signals are active. A selector carries no filter value.
46@dataclass(frozen=True) 47class Signal: 48 """ 49 A live signal value received from the broker. 50 51 Yielded by `BrokerClient.subscribe()` and `BrokerClient.read_signals()`. 52 For signals grouped by frame with a timestamp, use `BrokerClient.subscribe_frames()` 53 which yields `remotivelabs.broker.frame.Frame` objects instead. 54 55 Attributes: 56 name: The name of the signal. 57 namespace: The namespace the signal belongs to. 58 value: The current decoded value of the signal. 59 """ 60 61 name: SignalName 62 namespace: NamespaceName 63 value: SignalValue 64 65 def __str__(self) -> str: 66 return f"{self.namespace}.{self.name}: {self.value!r}"
A live signal value received from the broker.
Yielded by BrokerClient.subscribe() and BrokerClient.read_signals().
For signals grouped by frame with a timestamp, use BrokerClient.subscribe_frames()
which yields remotivelabs.broker.frame.Frame objects instead.
Attributes:
- name: The name of the signal.
- namespace: The namespace the signal belongs to.
- value: The current decoded value of the signal.
89@dataclass(frozen=True) 90class SignalInfo: 91 """ 92 Static metadata describing a signal as defined in the signal database. 93 94 Returned by `BrokerClient.list_signal_infos()` and `BrokerClient.get_signal_info()`, 95 and embedded in `remotivelabs.broker.frame.FrameInfo.signals`. Use it to introspect 96 signal encoding, build filter predicates, or pass directly to `BrokerClient.subscribe()`. 97 It does not carry a live value - see `Signal` for that. 98 99 Attributes: 100 name: Name of the signal. 101 namespace: Namespace the signal belongs to. 102 receiver: List of receivers for the signal. 103 sender: List of senders for the signal. 104 named_values: Mapping from raw numeric values to symbolic names (e.g., enums). 105 value_names: Reverse mapping from symbolic names to raw numeric values. 106 min: Minimum allowed value. 107 max: Maximum allowed value. 108 factor: Multiplication factor used for encoding and decoding the value in the frame. 109 offset: Offset used for encoding and decoding the value in the frame. 110 start_value: Initial value to use before publishing. 111 size: Size of the signal value when packed in the frame (bits). 112 start_bit: Index of the first bit where this signal's data begins inside the frame. 113 unit: Unit of the signal value. 114 description: Description of the signal, taken from the signal database. 115 multiplex: Multiplexing role of the signal, if any. 116 """ 117 118 name: SignalName 119 namespace: NamespaceName 120 receiver: list[str] 121 sender: list[str] 122 named_values: dict[int, str] 123 value_names: dict[str, int] 124 min: float 125 max: float 126 factor: float 127 offset: float 128 start_value: float 129 size: int 130 start_bit: int 131 unit: Optional[str] = None 132 description: Optional[str] = None 133 multiplex: Optional[MultiplexInfo] = None 134 135 def __str__(self) -> str: 136 return f"{self.namespace}.{self.name}"
Static metadata describing a signal as defined in the signal database.
Returned by BrokerClient.list_signal_infos() and BrokerClient.get_signal_info(),
and embedded in remotivelabs.broker.frame.FrameInfo.signals. Use it to introspect
signal encoding, build filter predicates, or pass directly to BrokerClient.subscribe().
It does not carry a live value - see Signal for that.
Attributes:
- name: Name of the signal.
- namespace: Namespace the signal belongs to.
- receiver: List of receivers for the signal.
- sender: List of senders for the signal.
- named_values: Mapping from raw numeric values to symbolic names (e.g., enums).
- value_names: Reverse mapping from symbolic names to raw numeric values.
- min: Minimum allowed value.
- max: Maximum allowed value.
- factor: Multiplication factor used for encoding and decoding the value in the frame.
- offset: Offset used for encoding and decoding the value in the frame.
- start_value: Initial value to use before publishing.
- size: Size of the signal value when packed in the frame (bits).
- start_bit: Index of the first bit where this signal's data begins inside the frame.
- unit: Unit of the signal value.
- description: Description of the signal, taken from the signal database.
- multiplex: Multiplexing role of the signal, if any.
69@dataclass(frozen=True) 70class WriteSignal: 71 """ 72 A signal value to be published to the broker. 73 74 The write counterpart to `Signal`. Pass instances to `BrokerClient.publish()` 75 to set signal values on the bus. 76 77 Attributes: 78 name: The name of the signal to write. 79 value: The value to assign to the signal. 80 """ 81 82 name: SignalName 83 value: SignalValue 84 85 def __str__(self) -> str: 86 return f"{self.name}: {self.value!r}"
A signal value to be published to the broker.
The write counterpart to Signal. Pass instances to BrokerClient.publish()
to set signal values on the bus.
Attributes:
- name: The name of the signal to write.
- value: The value to assign to the signal.