remotivelabs.topology.namespaces.namespace
1from __future__ import annotations 2 3from abc import ABC 4from typing import Awaitable, Callable, Generic, TypeVar 5 6from remotivelabs.broker import BrokerClient, Frame, FrameSubscription, NamespaceInfo, NamespaceName, OnChangeMode, SecocProperty 7from remotivelabs.broker.filters import FilterLike 8from typing_extensions import Self 9 10from remotivelabs.topology.namespaces.monitor import SubscriptionMonitor 11 12F = TypeVar("F", bound=FilterLike) 13C = TypeVar("C", bound=Callable[..., Awaitable[object]]) 14 15 16class Namespace(ABC, Generic[F, C]): 17 """ 18 Base class for protocol-specific namespaces. 19 20 A namespace maps to a single namespace on a RemotiveBroker and provides the 21 lifecycle (`open`/`close`) and callback subscription plumbing shared by all 22 protocols. Subclasses add protocol-specific behavior (e.g., restbus, SOME/IP 23 requests, CAN/LIN framing) by overriding the `_on_open(info)` and `_on_close()` 24 hooks. `_on_open` receives the broker-side `NamespaceInfo`, so subclasses can 25 assert the namespace type and run any setup before `_opened` flips to `True`. 26 27 Typical usage is to pass instances into a `BehavioralModel`, which drives the 28 lifecycle. A namespace can also be used standalone via the async context 29 manager protocol. 30 31 See concrete implementations: 32 - `remotivelabs.topology.namespaces.can.CanNamespace` 33 - `remotivelabs.topology.namespaces.some_ip.SomeIPNamespace` 34 - `remotivelabs.topology.namespaces.generic.GenericNamespace` 35 - `remotivelabs.topology.namespaces.scripted.ScriptedNamespace` 36 """ 37 38 def __init__( 39 self, 40 name: NamespaceName, 41 broker_client: BrokerClient, 42 ): 43 self._namespace = name 44 self._broker_client = broker_client 45 self._opened = False 46 self._sub_monitor = SubscriptionMonitor(broker_client, name) 47 48 @property 49 def name(self) -> NamespaceName: 50 return self._namespace 51 52 @property 53 def opened(self) -> bool: 54 """True if the namespace has been opened.""" 55 return self._opened 56 57 async def open(self) -> Self: 58 """ 59 Open the namespace and prepare it for use. 60 This is an idempotent operation - calling it multiple times has no additional effect. 61 62 Raises: 63 ValueError: If the namespace is not configured on RemotiveBroker. 64 65 Returns: 66 The namespace 67 """ 68 if self._opened: 69 return self 70 info = await self._broker_client.get_namespace(self.name) 71 if info is None: 72 raise ValueError(f"Namespace '{self.name}' is not configured on RemotiveBroker") 73 await self._on_open(info) 74 self._opened = True 75 return self 76 77 async def close(self) -> None: 78 """ 79 Close the namespace and clean up resources. 80 This is an idempotent operation - calling it multiple times has no additional effect. 81 """ 82 self._opened = False 83 try: 84 await self._on_close() 85 finally: 86 await self._sub_monitor.close() 87 88 async def _on_open(self, info: NamespaceInfo) -> None: 89 """ 90 Hook for subclasses to validate the namespace and run setup, after the broker confirms it exists 91 and before `_opened` flips to True. Subclasses that extend another namespace class should call 92 `await super()._on_open(info)` to preserve inherited setup. 93 """ 94 pass 95 96 async def _on_close(self) -> None: 97 """Hook for subclasses to tear down their resources. Runs before the subscription monitor is closed.""" 98 pass 99 100 async def _subscribe( 101 self, 102 subscriptions: list[FrameSubscription], 103 callback: Callable[[Frame], Awaitable[None]], 104 on_change: OnChangeMode = OnChangeMode.OFF, 105 decode_named_values: bool = True, 106 callback_label: str | None = None, 107 ) -> str: 108 return await self._sub_monitor.subscribe( 109 subscriptions, 110 callback, 111 on_change=on_change, 112 decode_named_values=decode_named_values, 113 callback_label=callback_label, 114 ) 115 116 async def _unsubscribe(self, subscription_id: str) -> None: 117 await self._sub_monitor.unsubscribe(subscription_id) 118 119 async def set_secoc_property(self, property: SecocProperty) -> None: 120 """Set a SecOC property in the namespace.""" 121 await self._broker_client.set_secoc_property(namespace=self.name, property=property) 122 123 async def run_forever(self) -> None: 124 """Run the namespace indefinitely, monitoring subscription tasks for exceptions.""" 125 await self._sub_monitor.run_forever() 126 127 async def __aenter__(self) -> Self: 128 return await self.open() 129 130 async def __aexit__(self, exc_type, exc_value, traceback) -> None: 131 await self.close()
17class Namespace(ABC, Generic[F, C]): 18 """ 19 Base class for protocol-specific namespaces. 20 21 A namespace maps to a single namespace on a RemotiveBroker and provides the 22 lifecycle (`open`/`close`) and callback subscription plumbing shared by all 23 protocols. Subclasses add protocol-specific behavior (e.g., restbus, SOME/IP 24 requests, CAN/LIN framing) by overriding the `_on_open(info)` and `_on_close()` 25 hooks. `_on_open` receives the broker-side `NamespaceInfo`, so subclasses can 26 assert the namespace type and run any setup before `_opened` flips to `True`. 27 28 Typical usage is to pass instances into a `BehavioralModel`, which drives the 29 lifecycle. A namespace can also be used standalone via the async context 30 manager protocol. 31 32 See concrete implementations: 33 - `remotivelabs.topology.namespaces.can.CanNamespace` 34 - `remotivelabs.topology.namespaces.some_ip.SomeIPNamespace` 35 - `remotivelabs.topology.namespaces.generic.GenericNamespace` 36 - `remotivelabs.topology.namespaces.scripted.ScriptedNamespace` 37 """ 38 39 def __init__( 40 self, 41 name: NamespaceName, 42 broker_client: BrokerClient, 43 ): 44 self._namespace = name 45 self._broker_client = broker_client 46 self._opened = False 47 self._sub_monitor = SubscriptionMonitor(broker_client, name) 48 49 @property 50 def name(self) -> NamespaceName: 51 return self._namespace 52 53 @property 54 def opened(self) -> bool: 55 """True if the namespace has been opened.""" 56 return self._opened 57 58 async def open(self) -> Self: 59 """ 60 Open the namespace and prepare it for use. 61 This is an idempotent operation - calling it multiple times has no additional effect. 62 63 Raises: 64 ValueError: If the namespace is not configured on RemotiveBroker. 65 66 Returns: 67 The namespace 68 """ 69 if self._opened: 70 return self 71 info = await self._broker_client.get_namespace(self.name) 72 if info is None: 73 raise ValueError(f"Namespace '{self.name}' is not configured on RemotiveBroker") 74 await self._on_open(info) 75 self._opened = True 76 return self 77 78 async def close(self) -> None: 79 """ 80 Close the namespace and clean up resources. 81 This is an idempotent operation - calling it multiple times has no additional effect. 82 """ 83 self._opened = False 84 try: 85 await self._on_close() 86 finally: 87 await self._sub_monitor.close() 88 89 async def _on_open(self, info: NamespaceInfo) -> None: 90 """ 91 Hook for subclasses to validate the namespace and run setup, after the broker confirms it exists 92 and before `_opened` flips to True. Subclasses that extend another namespace class should call 93 `await super()._on_open(info)` to preserve inherited setup. 94 """ 95 pass 96 97 async def _on_close(self) -> None: 98 """Hook for subclasses to tear down their resources. Runs before the subscription monitor is closed.""" 99 pass 100 101 async def _subscribe( 102 self, 103 subscriptions: list[FrameSubscription], 104 callback: Callable[[Frame], Awaitable[None]], 105 on_change: OnChangeMode = OnChangeMode.OFF, 106 decode_named_values: bool = True, 107 callback_label: str | None = None, 108 ) -> str: 109 return await self._sub_monitor.subscribe( 110 subscriptions, 111 callback, 112 on_change=on_change, 113 decode_named_values=decode_named_values, 114 callback_label=callback_label, 115 ) 116 117 async def _unsubscribe(self, subscription_id: str) -> None: 118 await self._sub_monitor.unsubscribe(subscription_id) 119 120 async def set_secoc_property(self, property: SecocProperty) -> None: 121 """Set a SecOC property in the namespace.""" 122 await self._broker_client.set_secoc_property(namespace=self.name, property=property) 123 124 async def run_forever(self) -> None: 125 """Run the namespace indefinitely, monitoring subscription tasks for exceptions.""" 126 await self._sub_monitor.run_forever() 127 128 async def __aenter__(self) -> Self: 129 return await self.open() 130 131 async def __aexit__(self, exc_type, exc_value, traceback) -> None: 132 await self.close()
Base class for protocol-specific namespaces.
A namespace maps to a single namespace on a RemotiveBroker and provides the
lifecycle (open/close) and callback subscription plumbing shared by all
protocols. Subclasses add protocol-specific behavior (e.g., restbus, SOME/IP
requests, CAN/LIN framing) by overriding the _on_open(info) and _on_close()
hooks. _on_open receives the broker-side NamespaceInfo, so subclasses can
assert the namespace type and run any setup before _opened flips to True.
Typical usage is to pass instances into a BehavioralModel, which drives the
lifecycle. A namespace can also be used standalone via the async context
manager protocol.
See concrete implementations:
53 @property 54 def opened(self) -> bool: 55 """True if the namespace has been opened.""" 56 return self._opened
True if the namespace has been opened.
58 async def open(self) -> Self: 59 """ 60 Open the namespace and prepare it for use. 61 This is an idempotent operation - calling it multiple times has no additional effect. 62 63 Raises: 64 ValueError: If the namespace is not configured on RemotiveBroker. 65 66 Returns: 67 The namespace 68 """ 69 if self._opened: 70 return self 71 info = await self._broker_client.get_namespace(self.name) 72 if info is None: 73 raise ValueError(f"Namespace '{self.name}' is not configured on RemotiveBroker") 74 await self._on_open(info) 75 self._opened = True 76 return self
Open the namespace and prepare it for use. This is an idempotent operation - calling it multiple times has no additional effect.
Raises:
- ValueError: If the namespace is not configured on RemotiveBroker.
Returns:
The namespace
78 async def close(self) -> None: 79 """ 80 Close the namespace and clean up resources. 81 This is an idempotent operation - calling it multiple times has no additional effect. 82 """ 83 self._opened = False 84 try: 85 await self._on_close() 86 finally: 87 await self._sub_monitor.close()
Close the namespace and clean up resources. This is an idempotent operation - calling it multiple times has no additional effect.
120 async def set_secoc_property(self, property: SecocProperty) -> None: 121 """Set a SecOC property in the namespace.""" 122 await self._broker_client.set_secoc_property(namespace=self.name, property=property)
Set a SecOC property in the namespace.