remotivelabs.topology.namespaces.generic
1from __future__ import annotations 2 3from collections.abc import Awaitable, Callable, Sequence 4from contextlib import asynccontextmanager 5from dataclasses import dataclass, field 6from typing import AsyncGenerator, AsyncIterator 7 8from remotivelabs.broker import ( 9 BrokerClient, 10 Frame, 11 FrameInfo, 12 FrameName, 13 FrameSubscription, 14 NamespaceInfo, 15 NamespaceName, 16 RestbusFrameConfig, 17 RestbusSignalConfig, 18 Signal, 19 SignalInfo, 20 SignalName, 21 SignalValue, 22 WriteSignal, 23) 24from remotivelabs.broker.filters import FilterLike, is_frame_filter 25from typing_extensions import Self 26 27from remotivelabs.topology.namespaces.input_handlers import FrameHandler, InputHandler, InputHandlerSpec 28from remotivelabs.topology.namespaces.namespace import Namespace 29 30__all__ = ["GenericNamespace", "InputHandlerSpec", "Restbus", "RestbusConfig", "TransactionContext"] 31 32 33class GenericNamespace(Namespace[FilterLike, Callable[[Frame], Awaitable[None]]]): 34 """ 35 GenericNamespace provides access to frames and signals in a specific namespace using a broker client. 36 37 This class also manages restbus configurations which enable frame publishing based on filters. 38 To load restbus configuration and activate the restbus, use this class as an async context manager. 39 """ 40 41 def __init__( 42 self, 43 name: NamespaceName, 44 broker_client: BrokerClient, 45 restbus_configs: list[RestbusConfig] | None = None, 46 decode_named_values: bool = False, 47 input_handlers: list[InputHandlerSpec] | None = None, 48 ): 49 """ 50 Initialize the generic namespace client. 51 52 Args: 53 name: The namespace name to operate in. 54 broker_client: The client used to communicate with the broker. 55 restbus_configs: Optional list of configurations with filters for the restbus. 56 Applied in order; if multiple filters match the same frame, the last matching configuration takes precedence. 57 decode_named_values: True will decode named values to str. 58 input_handlers: Optional list of `(filters, callback)` pairs registered on `open()`. 59 60 Note: 61 Use together with a `BehavioralModel` or start the instance using a context manager: 62 ```python 63 async with GenericNamespace(...) as broker_client: 64 ... 65 ``` 66 """ 67 super().__init__(name=name, broker_client=broker_client) 68 self._restbus = Restbus(namespace=name, broker_client=broker_client, restbus_configs=restbus_configs or []) 69 self._decode_named_values = decode_named_values 70 self._input_handlers: list[InputHandlerSpec] = input_handlers or [] 71 72 @property 73 def restbus(self) -> Restbus: 74 """ 75 Property to interact with the restbus. 76 The restbus manages periodic publishing of frames and signals. 77 """ 78 return self._restbus 79 80 async def _on_open(self, info: NamespaceInfo) -> None: # noqa: ARG002 81 await self.restbus.open() 82 for filters, callback in self._input_handlers: 83 await self.subscribe_input_handler(filters, callback) 84 85 async def _on_close(self) -> None: 86 await self.restbus.close() 87 88 async def subscribe_input_handler( 89 self, 90 filters: Sequence[FilterLike], 91 callback: Callable[[Frame], Awaitable[None]], 92 ) -> str: 93 """ 94 Register an input handler on the namespace to receive frames matching the given filters. 95 96 Uses the same `FrameHandler` pipeline as `BehavioralModel.input_handlers`, so frame filters, 97 signal filters, and named-value decoding behave identically. Unlike `create_input_handler`, 98 this registers directly on the namespace and does not require a `BehavioralModel`. 99 Use `unsubscribe_input_handler` to remove it. 100 101 Args: 102 filters: Filters to select frames and/or signals. 103 callback: Async function called with each matching `Frame`. 104 105 Returns: 106 A subscription ID to pass to `unsubscribe_input_handler`. 107 108 Raises: 109 ValueError: If the filters do not match any frames in the namespace. 110 """ 111 handler = FrameHandler(filters=filters, cb=callback, decode_named_values=self._decode_named_values) 112 for fi in await self._broker_client.list_frame_infos(self.name): 113 handler.add(fi) 114 subs = handler.subscriptions() 115 if not subs: 116 raise ValueError(f"Input handler filters {list(filters)} did not match any frames on namespace '{self.name}'") 117 118 return await self._subscribe(subs, handler.handle, decode_named_values=False) 119 120 async def unsubscribe_input_handler(self, subscription_id: str) -> None: 121 """ 122 Cancel an input handler registered via `subscribe_input_handler`. 123 124 Args: 125 subscription_id: The ID returned by `subscribe_input_handler`. 126 """ 127 await self._unsubscribe(subscription_id) 128 129 async def list_frame_infos(self) -> list[FrameInfo]: 130 """Return all available frame infos in the namespace.""" 131 return await self._broker_client.list_frame_infos(self.name) 132 133 async def get_frame_info(self, name: str) -> FrameInfo | None: 134 """Return information about a specific frame by name.""" 135 return await self._broker_client.get_frame_info(name, namespace=self.name) 136 137 async def list_signal_infos(self) -> list[SignalInfo]: 138 """Return all available signal infos in the namespace.""" 139 return await self._broker_client.list_signal_infos(self.name) 140 141 async def get_signal_info(self, name: SignalName) -> SignalInfo | None: 142 """Return information about a specific signal by name.""" 143 return await self._broker_client.get_signal_info(name, namespace=self.name) 144 145 async def publish(self, *signals: WriteSignal | tuple[SignalName, SignalValue]) -> None: 146 """ 147 Publish one or more signals to the broker. 148 149 Args: 150 *signals: One or more WriteSignal instances or (signal_name, value) tuples to publish. 151 """ 152 remapped = [WriteSignal(name=s[0], value=s[1]) if isinstance(s, tuple) else s for s in signals] 153 await self._broker_client.publish((self._namespace, remapped)) 154 155 async def subscribe(self, *name: SignalName, on_change: bool = False) -> AsyncIterator[list[Signal]]: 156 """ 157 Subscribe to a list of signals. 158 159 Args: 160 *name: One or more signal names to subscribe to. 161 on_change: Whether to receive updates only on change. 162 163 Note: does not support decoding enums 164 165 Returns: 166 An asynchronous iterator of lists of Signal objects. 167 """ 168 return await self._broker_client.subscribe((self.name, list(name)), on_change=on_change, initial_empty=True) 169 170 async def subscribe_frames( 171 self, 172 *frames: FrameSubscription, 173 on_change: bool = False, 174 initial_empty: bool = True, 175 decode_named_values: bool | None = None, 176 ) -> AsyncIterator[Frame]: 177 """ 178 Subscribe to a Frames. 179 180 Args: 181 *frames: One or more frames to subscribe to. 182 on_change: Whether to receive updates only on change. 183 initial_empty: If `True`, the first broker message (an empty sync marker) is 184 consumed internally before the iterator is returned, ensuring the broker is 185 ready before the first real value arrives. Useful when you need to guarantee 186 the subscription is live before publishing something. 187 decode_named_values: True will decode named values to str. Defaults to the value 188 set in the constructor. 189 190 Returns: 191 An asynchronous iterator with Frames. 192 """ 193 decode_values = self._decode_named_values if decode_named_values is None else decode_named_values 194 return await self._broker_client.subscribe_frames( 195 (self.name, list(frames)), on_change=on_change, initial_empty=initial_empty, decode_named_values=decode_values 196 ) 197 198 def create_input_handler( 199 self, 200 filters: Sequence[FilterLike], 201 callback: Callable[[Frame], Awaitable[None]], 202 ) -> tuple[NamespaceName, InputHandler]: 203 """ 204 Create an input handler for this namespace to be used with a `BehavioralModel`. 205 206 Args: 207 filters: A sequence of filter objects to select relevant frames or signals. 208 callback: An async callback invoked with each matching `Frame`. 209 210 Returns: 211 A `(namespace_name, handler)` pair ready to pass to `BehavioralModel`. 212 """ 213 return (self.name, FrameHandler(filters=filters, cb=callback, decode_named_values=self._decode_named_values)) 214 215 216@dataclass 217class RestbusConfig: 218 """ 219 Configuration for the Restbus 220 221 Attributes: 222 restbus_filters: List of filters used to select frames; matching frames will be configured and managed by the restbus. 223 delay_multiplier: Multiplier for applying artificial delays; default is 1 (no delay). 224 cycle_time_millis: Optional fixed cycle time in milliseconds for publishing. 225 By default the cycle time from the signal database is used. 226 """ 227 228 restbus_filters: list[FilterLike] 229 delay_multiplier: float = 1 230 cycle_time_millis: float | None = None 231 232 233class Restbus: 234 """ 235 Restbus provides a way to publish frames according to their cycle time. 236 Sending recurring frames is common with for example CAN or LIN. Notice that each Namespace has its own Restbus. 237 It allows configuring frame publishing behavior, applying filters, and controlling the restbus lifecycle. 238 239 Also notice that new frames can be added or removed in order to emulate how different 240 frames are sent depending on the state of the model. 241 242 The broker runs one restbus per namespace, shared by every client using that namespace. Each `Restbus` 243 keeps track of the frames it added and only removes those on `close` and resets those on `reset`. Frames 244 are keyed by name, so if two clients add the same frame, removing or resetting it affects both. 245 246 Usage: 247 Should be used with through a `Namespace` implementation such as `GenericNamespace`, but can be used standalone. 248 249 ```python 250 async with Restbus(namespace, broker_client, restbus_configs) as restbus: 251 await restbus.start() 252 ``` 253 Args: 254 namespace: The namespace to operate in. 255 broker_client: The broker client to communicate with. 256 restbus_configs: Optional list of configurations with filters for the restbus. 257 Applied in order; if multiple filters match the same frame, the last matching configuration takes precedence. 258 """ 259 260 def __init__(self, namespace: NamespaceName, broker_client: BrokerClient, restbus_configs: list[RestbusConfig] | None = None): 261 self._namespace = namespace 262 self._broker_client = broker_client 263 self._restbus_configs = restbus_configs or [] 264 self._is_open = False 265 self._frames: set[FrameName] = set() 266 267 async def open(self) -> Self: 268 """ 269 Open the restbus and initialize it with configured frames. 270 This is an idempotent operation - calling it multiple times has no additional effect. 271 """ 272 if self._is_open: 273 return self 274 275 frame_infos = await self._broker_client.list_frame_infos(self._namespace) 276 frames: dict[FrameName, RestbusFrameConfig] = {} 277 for config in self._restbus_configs: 278 matched_filters: set[FilterLike] = set() 279 for frame_info in frame_infos: 280 for filter in config.restbus_filters: 281 if is_frame_filter(filter) and filter(frame_info): 282 matched_filters.add(filter) 283 cycle_time = (config.cycle_time_millis or frame_info.cycle_time_millis) * config.delay_multiplier 284 if cycle_time: 285 frame_config = RestbusFrameConfig(name=frame_info.name, cycle_time=cycle_time) 286 frames[frame_info.name] = frame_config 287 for filter in config.restbus_filters: 288 if filter not in matched_filters: 289 raise ValueError(f"Filter {filter} did not match any frames") 290 291 if frames: 292 await self.add(*frames.values()) 293 294 self._is_open = True 295 return self 296 297 async def close(self) -> None: 298 """ 299 Close the restbus by removing the frames this instance added, whether from `restbus_configs` or `add`. 300 Frames added by other clients on the same namespace keep running, and the namespace's running state 301 is left as it is. 302 This is an idempotent operation - calling it multiple times has no additional effect. 303 """ 304 if self._frames: 305 await self._broker_client.restbus.remove((self._namespace, sorted(self._frames))) 306 self._frames.clear() 307 self._is_open = False 308 309 async def __aenter__(self) -> Self: 310 return await self.open() 311 312 async def __aexit__(self, exc_type, exc_value, traceback) -> None: 313 await self.close() 314 315 async def add(self, *frame_configs: RestbusFrameConfig, start: bool = False): 316 """ 317 Add frames by configuration to the restbus. 318 319 Args: 320 *frame_configs: One or more frame configurations 321 start: Whether to start the restbus publishing immediately. 322 Note: this flag controls a global state for the entire restbus, not individual frames. 323 """ 324 await self._broker_client.restbus.add((self._namespace, list(frame_configs)), start=start) 325 self._frames.update(fc.name for fc in frame_configs) 326 327 async def start(self): 328 """Start restbus publishing for this namespace.""" 329 await self._broker_client.restbus.start(self._namespace) 330 331 async def stop(self): 332 """ 333 Stop restbus publishing for this namespace. 334 Note: this stops the entire namespace, including frames added by other clients. 335 """ 336 await self._broker_client.restbus.stop(self._namespace) 337 338 async def remove(self, *frames: FrameName): 339 """ 340 Remove frames from the restbus. 341 342 Args: 343 *frames: One or more frame names to remove 344 """ 345 await self._broker_client.restbus.remove((self._namespace, list(frames))) 346 self._frames.difference_update(frames) 347 348 async def update_signals(self, *signal_configs: RestbusSignalConfig | tuple[SignalName, SignalValue]) -> None: 349 """ 350 Update signal configurations for the restbus. 351 352 Args: 353 *signal_configs: Signal configurations to update, or a tuple of signal name and value. 354 """ 355 remapped_configs = [RestbusSignalConfig.set(sc[0], sc[1]) if isinstance(sc, tuple) else sc for sc in signal_configs] 356 await self._broker_client.restbus.update_signals((self._namespace, list(remapped_configs))) 357 358 async def reset_signals(self, *signals: SignalName) -> None: 359 """ 360 Reset specified signals in the restbus to their original values. 361 362 Args: 363 *signals: Signal names to reset. 364 """ 365 await self._broker_client.restbus.reset_signals((self._namespace, list(signals))) 366 367 async def reset(self) -> None: 368 """ 369 Reset all signals of the frames this instance added to their default values. 370 Frames added by other clients on the same namespace are left as they are. 371 """ 372 if not self._frames: 373 return 374 frame_infos = await self._broker_client.list_frame_infos(self._namespace) 375 signals = [signal for fi in frame_infos if fi.name in self._frames for signal in fi.signals] 376 if signals: 377 await self.reset_signals(*signals) 378 379 @asynccontextmanager 380 async def transaction(self) -> AsyncGenerator[TransactionContext, None]: 381 """ 382 Context manager for batching signal updates and resets. 383 384 Usage: 385 ```python 386 async with restbus.transaction() as tx: 387 tx.updates.append(...) 388 tx.resets.append(...) 389 ``` 390 """ 391 tc = TransactionContext() 392 yield tc 393 if len(tc.resets) > 0: 394 await self.reset_signals(*tc.resets) 395 if len(tc.updates) > 0: 396 await self.update_signals(*tc.updates) 397 398 399@dataclass 400class TransactionContext: 401 """Accumulates signal updates and resets to be applied atomically via `Restbus.transaction()`.""" 402 403 updates: list[RestbusSignalConfig | tuple[SignalName, SignalValue]] = field(default_factory=list) 404 resets: list[FrameName] = field(default_factory=list) 405 406 def update(self, *signal_config: RestbusSignalConfig | tuple[SignalName, SignalValue]) -> None: 407 """ 408 Queue one or more signal value updates. 409 410 The tuple shorthand ``(name, value)`` is equivalent to ``RestbusSignalConfig.set(name, value)`` 411 and sets a constant value. For more advanced use cases, pass a ``RestbusSignalConfig`` directly: 412 413 - Cycle through a sequence of values: ``RestbusSignalConfig(name, loop=[v1, v2, ...])`` 414 - Emit initial values before the loop: ``RestbusSignalConfig(name, loop=[...], initial=[...])`` 415 - Update-bit pattern (pulse once then hold 0): ``RestbusSignalConfig.set_update_bit(name)`` 416 """ 417 remapped_configs = [RestbusSignalConfig.set(sc[0], sc[1]) if isinstance(sc, tuple) else sc for sc in signal_config] 418 self.updates.extend(remapped_configs) 419 420 def set_update_bit(self, *signals: SignalName) -> None: 421 """Queue an update-bit set for one or more signals.""" 422 self.updates.extend([RestbusSignalConfig.set_update_bit(name) for name in signals]) 423 424 def reset_signal(self, *signals: SignalName) -> None: 425 """Queue one or more signals to be reset to their database default values.""" 426 self.resets.extend(signals)
34class GenericNamespace(Namespace[FilterLike, Callable[[Frame], Awaitable[None]]]): 35 """ 36 GenericNamespace provides access to frames and signals in a specific namespace using a broker client. 37 38 This class also manages restbus configurations which enable frame publishing based on filters. 39 To load restbus configuration and activate the restbus, use this class as an async context manager. 40 """ 41 42 def __init__( 43 self, 44 name: NamespaceName, 45 broker_client: BrokerClient, 46 restbus_configs: list[RestbusConfig] | None = None, 47 decode_named_values: bool = False, 48 input_handlers: list[InputHandlerSpec] | None = None, 49 ): 50 """ 51 Initialize the generic namespace client. 52 53 Args: 54 name: The namespace name to operate in. 55 broker_client: The client used to communicate with the broker. 56 restbus_configs: Optional list of configurations with filters for the restbus. 57 Applied in order; if multiple filters match the same frame, the last matching configuration takes precedence. 58 decode_named_values: True will decode named values to str. 59 input_handlers: Optional list of `(filters, callback)` pairs registered on `open()`. 60 61 Note: 62 Use together with a `BehavioralModel` or start the instance using a context manager: 63 ```python 64 async with GenericNamespace(...) as broker_client: 65 ... 66 ``` 67 """ 68 super().__init__(name=name, broker_client=broker_client) 69 self._restbus = Restbus(namespace=name, broker_client=broker_client, restbus_configs=restbus_configs or []) 70 self._decode_named_values = decode_named_values 71 self._input_handlers: list[InputHandlerSpec] = input_handlers or [] 72 73 @property 74 def restbus(self) -> Restbus: 75 """ 76 Property to interact with the restbus. 77 The restbus manages periodic publishing of frames and signals. 78 """ 79 return self._restbus 80 81 async def _on_open(self, info: NamespaceInfo) -> None: # noqa: ARG002 82 await self.restbus.open() 83 for filters, callback in self._input_handlers: 84 await self.subscribe_input_handler(filters, callback) 85 86 async def _on_close(self) -> None: 87 await self.restbus.close() 88 89 async def subscribe_input_handler( 90 self, 91 filters: Sequence[FilterLike], 92 callback: Callable[[Frame], Awaitable[None]], 93 ) -> str: 94 """ 95 Register an input handler on the namespace to receive frames matching the given filters. 96 97 Uses the same `FrameHandler` pipeline as `BehavioralModel.input_handlers`, so frame filters, 98 signal filters, and named-value decoding behave identically. Unlike `create_input_handler`, 99 this registers directly on the namespace and does not require a `BehavioralModel`. 100 Use `unsubscribe_input_handler` to remove it. 101 102 Args: 103 filters: Filters to select frames and/or signals. 104 callback: Async function called with each matching `Frame`. 105 106 Returns: 107 A subscription ID to pass to `unsubscribe_input_handler`. 108 109 Raises: 110 ValueError: If the filters do not match any frames in the namespace. 111 """ 112 handler = FrameHandler(filters=filters, cb=callback, decode_named_values=self._decode_named_values) 113 for fi in await self._broker_client.list_frame_infos(self.name): 114 handler.add(fi) 115 subs = handler.subscriptions() 116 if not subs: 117 raise ValueError(f"Input handler filters {list(filters)} did not match any frames on namespace '{self.name}'") 118 119 return await self._subscribe(subs, handler.handle, decode_named_values=False) 120 121 async def unsubscribe_input_handler(self, subscription_id: str) -> None: 122 """ 123 Cancel an input handler registered via `subscribe_input_handler`. 124 125 Args: 126 subscription_id: The ID returned by `subscribe_input_handler`. 127 """ 128 await self._unsubscribe(subscription_id) 129 130 async def list_frame_infos(self) -> list[FrameInfo]: 131 """Return all available frame infos in the namespace.""" 132 return await self._broker_client.list_frame_infos(self.name) 133 134 async def get_frame_info(self, name: str) -> FrameInfo | None: 135 """Return information about a specific frame by name.""" 136 return await self._broker_client.get_frame_info(name, namespace=self.name) 137 138 async def list_signal_infos(self) -> list[SignalInfo]: 139 """Return all available signal infos in the namespace.""" 140 return await self._broker_client.list_signal_infos(self.name) 141 142 async def get_signal_info(self, name: SignalName) -> SignalInfo | None: 143 """Return information about a specific signal by name.""" 144 return await self._broker_client.get_signal_info(name, namespace=self.name) 145 146 async def publish(self, *signals: WriteSignal | tuple[SignalName, SignalValue]) -> None: 147 """ 148 Publish one or more signals to the broker. 149 150 Args: 151 *signals: One or more WriteSignal instances or (signal_name, value) tuples to publish. 152 """ 153 remapped = [WriteSignal(name=s[0], value=s[1]) if isinstance(s, tuple) else s for s in signals] 154 await self._broker_client.publish((self._namespace, remapped)) 155 156 async def subscribe(self, *name: SignalName, on_change: bool = False) -> AsyncIterator[list[Signal]]: 157 """ 158 Subscribe to a list of signals. 159 160 Args: 161 *name: One or more signal names to subscribe to. 162 on_change: Whether to receive updates only on change. 163 164 Note: does not support decoding enums 165 166 Returns: 167 An asynchronous iterator of lists of Signal objects. 168 """ 169 return await self._broker_client.subscribe((self.name, list(name)), on_change=on_change, initial_empty=True) 170 171 async def subscribe_frames( 172 self, 173 *frames: FrameSubscription, 174 on_change: bool = False, 175 initial_empty: bool = True, 176 decode_named_values: bool | None = None, 177 ) -> AsyncIterator[Frame]: 178 """ 179 Subscribe to a Frames. 180 181 Args: 182 *frames: One or more frames to subscribe to. 183 on_change: Whether to receive updates only on change. 184 initial_empty: If `True`, the first broker message (an empty sync marker) is 185 consumed internally before the iterator is returned, ensuring the broker is 186 ready before the first real value arrives. Useful when you need to guarantee 187 the subscription is live before publishing something. 188 decode_named_values: True will decode named values to str. Defaults to the value 189 set in the constructor. 190 191 Returns: 192 An asynchronous iterator with Frames. 193 """ 194 decode_values = self._decode_named_values if decode_named_values is None else decode_named_values 195 return await self._broker_client.subscribe_frames( 196 (self.name, list(frames)), on_change=on_change, initial_empty=initial_empty, decode_named_values=decode_values 197 ) 198 199 def create_input_handler( 200 self, 201 filters: Sequence[FilterLike], 202 callback: Callable[[Frame], Awaitable[None]], 203 ) -> tuple[NamespaceName, InputHandler]: 204 """ 205 Create an input handler for this namespace to be used with a `BehavioralModel`. 206 207 Args: 208 filters: A sequence of filter objects to select relevant frames or signals. 209 callback: An async callback invoked with each matching `Frame`. 210 211 Returns: 212 A `(namespace_name, handler)` pair ready to pass to `BehavioralModel`. 213 """ 214 return (self.name, FrameHandler(filters=filters, cb=callback, decode_named_values=self._decode_named_values))
GenericNamespace provides access to frames and signals in a specific namespace using a broker client.
This class also manages restbus configurations which enable frame publishing based on filters. To load restbus configuration and activate the restbus, use this class as an async context manager.
42 def __init__( 43 self, 44 name: NamespaceName, 45 broker_client: BrokerClient, 46 restbus_configs: list[RestbusConfig] | None = None, 47 decode_named_values: bool = False, 48 input_handlers: list[InputHandlerSpec] | None = None, 49 ): 50 """ 51 Initialize the generic namespace client. 52 53 Args: 54 name: The namespace name to operate in. 55 broker_client: The client used to communicate with the broker. 56 restbus_configs: Optional list of configurations with filters for the restbus. 57 Applied in order; if multiple filters match the same frame, the last matching configuration takes precedence. 58 decode_named_values: True will decode named values to str. 59 input_handlers: Optional list of `(filters, callback)` pairs registered on `open()`. 60 61 Note: 62 Use together with a `BehavioralModel` or start the instance using a context manager: 63 ```python 64 async with GenericNamespace(...) as broker_client: 65 ... 66 ``` 67 """ 68 super().__init__(name=name, broker_client=broker_client) 69 self._restbus = Restbus(namespace=name, broker_client=broker_client, restbus_configs=restbus_configs or []) 70 self._decode_named_values = decode_named_values 71 self._input_handlers: list[InputHandlerSpec] = input_handlers or []
Initialize the generic namespace client.
Arguments:
- name: The namespace name to operate in.
- broker_client: The client used to communicate with the broker.
- restbus_configs: Optional list of configurations with filters for the restbus. Applied in order; if multiple filters match the same frame, the last matching configuration takes precedence.
- decode_named_values: True will decode named values to str.
- input_handlers: Optional list of
(filters, callback)pairs registered onopen().
Note:
Use together with a
BehavioralModelor start the instance using a context manager:async with GenericNamespace(...) as broker_client: ...
73 @property 74 def restbus(self) -> Restbus: 75 """ 76 Property to interact with the restbus. 77 The restbus manages periodic publishing of frames and signals. 78 """ 79 return self._restbus
Property to interact with the restbus. The restbus manages periodic publishing of frames and signals.
89 async def subscribe_input_handler( 90 self, 91 filters: Sequence[FilterLike], 92 callback: Callable[[Frame], Awaitable[None]], 93 ) -> str: 94 """ 95 Register an input handler on the namespace to receive frames matching the given filters. 96 97 Uses the same `FrameHandler` pipeline as `BehavioralModel.input_handlers`, so frame filters, 98 signal filters, and named-value decoding behave identically. Unlike `create_input_handler`, 99 this registers directly on the namespace and does not require a `BehavioralModel`. 100 Use `unsubscribe_input_handler` to remove it. 101 102 Args: 103 filters: Filters to select frames and/or signals. 104 callback: Async function called with each matching `Frame`. 105 106 Returns: 107 A subscription ID to pass to `unsubscribe_input_handler`. 108 109 Raises: 110 ValueError: If the filters do not match any frames in the namespace. 111 """ 112 handler = FrameHandler(filters=filters, cb=callback, decode_named_values=self._decode_named_values) 113 for fi in await self._broker_client.list_frame_infos(self.name): 114 handler.add(fi) 115 subs = handler.subscriptions() 116 if not subs: 117 raise ValueError(f"Input handler filters {list(filters)} did not match any frames on namespace '{self.name}'") 118 119 return await self._subscribe(subs, handler.handle, decode_named_values=False)
Register an input handler on the namespace to receive frames matching the given filters.
Uses the same FrameHandler pipeline as BehavioralModel.input_handlers, so frame filters,
signal filters, and named-value decoding behave identically. Unlike create_input_handler,
this registers directly on the namespace and does not require a BehavioralModel.
Use unsubscribe_input_handler to remove it.
Arguments:
- filters: Filters to select frames and/or signals.
- callback: Async function called with each matching
Frame.
Returns:
A subscription ID to pass to
unsubscribe_input_handler.
Raises:
- ValueError: If the filters do not match any frames in the namespace.
121 async def unsubscribe_input_handler(self, subscription_id: str) -> None: 122 """ 123 Cancel an input handler registered via `subscribe_input_handler`. 124 125 Args: 126 subscription_id: The ID returned by `subscribe_input_handler`. 127 """ 128 await self._unsubscribe(subscription_id)
Cancel an input handler registered via subscribe_input_handler.
Arguments:
- subscription_id: The ID returned by
subscribe_input_handler.
130 async def list_frame_infos(self) -> list[FrameInfo]: 131 """Return all available frame infos in the namespace.""" 132 return await self._broker_client.list_frame_infos(self.name)
Return all available frame infos in the namespace.
134 async def get_frame_info(self, name: str) -> FrameInfo | None: 135 """Return information about a specific frame by name.""" 136 return await self._broker_client.get_frame_info(name, namespace=self.name)
Return information about a specific frame by name.
138 async def list_signal_infos(self) -> list[SignalInfo]: 139 """Return all available signal infos in the namespace.""" 140 return await self._broker_client.list_signal_infos(self.name)
Return all available signal infos in the namespace.
142 async def get_signal_info(self, name: SignalName) -> SignalInfo | None: 143 """Return information about a specific signal by name.""" 144 return await self._broker_client.get_signal_info(name, namespace=self.name)
Return information about a specific signal by name.
146 async def publish(self, *signals: WriteSignal | tuple[SignalName, SignalValue]) -> None: 147 """ 148 Publish one or more signals to the broker. 149 150 Args: 151 *signals: One or more WriteSignal instances or (signal_name, value) tuples to publish. 152 """ 153 remapped = [WriteSignal(name=s[0], value=s[1]) if isinstance(s, tuple) else s for s in signals] 154 await self._broker_client.publish((self._namespace, remapped))
Publish one or more signals to the broker.
Arguments:
- *signals: One or more WriteSignal instances or (signal_name, value) tuples to publish.
156 async def subscribe(self, *name: SignalName, on_change: bool = False) -> AsyncIterator[list[Signal]]: 157 """ 158 Subscribe to a list of signals. 159 160 Args: 161 *name: One or more signal names to subscribe to. 162 on_change: Whether to receive updates only on change. 163 164 Note: does not support decoding enums 165 166 Returns: 167 An asynchronous iterator of lists of Signal objects. 168 """ 169 return await self._broker_client.subscribe((self.name, list(name)), on_change=on_change, initial_empty=True)
Subscribe to a list of signals.
Arguments:
- *name: One or more signal names to subscribe to.
- on_change: Whether to receive updates only on change.
Note: does not support decoding enums
Returns:
An asynchronous iterator of lists of Signal objects.
171 async def subscribe_frames( 172 self, 173 *frames: FrameSubscription, 174 on_change: bool = False, 175 initial_empty: bool = True, 176 decode_named_values: bool | None = None, 177 ) -> AsyncIterator[Frame]: 178 """ 179 Subscribe to a Frames. 180 181 Args: 182 *frames: One or more frames to subscribe to. 183 on_change: Whether to receive updates only on change. 184 initial_empty: If `True`, the first broker message (an empty sync marker) is 185 consumed internally before the iterator is returned, ensuring the broker is 186 ready before the first real value arrives. Useful when you need to guarantee 187 the subscription is live before publishing something. 188 decode_named_values: True will decode named values to str. Defaults to the value 189 set in the constructor. 190 191 Returns: 192 An asynchronous iterator with Frames. 193 """ 194 decode_values = self._decode_named_values if decode_named_values is None else decode_named_values 195 return await self._broker_client.subscribe_frames( 196 (self.name, list(frames)), on_change=on_change, initial_empty=initial_empty, decode_named_values=decode_values 197 )
Subscribe to a Frames.
Arguments:
- *frames: One or more frames 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. - decode_named_values: True will decode named values to str. Defaults to the value set in the constructor.
Returns:
An asynchronous iterator with Frames.
199 def create_input_handler( 200 self, 201 filters: Sequence[FilterLike], 202 callback: Callable[[Frame], Awaitable[None]], 203 ) -> tuple[NamespaceName, InputHandler]: 204 """ 205 Create an input handler for this namespace to be used with a `BehavioralModel`. 206 207 Args: 208 filters: A sequence of filter objects to select relevant frames or signals. 209 callback: An async callback invoked with each matching `Frame`. 210 211 Returns: 212 A `(namespace_name, handler)` pair ready to pass to `BehavioralModel`. 213 """ 214 return (self.name, FrameHandler(filters=filters, cb=callback, decode_named_values=self._decode_named_values))
Create an input handler for this namespace to be used with a BehavioralModel.
Arguments:
- filters: A sequence of filter objects to select relevant frames or signals.
- callback: An async callback invoked with each matching
Frame.
Returns:
A
(namespace_name, handler)pair ready to pass toBehavioralModel.
234class Restbus: 235 """ 236 Restbus provides a way to publish frames according to their cycle time. 237 Sending recurring frames is common with for example CAN or LIN. Notice that each Namespace has its own Restbus. 238 It allows configuring frame publishing behavior, applying filters, and controlling the restbus lifecycle. 239 240 Also notice that new frames can be added or removed in order to emulate how different 241 frames are sent depending on the state of the model. 242 243 The broker runs one restbus per namespace, shared by every client using that namespace. Each `Restbus` 244 keeps track of the frames it added and only removes those on `close` and resets those on `reset`. Frames 245 are keyed by name, so if two clients add the same frame, removing or resetting it affects both. 246 247 Usage: 248 Should be used with through a `Namespace` implementation such as `GenericNamespace`, but can be used standalone. 249 250 ```python 251 async with Restbus(namespace, broker_client, restbus_configs) as restbus: 252 await restbus.start() 253 ``` 254 Args: 255 namespace: The namespace to operate in. 256 broker_client: The broker client to communicate with. 257 restbus_configs: Optional list of configurations with filters for the restbus. 258 Applied in order; if multiple filters match the same frame, the last matching configuration takes precedence. 259 """ 260 261 def __init__(self, namespace: NamespaceName, broker_client: BrokerClient, restbus_configs: list[RestbusConfig] | None = None): 262 self._namespace = namespace 263 self._broker_client = broker_client 264 self._restbus_configs = restbus_configs or [] 265 self._is_open = False 266 self._frames: set[FrameName] = set() 267 268 async def open(self) -> Self: 269 """ 270 Open the restbus and initialize it with configured frames. 271 This is an idempotent operation - calling it multiple times has no additional effect. 272 """ 273 if self._is_open: 274 return self 275 276 frame_infos = await self._broker_client.list_frame_infos(self._namespace) 277 frames: dict[FrameName, RestbusFrameConfig] = {} 278 for config in self._restbus_configs: 279 matched_filters: set[FilterLike] = set() 280 for frame_info in frame_infos: 281 for filter in config.restbus_filters: 282 if is_frame_filter(filter) and filter(frame_info): 283 matched_filters.add(filter) 284 cycle_time = (config.cycle_time_millis or frame_info.cycle_time_millis) * config.delay_multiplier 285 if cycle_time: 286 frame_config = RestbusFrameConfig(name=frame_info.name, cycle_time=cycle_time) 287 frames[frame_info.name] = frame_config 288 for filter in config.restbus_filters: 289 if filter not in matched_filters: 290 raise ValueError(f"Filter {filter} did not match any frames") 291 292 if frames: 293 await self.add(*frames.values()) 294 295 self._is_open = True 296 return self 297 298 async def close(self) -> None: 299 """ 300 Close the restbus by removing the frames this instance added, whether from `restbus_configs` or `add`. 301 Frames added by other clients on the same namespace keep running, and the namespace's running state 302 is left as it is. 303 This is an idempotent operation - calling it multiple times has no additional effect. 304 """ 305 if self._frames: 306 await self._broker_client.restbus.remove((self._namespace, sorted(self._frames))) 307 self._frames.clear() 308 self._is_open = False 309 310 async def __aenter__(self) -> Self: 311 return await self.open() 312 313 async def __aexit__(self, exc_type, exc_value, traceback) -> None: 314 await self.close() 315 316 async def add(self, *frame_configs: RestbusFrameConfig, start: bool = False): 317 """ 318 Add frames by configuration to the restbus. 319 320 Args: 321 *frame_configs: One or more frame configurations 322 start: Whether to start the restbus publishing immediately. 323 Note: this flag controls a global state for the entire restbus, not individual frames. 324 """ 325 await self._broker_client.restbus.add((self._namespace, list(frame_configs)), start=start) 326 self._frames.update(fc.name for fc in frame_configs) 327 328 async def start(self): 329 """Start restbus publishing for this namespace.""" 330 await self._broker_client.restbus.start(self._namespace) 331 332 async def stop(self): 333 """ 334 Stop restbus publishing for this namespace. 335 Note: this stops the entire namespace, including frames added by other clients. 336 """ 337 await self._broker_client.restbus.stop(self._namespace) 338 339 async def remove(self, *frames: FrameName): 340 """ 341 Remove frames from the restbus. 342 343 Args: 344 *frames: One or more frame names to remove 345 """ 346 await self._broker_client.restbus.remove((self._namespace, list(frames))) 347 self._frames.difference_update(frames) 348 349 async def update_signals(self, *signal_configs: RestbusSignalConfig | tuple[SignalName, SignalValue]) -> None: 350 """ 351 Update signal configurations for the restbus. 352 353 Args: 354 *signal_configs: Signal configurations to update, or a tuple of signal name and value. 355 """ 356 remapped_configs = [RestbusSignalConfig.set(sc[0], sc[1]) if isinstance(sc, tuple) else sc for sc in signal_configs] 357 await self._broker_client.restbus.update_signals((self._namespace, list(remapped_configs))) 358 359 async def reset_signals(self, *signals: SignalName) -> None: 360 """ 361 Reset specified signals in the restbus to their original values. 362 363 Args: 364 *signals: Signal names to reset. 365 """ 366 await self._broker_client.restbus.reset_signals((self._namespace, list(signals))) 367 368 async def reset(self) -> None: 369 """ 370 Reset all signals of the frames this instance added to their default values. 371 Frames added by other clients on the same namespace are left as they are. 372 """ 373 if not self._frames: 374 return 375 frame_infos = await self._broker_client.list_frame_infos(self._namespace) 376 signals = [signal for fi in frame_infos if fi.name in self._frames for signal in fi.signals] 377 if signals: 378 await self.reset_signals(*signals) 379 380 @asynccontextmanager 381 async def transaction(self) -> AsyncGenerator[TransactionContext, None]: 382 """ 383 Context manager for batching signal updates and resets. 384 385 Usage: 386 ```python 387 async with restbus.transaction() as tx: 388 tx.updates.append(...) 389 tx.resets.append(...) 390 ``` 391 """ 392 tc = TransactionContext() 393 yield tc 394 if len(tc.resets) > 0: 395 await self.reset_signals(*tc.resets) 396 if len(tc.updates) > 0: 397 await self.update_signals(*tc.updates)
Restbus provides a way to publish frames according to their cycle time. Sending recurring frames is common with for example CAN or LIN. Notice that each Namespace has its own Restbus. It allows configuring frame publishing behavior, applying filters, and controlling the restbus lifecycle.
Also notice that new frames can be added or removed in order to emulate how different frames are sent depending on the state of the model.
The broker runs one restbus per namespace, shared by every client using that namespace. Each Restbus
keeps track of the frames it added and only removes those on close and resets those on reset. Frames
are keyed by name, so if two clients add the same frame, removing or resetting it affects both.
Usage:
Should be used with through a
Namespaceimplementation such asGenericNamespace, but can be used standalone.async with Restbus(namespace, broker_client, restbus_configs) as restbus: await restbus.start()
Arguments:
- namespace: The namespace to operate in.
- broker_client: The broker client to communicate with.
- restbus_configs: Optional list of configurations with filters for the restbus. Applied in order; if multiple filters match the same frame, the last matching configuration takes precedence.
261 def __init__(self, namespace: NamespaceName, broker_client: BrokerClient, restbus_configs: list[RestbusConfig] | None = None): 262 self._namespace = namespace 263 self._broker_client = broker_client 264 self._restbus_configs = restbus_configs or [] 265 self._is_open = False 266 self._frames: set[FrameName] = set()
268 async def open(self) -> Self: 269 """ 270 Open the restbus and initialize it with configured frames. 271 This is an idempotent operation - calling it multiple times has no additional effect. 272 """ 273 if self._is_open: 274 return self 275 276 frame_infos = await self._broker_client.list_frame_infos(self._namespace) 277 frames: dict[FrameName, RestbusFrameConfig] = {} 278 for config in self._restbus_configs: 279 matched_filters: set[FilterLike] = set() 280 for frame_info in frame_infos: 281 for filter in config.restbus_filters: 282 if is_frame_filter(filter) and filter(frame_info): 283 matched_filters.add(filter) 284 cycle_time = (config.cycle_time_millis or frame_info.cycle_time_millis) * config.delay_multiplier 285 if cycle_time: 286 frame_config = RestbusFrameConfig(name=frame_info.name, cycle_time=cycle_time) 287 frames[frame_info.name] = frame_config 288 for filter in config.restbus_filters: 289 if filter not in matched_filters: 290 raise ValueError(f"Filter {filter} did not match any frames") 291 292 if frames: 293 await self.add(*frames.values()) 294 295 self._is_open = True 296 return self
Open the restbus and initialize it with configured frames. This is an idempotent operation - calling it multiple times has no additional effect.
298 async def close(self) -> None: 299 """ 300 Close the restbus by removing the frames this instance added, whether from `restbus_configs` or `add`. 301 Frames added by other clients on the same namespace keep running, and the namespace's running state 302 is left as it is. 303 This is an idempotent operation - calling it multiple times has no additional effect. 304 """ 305 if self._frames: 306 await self._broker_client.restbus.remove((self._namespace, sorted(self._frames))) 307 self._frames.clear() 308 self._is_open = False
Close the restbus by removing the frames this instance added, whether from restbus_configs or add.
Frames added by other clients on the same namespace keep running, and the namespace's running state
is left as it is.
This is an idempotent operation - calling it multiple times has no additional effect.
316 async def add(self, *frame_configs: RestbusFrameConfig, start: bool = False): 317 """ 318 Add frames by configuration to the restbus. 319 320 Args: 321 *frame_configs: One or more frame configurations 322 start: Whether to start the restbus publishing immediately. 323 Note: this flag controls a global state for the entire restbus, not individual frames. 324 """ 325 await self._broker_client.restbus.add((self._namespace, list(frame_configs)), start=start) 326 self._frames.update(fc.name for fc in frame_configs)
Add frames by configuration to the restbus.
Arguments:
- *frame_configs: One or more frame configurations
- start: Whether to start the restbus publishing immediately. Note: this flag controls a global state for the entire restbus, not individual frames.
328 async def start(self): 329 """Start restbus publishing for this namespace.""" 330 await self._broker_client.restbus.start(self._namespace)
Start restbus publishing for this namespace.
332 async def stop(self): 333 """ 334 Stop restbus publishing for this namespace. 335 Note: this stops the entire namespace, including frames added by other clients. 336 """ 337 await self._broker_client.restbus.stop(self._namespace)
Stop restbus publishing for this namespace. Note: this stops the entire namespace, including frames added by other clients.
339 async def remove(self, *frames: FrameName): 340 """ 341 Remove frames from the restbus. 342 343 Args: 344 *frames: One or more frame names to remove 345 """ 346 await self._broker_client.restbus.remove((self._namespace, list(frames))) 347 self._frames.difference_update(frames)
Remove frames from the restbus.
Arguments:
- *frames: One or more frame names to remove
349 async def update_signals(self, *signal_configs: RestbusSignalConfig | tuple[SignalName, SignalValue]) -> None: 350 """ 351 Update signal configurations for the restbus. 352 353 Args: 354 *signal_configs: Signal configurations to update, or a tuple of signal name and value. 355 """ 356 remapped_configs = [RestbusSignalConfig.set(sc[0], sc[1]) if isinstance(sc, tuple) else sc for sc in signal_configs] 357 await self._broker_client.restbus.update_signals((self._namespace, list(remapped_configs)))
Update signal configurations for the restbus.
Arguments:
- *signal_configs: Signal configurations to update, or a tuple of signal name and value.
359 async def reset_signals(self, *signals: SignalName) -> None: 360 """ 361 Reset specified signals in the restbus to their original values. 362 363 Args: 364 *signals: Signal names to reset. 365 """ 366 await self._broker_client.restbus.reset_signals((self._namespace, list(signals)))
Reset specified signals in the restbus to their original values.
Arguments:
- *signals: Signal names to reset.
368 async def reset(self) -> None: 369 """ 370 Reset all signals of the frames this instance added to their default values. 371 Frames added by other clients on the same namespace are left as they are. 372 """ 373 if not self._frames: 374 return 375 frame_infos = await self._broker_client.list_frame_infos(self._namespace) 376 signals = [signal for fi in frame_infos if fi.name in self._frames for signal in fi.signals] 377 if signals: 378 await self.reset_signals(*signals)
Reset all signals of the frames this instance added to their default values. Frames added by other clients on the same namespace are left as they are.
380 @asynccontextmanager 381 async def transaction(self) -> AsyncGenerator[TransactionContext, None]: 382 """ 383 Context manager for batching signal updates and resets. 384 385 Usage: 386 ```python 387 async with restbus.transaction() as tx: 388 tx.updates.append(...) 389 tx.resets.append(...) 390 ``` 391 """ 392 tc = TransactionContext() 393 yield tc 394 if len(tc.resets) > 0: 395 await self.reset_signals(*tc.resets) 396 if len(tc.updates) > 0: 397 await self.update_signals(*tc.updates)
Context manager for batching signal updates and resets.
Usage:
async with restbus.transaction() as tx: tx.updates.append(...) tx.resets.append(...)
217@dataclass 218class RestbusConfig: 219 """ 220 Configuration for the Restbus 221 222 Attributes: 223 restbus_filters: List of filters used to select frames; matching frames will be configured and managed by the restbus. 224 delay_multiplier: Multiplier for applying artificial delays; default is 1 (no delay). 225 cycle_time_millis: Optional fixed cycle time in milliseconds for publishing. 226 By default the cycle time from the signal database is used. 227 """ 228 229 restbus_filters: list[FilterLike] 230 delay_multiplier: float = 1 231 cycle_time_millis: float | None = None
Configuration for the Restbus
Attributes:
- restbus_filters: List of filters used to select frames; matching frames will be configured and managed by the restbus.
- delay_multiplier: Multiplier for applying artificial delays; default is 1 (no delay).
- cycle_time_millis: Optional fixed cycle time in milliseconds for publishing. By default the cycle time from the signal database is used.
400@dataclass 401class TransactionContext: 402 """Accumulates signal updates and resets to be applied atomically via `Restbus.transaction()`.""" 403 404 updates: list[RestbusSignalConfig | tuple[SignalName, SignalValue]] = field(default_factory=list) 405 resets: list[FrameName] = field(default_factory=list) 406 407 def update(self, *signal_config: RestbusSignalConfig | tuple[SignalName, SignalValue]) -> None: 408 """ 409 Queue one or more signal value updates. 410 411 The tuple shorthand ``(name, value)`` is equivalent to ``RestbusSignalConfig.set(name, value)`` 412 and sets a constant value. For more advanced use cases, pass a ``RestbusSignalConfig`` directly: 413 414 - Cycle through a sequence of values: ``RestbusSignalConfig(name, loop=[v1, v2, ...])`` 415 - Emit initial values before the loop: ``RestbusSignalConfig(name, loop=[...], initial=[...])`` 416 - Update-bit pattern (pulse once then hold 0): ``RestbusSignalConfig.set_update_bit(name)`` 417 """ 418 remapped_configs = [RestbusSignalConfig.set(sc[0], sc[1]) if isinstance(sc, tuple) else sc for sc in signal_config] 419 self.updates.extend(remapped_configs) 420 421 def set_update_bit(self, *signals: SignalName) -> None: 422 """Queue an update-bit set for one or more signals.""" 423 self.updates.extend([RestbusSignalConfig.set_update_bit(name) for name in signals]) 424 425 def reset_signal(self, *signals: SignalName) -> None: 426 """Queue one or more signals to be reset to their database default values.""" 427 self.resets.extend(signals)
Accumulates signal updates and resets to be applied atomically via Restbus.transaction().
407 def update(self, *signal_config: RestbusSignalConfig | tuple[SignalName, SignalValue]) -> None: 408 """ 409 Queue one or more signal value updates. 410 411 The tuple shorthand ``(name, value)`` is equivalent to ``RestbusSignalConfig.set(name, value)`` 412 and sets a constant value. For more advanced use cases, pass a ``RestbusSignalConfig`` directly: 413 414 - Cycle through a sequence of values: ``RestbusSignalConfig(name, loop=[v1, v2, ...])`` 415 - Emit initial values before the loop: ``RestbusSignalConfig(name, loop=[...], initial=[...])`` 416 - Update-bit pattern (pulse once then hold 0): ``RestbusSignalConfig.set_update_bit(name)`` 417 """ 418 remapped_configs = [RestbusSignalConfig.set(sc[0], sc[1]) if isinstance(sc, tuple) else sc for sc in signal_config] 419 self.updates.extend(remapped_configs)
Queue one or more signal value updates.
The tuple shorthand (name, value) is equivalent to RestbusSignalConfig.set(name, value)
and sets a constant value. For more advanced use cases, pass a RestbusSignalConfig directly:
- Cycle through a sequence of values:
RestbusSignalConfig(name, loop=[v1, v2, ...]) - Emit initial values before the loop:
RestbusSignalConfig(name, loop=[...], initial=[...]) - Update-bit pattern (pulse once then hold 0):
RestbusSignalConfig.set_update_bit(name)
421 def set_update_bit(self, *signals: SignalName) -> None: 422 """Queue an update-bit set for one or more signals.""" 423 self.updates.extend([RestbusSignalConfig.set_update_bit(name) for name in signals])
Queue an update-bit set for one or more signals.