remotivelabs.topology.namespaces.lin
LIN namespace package.
Enables publishing and subscribing to frames and signals on a LIN (Local Interconnect Network) bus.
Unlike CAN, LIN frames are not driven by a client-side restbus. Frame timing is governed by the LIN master's schedule table (defined in the LDF) and executed by RemotiveBroker. Each side of the bus publishes its sender frames into a per-namespace cache; the broker emits the cached values when the master polls.
1""" 2# LIN namespace package. 3 4<!-- start-include --> 5Enables publishing and subscribing to frames and signals on a LIN (Local Interconnect Network) bus. 6 7Unlike CAN, LIN frames are not driven by a client-side restbus. Frame timing is governed by the 8LIN master's schedule table (defined in the LDF) and executed by RemotiveBroker. Each side of the 9bus publishes its sender frames into a per-namespace cache; the broker emits the cached values 10when the master polls. 11<!-- end-include --> 12""" 13 14from __future__ import annotations 15 16from remotivelabs.topology.namespaces.lin.namespace import LinNamespace 17 18__all__ = ["LinNamespace"]
28class LinNamespace(Namespace[FilterLike, Callable[[Frame], Awaitable[None]]]): 29 """ 30 Used to represent a LIN (Local Interconnect Network) namespace in a simulation or testing environment. 31 32 Frame timing is governed by the LIN master's schedule table. Frames are published directly to the 33 broker's per-namespace cache; the broker emits the cached values when the master polls. The cache 34 is seeded with each signal's database-defined start value when the namespace is opened. 35 """ 36 37 _input_handlers: list[InputHandlerSpec] 38 _cache_config: list[FilterLike] | None 39 40 def __init__( 41 self, 42 name: NamespaceName, 43 broker_client: BrokerClient, 44 decode_named_values: bool = False, 45 input_handlers: list[InputHandlerSpec] | None = None, 46 cache_config: str | list[FilterLike] | None = None, 47 ): 48 """ 49 Initialize the LIN namespace client. 50 51 Args: 52 name: The namespace name to operate in. 53 broker_client: The client used to communicate with the broker. 54 decode_named_values: True will decode named values to str. 55 input_handlers: Optional list of `(filters, callback)` pairs registered on `open()`. 56 cache_config: Optional filter configuration for populating the frame cache. Can be a sender name string 57 or a list of FilterLike objects. If None, cache initialization is skipped. 58 59 """ 60 super().__init__(name=name, broker_client=broker_client) 61 self._decode_named_values = decode_named_values 62 self._input_handlers = input_handlers or [] 63 64 if isinstance(cache_config, str): 65 self._cache_config = [SenderFilter(cache_config)] 66 else: 67 self._cache_config = cache_config 68 69 async def _on_open(self, info: NamespaceInfo) -> None: 70 if info.type not in ("lin", "udp-lin"): 71 raise ValueError(f"Namespace '{self.name}' is not of type 'lin' or 'udp-lin'") 72 await self.init_frame_cache() 73 for filters, callback in self._input_handlers: 74 await self.subscribe_input_handler(filters, callback) 75 76 async def init_frame_cache(self) -> None: 77 """ 78 Seed the broker-side LIN cache with each signal's database-defined start value. 79 80 On a LIN bus, publishing sets the value the broker returns when the master polls a frame. 81 Called automatically from `open()`; can be called again to re-seed the cache. 82 83 E2E counter and CRC signals are excluded from cache initialization. They will be 84 calculated by the broker. 85 """ 86 87 if self._cache_config is None: 88 return 89 90 frame_infos = await self.list_frame_infos() 91 92 # Apply both cache_config filters and E2E signal exclusion 93 filters = [*self._cache_config, E2eSignalsFilter(exclude=True)] 94 95 frames: list[FrameInfo] = [] 96 for frame_info in frame_infos: 97 filtered_frame_info = filter_recursive(frame_info, filters) 98 if filtered_frame_info and filtered_frame_info.signals: 99 frames.append(filtered_frame_info) 100 101 writes: list[WriteSignal] = [] 102 for frame_info in frames: 103 for name, info in frame_info.signals.items(): 104 writes.append(WriteSignal(name, info.start_value)) 105 106 if writes: 107 await self.publish(*writes) 108 109 async def set_schedule(self, schedule_table_name: str) -> None: 110 """ 111 Switch the active LIN schedule table on this namespace. 112 113 Only valid on a LIN master namespace. 114 115 Args: 116 schedule_table_name: Name of the schedule table to activate (as defined in the LDF). 117 """ 118 await self._broker_client.switch_lin_schedule(self.name, schedule_table_name) 119 120 async def list_frame_infos(self) -> list[FrameInfo]: 121 """Return all available frame infos in the namespace.""" 122 return await self._broker_client.list_frame_infos(self.name) 123 124 async def get_frame_info(self, name: str) -> FrameInfo | None: 125 """Return information about a specific frame by name.""" 126 return await self._broker_client.get_frame_info(name, namespace=self.name) 127 128 async def list_signal_infos(self) -> list[SignalInfo]: 129 """Return all available signal infos in the namespace.""" 130 return await self._broker_client.list_signal_infos(self.name) 131 132 async def get_signal_info(self, name: SignalName) -> SignalInfo | None: 133 """Return information about a specific signal by name.""" 134 return await self._broker_client.get_signal_info(name, namespace=self.name) 135 136 async def publish(self, *signals: WriteSignal | tuple[SignalName, SignalValue]) -> None: 137 """ 138 Publish one or more signals to the broker. 139 140 On LIN this writes to the broker-side cache that the schedule reads from. 141 142 Args: 143 *signals: One or more WriteSignal instances or (signal_name, value) tuples to publish. 144 """ 145 remapped = [WriteSignal(name=s[0], value=s[1]) if isinstance(s, tuple) else s for s in signals] 146 await self._broker_client.publish((self._namespace, remapped)) 147 148 async def subscribe(self, *name: SignalName, on_change: bool = False) -> AsyncIterator[list[Signal]]: 149 """ 150 Subscribe to a list of signals. 151 152 Args: 153 *name: One or more signal names to subscribe to. 154 on_change: Whether to receive updates only on change. 155 156 Note: does not support decoding enums 157 158 Returns: 159 An asynchronous iterator of lists of Signal objects. 160 """ 161 return await self._broker_client.subscribe((self.name, list(name)), on_change=on_change, initial_empty=True) 162 163 async def subscribe_frames( 164 self, 165 *frames: FrameSubscription, 166 on_change: bool = False, 167 initial_empty: bool = True, 168 decode_named_values: bool | None = None, 169 ) -> AsyncIterator[Frame]: 170 """ 171 Subscribe to Frames. 172 173 Args: 174 *frames: One or more frames to subscribe to. 175 on_change: Whether to receive updates only on change. 176 initial_empty: If `True`, the first broker message (an empty sync marker) is 177 consumed internally before the iterator is returned, ensuring the broker is 178 ready before the first real value arrives. 179 decode_named_values: True will decode named values to str. Defaults to the value 180 set in the constructor. 181 182 Returns: 183 An asynchronous iterator with Frames. 184 """ 185 decode_values = self._decode_named_values if decode_named_values is None else decode_named_values 186 return await self._broker_client.subscribe_frames( 187 (self.name, list(frames)), on_change=on_change, initial_empty=initial_empty, decode_named_values=decode_values 188 ) 189 190 async def subscribe_headers( 191 self, 192 *frames: FrameName, 193 initial_empty: bool = True, 194 ) -> AsyncIterator[Header]: 195 """ 196 Subscribe to frame headers (arbitration identifiers) on this namespace. 197 198 Headers carry only the frame identifier — no signal values. On LIN this lets you 199 observe which frames the master is polling without subscribing to the responses. 200 201 Args: 202 *frames: Frame names whose headers to subscribe to. 203 initial_empty: If `True`, the first broker message (an empty sync marker) is 204 consumed internally before the iterator is returned, ensuring the broker 205 is ready before the first real header arrives. 206 207 Returns: 208 An async iterator yielding one `Header` per received frame header. 209 """ 210 return await self._broker_client.subscribe_header((self.name, list(frames)), initial_empty=initial_empty) 211 212 async def subscribe_input_handler( 213 self, 214 filters: Sequence[FilterLike], 215 callback: Callable[[Frame], Awaitable[None]], 216 ) -> str: 217 """ 218 Register an input handler on the namespace to receive frames matching the given filters. 219 220 Use `unsubscribe_input_handler` to remove it. 221 222 Args: 223 filters: Filters to select frames and/or signals. 224 callback: Async function called with each matching `Frame`. 225 226 Returns: 227 A subscription ID to pass to `unsubscribe_input_handler`. 228 229 Raises: 230 ValueError: If the filters do not match any frames in the namespace. 231 """ 232 handler = FrameHandler(filters=filters, cb=callback, decode_named_values=self._decode_named_values) 233 for fi in await self._broker_client.list_frame_infos(self.name): 234 handler.add(fi) 235 subs = handler.subscriptions() 236 if not subs: 237 raise ValueError(f"Input handler filters {list(filters)} did not match any frames on namespace '{self.name}'") 238 239 return await self._subscribe(subs, handler.handle, decode_named_values=False) 240 241 async def unsubscribe_input_handler(self, subscription_id: str) -> None: 242 """ 243 Cancel an input handler registered via `subscribe_input_handler`. 244 245 Args: 246 subscription_id: The ID returned by `subscribe_input_handler`. 247 """ 248 await self._unsubscribe(subscription_id) 249 250 def create_input_handler( 251 self, 252 filters: Sequence[FilterLike], 253 callback: Callable[[Frame], Awaitable[None]], 254 ) -> tuple[NamespaceName, InputHandler]: 255 """ 256 Create an input handler for this namespace to be used with a `BehavioralModel`. 257 258 Args: 259 filters: A sequence of filter objects to select relevant frames or signals. 260 callback: An async callback invoked with each matching `Frame`. 261 262 Returns: 263 A `(namespace_name, handler)` pair ready to pass to `BehavioralModel`. 264 """ 265 return (self.name, FrameHandler(filters=filters, cb=callback, decode_named_values=self._decode_named_values))
Used to represent a LIN (Local Interconnect Network) namespace in a simulation or testing environment.
Frame timing is governed by the LIN master's schedule table. Frames are published directly to the broker's per-namespace cache; the broker emits the cached values when the master polls. The cache is seeded with each signal's database-defined start value when the namespace is opened.
40 def __init__( 41 self, 42 name: NamespaceName, 43 broker_client: BrokerClient, 44 decode_named_values: bool = False, 45 input_handlers: list[InputHandlerSpec] | None = None, 46 cache_config: str | list[FilterLike] | None = None, 47 ): 48 """ 49 Initialize the LIN namespace client. 50 51 Args: 52 name: The namespace name to operate in. 53 broker_client: The client used to communicate with the broker. 54 decode_named_values: True will decode named values to str. 55 input_handlers: Optional list of `(filters, callback)` pairs registered on `open()`. 56 cache_config: Optional filter configuration for populating the frame cache. Can be a sender name string 57 or a list of FilterLike objects. If None, cache initialization is skipped. 58 59 """ 60 super().__init__(name=name, broker_client=broker_client) 61 self._decode_named_values = decode_named_values 62 self._input_handlers = input_handlers or [] 63 64 if isinstance(cache_config, str): 65 self._cache_config = [SenderFilter(cache_config)] 66 else: 67 self._cache_config = cache_config
Initialize the LIN namespace client.
Arguments:
- name: The namespace name to operate in.
- broker_client: The client used to communicate with the broker.
- decode_named_values: True will decode named values to str.
- input_handlers: Optional list of
(filters, callback)pairs registered onopen(). - cache_config: Optional filter configuration for populating the frame cache. Can be a sender name string or a list of FilterLike objects. If None, cache initialization is skipped.
76 async def init_frame_cache(self) -> None: 77 """ 78 Seed the broker-side LIN cache with each signal's database-defined start value. 79 80 On a LIN bus, publishing sets the value the broker returns when the master polls a frame. 81 Called automatically from `open()`; can be called again to re-seed the cache. 82 83 E2E counter and CRC signals are excluded from cache initialization. They will be 84 calculated by the broker. 85 """ 86 87 if self._cache_config is None: 88 return 89 90 frame_infos = await self.list_frame_infos() 91 92 # Apply both cache_config filters and E2E signal exclusion 93 filters = [*self._cache_config, E2eSignalsFilter(exclude=True)] 94 95 frames: list[FrameInfo] = [] 96 for frame_info in frame_infos: 97 filtered_frame_info = filter_recursive(frame_info, filters) 98 if filtered_frame_info and filtered_frame_info.signals: 99 frames.append(filtered_frame_info) 100 101 writes: list[WriteSignal] = [] 102 for frame_info in frames: 103 for name, info in frame_info.signals.items(): 104 writes.append(WriteSignal(name, info.start_value)) 105 106 if writes: 107 await self.publish(*writes)
Seed the broker-side LIN cache with each signal's database-defined start value.
On a LIN bus, publishing sets the value the broker returns when the master polls a frame.
Called automatically from open(); can be called again to re-seed the cache.
E2E counter and CRC signals are excluded from cache initialization. They will be calculated by the broker.
109 async def set_schedule(self, schedule_table_name: str) -> None: 110 """ 111 Switch the active LIN schedule table on this namespace. 112 113 Only valid on a LIN master namespace. 114 115 Args: 116 schedule_table_name: Name of the schedule table to activate (as defined in the LDF). 117 """ 118 await self._broker_client.switch_lin_schedule(self.name, schedule_table_name)
Switch the active LIN schedule table on this namespace.
Only valid on a LIN master namespace.
Arguments:
- schedule_table_name: Name of the schedule table to activate (as defined in the LDF).
120 async def list_frame_infos(self) -> list[FrameInfo]: 121 """Return all available frame infos in the namespace.""" 122 return await self._broker_client.list_frame_infos(self.name)
Return all available frame infos in the namespace.
124 async def get_frame_info(self, name: str) -> FrameInfo | None: 125 """Return information about a specific frame by name.""" 126 return await self._broker_client.get_frame_info(name, namespace=self.name)
Return information about a specific frame by name.
128 async def list_signal_infos(self) -> list[SignalInfo]: 129 """Return all available signal infos in the namespace.""" 130 return await self._broker_client.list_signal_infos(self.name)
Return all available signal infos in the namespace.
132 async def get_signal_info(self, name: SignalName) -> SignalInfo | None: 133 """Return information about a specific signal by name.""" 134 return await self._broker_client.get_signal_info(name, namespace=self.name)
Return information about a specific signal by name.
136 async def publish(self, *signals: WriteSignal | tuple[SignalName, SignalValue]) -> None: 137 """ 138 Publish one or more signals to the broker. 139 140 On LIN this writes to the broker-side cache that the schedule reads from. 141 142 Args: 143 *signals: One or more WriteSignal instances or (signal_name, value) tuples to publish. 144 """ 145 remapped = [WriteSignal(name=s[0], value=s[1]) if isinstance(s, tuple) else s for s in signals] 146 await self._broker_client.publish((self._namespace, remapped))
Publish one or more signals to the broker.
On LIN this writes to the broker-side cache that the schedule reads from.
Arguments:
- *signals: One or more WriteSignal instances or (signal_name, value) tuples to publish.
148 async def subscribe(self, *name: SignalName, on_change: bool = False) -> AsyncIterator[list[Signal]]: 149 """ 150 Subscribe to a list of signals. 151 152 Args: 153 *name: One or more signal names to subscribe to. 154 on_change: Whether to receive updates only on change. 155 156 Note: does not support decoding enums 157 158 Returns: 159 An asynchronous iterator of lists of Signal objects. 160 """ 161 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.
163 async def subscribe_frames( 164 self, 165 *frames: FrameSubscription, 166 on_change: bool = False, 167 initial_empty: bool = True, 168 decode_named_values: bool | None = None, 169 ) -> AsyncIterator[Frame]: 170 """ 171 Subscribe to Frames. 172 173 Args: 174 *frames: One or more frames to subscribe to. 175 on_change: Whether to receive updates only on change. 176 initial_empty: If `True`, the first broker message (an empty sync marker) is 177 consumed internally before the iterator is returned, ensuring the broker is 178 ready before the first real value arrives. 179 decode_named_values: True will decode named values to str. Defaults to the value 180 set in the constructor. 181 182 Returns: 183 An asynchronous iterator with Frames. 184 """ 185 decode_values = self._decode_named_values if decode_named_values is None else decode_named_values 186 return await self._broker_client.subscribe_frames( 187 (self.name, list(frames)), on_change=on_change, initial_empty=initial_empty, decode_named_values=decode_values 188 )
Subscribe to 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. - decode_named_values: True will decode named values to str. Defaults to the value set in the constructor.
Returns:
An asynchronous iterator with Frames.
190 async def subscribe_headers( 191 self, 192 *frames: FrameName, 193 initial_empty: bool = True, 194 ) -> AsyncIterator[Header]: 195 """ 196 Subscribe to frame headers (arbitration identifiers) on this namespace. 197 198 Headers carry only the frame identifier — no signal values. On LIN this lets you 199 observe which frames the master is polling without subscribing to the responses. 200 201 Args: 202 *frames: Frame names whose headers to subscribe to. 203 initial_empty: If `True`, the first broker message (an empty sync marker) is 204 consumed internally before the iterator is returned, ensuring the broker 205 is ready before the first real header arrives. 206 207 Returns: 208 An async iterator yielding one `Header` per received frame header. 209 """ 210 return await self._broker_client.subscribe_header((self.name, list(frames)), initial_empty=initial_empty)
Subscribe to frame headers (arbitration identifiers) on this namespace.
Headers carry only the frame identifier — no signal values. On LIN this lets you observe which frames the master is polling without subscribing to the responses.
Arguments:
- *frames: Frame names 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 header arrives.
Returns:
An async iterator yielding one
Headerper received frame header.
212 async def subscribe_input_handler( 213 self, 214 filters: Sequence[FilterLike], 215 callback: Callable[[Frame], Awaitable[None]], 216 ) -> str: 217 """ 218 Register an input handler on the namespace to receive frames matching the given filters. 219 220 Use `unsubscribe_input_handler` to remove it. 221 222 Args: 223 filters: Filters to select frames and/or signals. 224 callback: Async function called with each matching `Frame`. 225 226 Returns: 227 A subscription ID to pass to `unsubscribe_input_handler`. 228 229 Raises: 230 ValueError: If the filters do not match any frames in the namespace. 231 """ 232 handler = FrameHandler(filters=filters, cb=callback, decode_named_values=self._decode_named_values) 233 for fi in await self._broker_client.list_frame_infos(self.name): 234 handler.add(fi) 235 subs = handler.subscriptions() 236 if not subs: 237 raise ValueError(f"Input handler filters {list(filters)} did not match any frames on namespace '{self.name}'") 238 239 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.
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.
241 async def unsubscribe_input_handler(self, subscription_id: str) -> None: 242 """ 243 Cancel an input handler registered via `subscribe_input_handler`. 244 245 Args: 246 subscription_id: The ID returned by `subscribe_input_handler`. 247 """ 248 await self._unsubscribe(subscription_id)
Cancel an input handler registered via subscribe_input_handler.
Arguments:
- subscription_id: The ID returned by
subscribe_input_handler.
250 def create_input_handler( 251 self, 252 filters: Sequence[FilterLike], 253 callback: Callable[[Frame], Awaitable[None]], 254 ) -> tuple[NamespaceName, InputHandler]: 255 """ 256 Create an input handler for this namespace to be used with a `BehavioralModel`. 257 258 Args: 259 filters: A sequence of filter objects to select relevant frames or signals. 260 callback: An async callback invoked with each matching `Frame`. 261 262 Returns: 263 A `(namespace_name, handler)` pair ready to pass to `BehavioralModel`. 264 """ 265 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.