remotivelabs.topology.mapping
remotivelabs.topology.mapping
Signal and message routing and transforms for the RemotiveTopology Python framework.
The module consolidates the pattern of subscribing on one channel, optionally transforming,
and republishing on another. It is built around a declarative mapping file format that can be
generated from ARXML or hand-authored for non-AUTOSAR use cases. A mapping file is loaded and
executed by a remotivelabs.topology.mapping.MappingModel — including custom sources and
targets registered on it — or wired into a
remotivelabs.topology.behavioral_model.BehavioralModel when the ECU also needs its own
callbacks.
Requires the mapping extra:
pip install remotivelabs-topology[mapping]
Mapping file format
A mapping file is a YAML list of routing entries. Each entry pairs a source with one or
more targets, and works on one of two levels: message level routes whole messages —
a CAN/LIN frame, an Ethernet PDU, or whatever unit a custom type defines — while
signal level maps a single value within one message. Signal-level entries may add a
transform; message-level entries are always passthrough (the raw payload is copied
without decode, and a transform on one fails validation). Both levels mix freely in
one file.
# yaml-language-server: $schema=https://files.remotivelabs.com/schemas/gateway-mapping-0.2.schema.json
schema: https://files.remotivelabs.com/schemas/gateway-mapping-0.2.schema.json
mappings:
# Message-level routing: one message to one target message
# Note: transforms are not allowed at message level
- source:
type: can
channel: RightDoor1CAN
frame: FrdmRightDoor1CanFrame01
target:
type: ethernet.pdu
channel: Insecure
source_socket: ZCInsecureUDP
target_socket: ZCInsecureCpEcuUDP
pdu: PduTrFrdmRightDoor1CanSignalPdu01
# Compact message-level routing: many messages between one channel pair
# This type of entry is what CLI generation produces from ARXML
- source:
type: can
channel: RightDoor1CAN
target:
type: ethernet.pdu
channel: Insecure
source_socket: ZCInsecureUDP
target_socket: ZCInsecureCpEcuUDP
messages:
FrdmRightDoor1CanFrame01: PduTrFrdmRightDoor1CanSignalPdu01
# Signal-level mapping CAN → LIN with a transform
- source:
type: can
frame: TurnLightControl
signal: LeftTurnLightRequest
channel: BodyCan0
target:
type: lin
frame: LpcLpc12LinFr01
signal: ExLiLpRearLiReqTurnIndcrLeLiCtrlLinFlg
channel: lin0
transform:
type: linear
factor: 1.0
min: 0
max: 255
# Fan-out: one source, a list of targets, shared transform
- source:
type: can
frame: TurnLightControl
signal: LeftTurnLightRequest
channel: BodyCan0
target:
- type: can
frame: FrontLightControl
signal: LeftIndicator
channel: FrontCan0
- type: can
frame: RearLightControl
signal: LeftIndicator
channel: RearCan0
transform:
type: passthrough
type identifies the channel type; can, lin, and ethernet.pdu are built-in and
executed by the framework. Any custom.-prefixed
type is user-defined; the framework loads and validates the entry, but application code
wires the I/O (see Use cases).
Execution model
Every routing entry follows the same flow:
source → transform → target
- source — where values come from: a broker channel, or a custom source
- transform — how each value is converted:
passthrough,linear,lookup, or a custom transform - target — where the converted value goes: a broker channel, or a custom target
These roles map directly to Python abstractions: a remotivelabs.topology.mapping.Source
produces values, a remotivelabs.topology.mapping.TransformFn converts each one, and a
remotivelabs.topology.mapping.Target consumes the result.
remotivelabs.topology.mapping.MappingModel is the primary API: it loads a mapping file and
runs every entry concurrently — message forwarding, signal transforms, and any custom sources,
targets, or transforms registered on it (see Use cases) — so mixed files need no
special handling. Under the hood, message-level entries run on
remotivelabs.topology.mapping.Forwarder and built-in signal-level entries on
remotivelabs.topology.mapping.Transformer.
Built-in types
The built-in (can, lin, ethernet.pdu) source and target types are executed by the
framework against the broker: a built-in source subscribes to its channel and feeds each
received message or signal value into the flow; a built-in target publishes the result
back to its channel.
Target output is written the way each channel type expects, so a mapped ECU behaves like a
real one: a CAN target drives a restbus (the frame keeps transmitting at its cycle time,
with the mapped value updated in place), a LIN target populates the broker-side cache the
master polls, and an Ethernet PDU target publishes directly.
remotivelabs.topology.mapping.MappingModel builds the right namespace per target channel
and owns its lifecycle.
Because CAN/LIN targets hold the last value, unchanged values are skipped and sources feeding only such targets are subscribed on change. Forwarding to a CAN target is therefore cyclic/sampled, not a lossless 1:1 relay — sub-cycle bursts coalesce to the latest value.
Use cases
| Use case | You write | Run it with |
|---|---|---|
| Message forwarding between channels | a mapping file (often CLI-generated from ARXML) | MappingModel / its bundled CLI |
| Signal mapping with built-in transforms | a mapping file | MappingModel |
| Custom source | a mapping file + a Source impl |
MappingModel.register_source |
| Custom target | a mapping file + a Target impl |
MappingModel.register_target |
| Custom transform | a mapping file + a TransformFn impl |
MappingModel.register_transform |
| Mappings + your own ECU logic | a mapping file + callbacks | BehavioralModel + handlers_from_mapping |
Message forwarding between channels
When the routing is already described by ARXML — typically a zone-controller or gateway
ECU — the remotive-topology CLI generates the mapping file directly from it, with no
hand-authored YAML or Python required: the generated mapping is automatically included in
the generated topology and loaded by the resulting ECU container at runtime. See the
remotive-topology CLI docs
for the generation flow.
Hand-author the mapping file when there's no ARXML available (e.g. non-AUTOSAR systems or prototypes), or when the ARXML doesn't describe the routing you need (e.g. cross-bus mapping or topology-specific bridging not captured in the source artifacts).
Either way, use remotivelabs.topology.mapping.MappingModel as the ECU's container entry point:
import asyncio
from pathlib import Path
from remotivelabs.broker import BrokerClient
from remotivelabs.topology.mapping import MappingModel
async def main():
async with BrokerClient(url="http://127.0.0.1:50051") as client:
model = MappingModel.from_mapping_file(Path("my-custom.gateway-mapping.yaml"), client)
await model.run_forever()
if __name__ == "__main__":
asyncio.run(main())
Or, run the bundled CLI directly:
python -m remotivelabs.topology.cli.mapping --mapping my-custom.gateway-mapping.yaml
A mapping channel is the bare bus name (e.g. BodyCan0), not a broker namespace — the same
bus is exposed as topology-BodyCan0 for standalone consumers or RLCM-BodyCan0 when running
as the RLCM ECU. The runtime resolves it as <ecu>-<channel>: the topology catch-all by
default, the ECU name via --ecu RLCM (or ecu="RLCM" in code), or an empty string for flat
namespaces that don't follow that scheme. Ethernet PDU channels fold their ARXML socket pair
in — topology-generated brokers wire one namespace per SoAd socket connection, so an
ethernet.pdu address resolves as <ecu>-<source_socket>-<target_socket>-<channel>.
Note: Don't forget to package the mapping YAML into the container image so it's available at runtime.
Signal mapping with built-in transforms
Hand-author signal-level entries with passthrough, linear, or lookup transforms (see the
format example above). They run exactly like message forwarding:
remotivelabs.topology.mapping.MappingModel executes every signal-level entry with a built-in
transform, alongside any message-level entries in the same file.
Custom source
Implement the remotivelabs.topology.mapping.Source protocol — a class with a
single signals() async-generator method — to plug a custom data origin (an input
device, FMU, websocket, ...) into a mapping. Its constructor takes the entry's
source address (authored YAML fields are read with address["field"]), plus an
optional second argument for dependencies you pass at registration:
model.register_source("custom.evdev", EvdevSource) # __init__(self, address)
model.register_source("custom.mqtt", MqttSource, MqttArgs(client=c)) # __init__(self, address, args)
remotivelabs.topology.mapping.MappingModel constructs one source per entry and
runs the flow (source → transform → built-in target) alongside its other entries.
Example — USB input device (evdev) mapped to a CAN signal
(see tests/fixtures/mappings/input_mapper_evdev.gateway-mapping.yaml):
- source:
type: custom.evdev # custom types are prefixed "custom."
signal: ABS_X
device_path: /dev/input/event4 # custom fields — read with address["device_path"], ...
source_type: 3
source_code: 0
target:
type: can
frame: SteeringWheelInfo
signal: SteeringWheelPosition
channel: BodyCan0
transform:
type: linear
factor: 0.1
min: -900.0
max: 900.0
import asyncio
from pathlib import Path
from typing import AsyncIterator
import evdev
from remotivelabs.broker import BrokerClient, SignalValue
from remotivelabs.topology.mapping import MappingModel
from remotivelabs.topology.mapping.models import SignalAddress
class EvdevSource:
"""
Custom `Source`: yields signal values from an evdev input device.
Constructed once per mapping entry; the entry's YAML fields are read with `address["field"]`.
"""
def __init__(self, address: SignalAddress) -> None:
self._device = evdev.InputDevice(address["device_path"])
self._source_type = int(address["source_type"])
self._source_code = int(address["source_code"])
async def signals(self) -> AsyncIterator[SignalValue]:
# A production source should also reconnect when the device drops.
async for event in self._device.async_read_loop():
if event.type == self._source_type and event.code == self._source_code:
yield event.value
async def main() -> None:
async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
# MappingModel owns the wiring: namespaces for built-in targets (CAN gets a restbus)
# and one source -> transform -> target flow per custom.evdev entry.
model = MappingModel.from_mapping_file(Path("my-custom.gateway-mapping.yaml"), broker_client, ecu="MyEcu")
model.register_source("custom.evdev", EvdevSource)
await model.run_forever()
if __name__ == "__main__":
asyncio.run(main())
Custom target
Implement the remotivelabs.topology.mapping.Target protocol — a class with a
single publish() async method — to plug a custom destination (VISSR, websocket,
file, ...) into a mapping. Constructed like a custom source — __init__(self, address)
or __init__(self, address, args) with dependencies passed at registration (group them
in a dataclass; remotivelabs.topology.mapping.TargetArgs is the optional
convention base). Registering a built-in type (e.g. "can") overrides the default
broker-backed target for entries that involve a custom address.
Example — broker scripted namespace (VSS) forwarded to a VISSR server
(see tests/fixtures/mappings/vss_namespace_to_vissr.gateway-mapping.yaml):
- source:
type: custom.vss # user-defined — channel below is the broker scripted namespace
signal: Vehicle.Speed
channel: vss
target:
type: custom.vissr # user-defined type string — implement the target yourself
signal: Vehicle.Speed
transform:
type: passthrough
import asyncio
from dataclasses import dataclass
from pathlib import Path
from remotivelabs.broker import BrokerClient, SignalValue
from remotivelabs.topology.mapping import MappingModel, Source, TargetArgs, TopologySource
from remotivelabs.topology.mapping.models import SignalAddress
@dataclass
class VissrArgs(TargetArgs):
"""Dependencies for VissrTarget — passed once at registration, shared by every entry."""
server_url: str
class VissrTarget:
"""
Custom `Target`: forwards values to a VISSR server.
Constructed once per mapping entry: the address's `signal` is the VSS path, dependencies
arrive as the second constructor argument.
"""
def __init__(self, address: SignalAddress, args: VissrArgs) -> None:
self._vss_path = address.signal
self._server_url = args.server_url
async def publish(self, value: SignalValue) -> None:
# Real implementation would call into a VISSR client here.
print(f"vissr {self._server_url} set {self._vss_path}={value!r}")
def vss_source(address: SignalAddress, broker_client: BrokerClient) -> Source:
"""
Reads VSS paths from a broker scripted namespace (the `custom.vss` channel).
A single dependency can be passed bare as `args` — no dataclass needed.
"""
return TopologySource(namespace=address["channel"], frame=address.signal, signal=address.signal, broker_client=broker_client)
async def main() -> None:
async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
model = MappingModel.from_mapping_file(Path("my-custom.gateway-mapping.yaml"), broker_client)
model.register_source("custom.vss", vss_source, broker_client)
model.register_target("custom.vissr", VissrTarget, VissrArgs(server_url="ws://localhost:8080"))
await model.run_forever()
if __name__ == "__main__":
asyncio.run(main())
Custom transform
Implement a remotivelabs.topology.mapping.TransformFn — a callable taking one signal value
and returning the transformed value — for logic the built-in transforms can't express.
Constructed like a custom source or target (__init__(self, transform) plus an optional
args for dependencies), so instances may hold per-entry state: a toggle, a counter, a
debounce. Custom transforms run in their own flow even between built-in channels.
Mapping file:
- source:
type: can
frame: HazardSwitch
signal: HazardRequest
channel: DriverCan
target:
type: can
frame: TurnLightControl
signal: HazardRequest
channel: BodyCan0
transform:
type: custom.hazard_toggle # toggle state machine — registered in code
initial: 0 # custom field → transform["initial"]
Application code:
import asyncio
from pathlib import Path
from remotivelabs.broker import BrokerClient, SignalValue
from remotivelabs.topology.mapping import MappingModel
from remotivelabs.topology.mapping.models import CustomTransform
class HazardToggle:
"""
Custom transform: toggles its output on every rising edge of the input.
Constructed once per mapping entry, so the state is per entry; called once per value.
"""
def __init__(self, transform: CustomTransform) -> None:
self._state = bool(transform.get("initial", 0))
self._previous: SignalValue = 0
def __call__(self, value: SignalValue) -> SignalValue:
if value and not self._previous:
self._state = not self._state
self._previous = value
return int(self._state)
async def main() -> None:
async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
model = MappingModel.from_mapping_file(Path("my-custom.gateway-mapping.yaml"), broker_client)
model.register_transform("custom.hazard_toggle", HazardToggle)
await model.run_forever()
if __name__ == "__main__":
asyncio.run(main())
Mappings + your own ECU logic
Use this when an ECU needs code that doesn't fit the Source / Target / TransformFn
protocols — logic spanning multiple signals, frame context, or asynchronous side effects —
in addition to its declarative mappings.
The recommended shape is two models under the same ECU in the instance file: one
container runs the mapping (remotivelabs.topology.mapping.MappingModel or the bundled CLI)
and another runs your custom remotivelabs.topology.behavioral_model.BehavioralModel code.
Each stays simple, and they scale and restart independently.
For a single process, remotivelabs.topology.mapping.handlers_from_mapping converts the
mapping file's signal-level entries into input handlers for a standard BehavioralModel;
register your own callbacks alongside them. It converts only signal-level entries with
built-in transforms — anything else in the file needs the two-model shape above.
import asyncio
from pathlib import Path
from remotivelabs.broker import BrokerClient, Frame
from remotivelabs.broker.filters import FrameFilter
from remotivelabs.topology.behavioral_model import BehavioralModel
from remotivelabs.topology.mapping import handlers_from_mapping, load_mapping
from remotivelabs.topology.namespaces.can import CanNamespace
from remotivelabs.topology.namespaces.lin import LinNamespace
async def _on_brake(frame: Frame) -> None:
print(f"Brake light frame received: {frame}")
async def main():
async with BrokerClient(url="http://127.0.0.1:50051") as broker_client:
can_ns = CanNamespace(name="RLCM-BodyCan0", broker_client=broker_client)
lin_ns = LinNamespace(name="RLCM-lin0", broker_client=broker_client)
config = load_mapping(Path("rlcm.gateway-mapping.yaml"))
async with BehavioralModel(
"RLCM",
broker_client=broker_client,
namespaces=[can_ns, lin_ns],
input_handlers=[
*handlers_from_mapping(config, {"BodyCan0": can_ns, "lin0": lin_ns}),
can_ns.create_input_handler([FrameFilter("BrakeLightControl")], _on_brake),
],
) as bm:
await bm.run_forever()
if __name__ == "__main__":
asyncio.run(main())
1""" 2# remotivelabs.topology.mapping 3 4<!-- start-include --> 5Signal and message routing and transforms for the RemotiveTopology Python framework. 6 7The module consolidates the pattern of subscribing on one channel, optionally transforming, 8and republishing on another. It is built around a declarative mapping file format that can be 9generated from ARXML or hand-authored for non-AUTOSAR use cases. A mapping file is loaded and 10executed by a `remotivelabs.topology.mapping.MappingModel` — including custom sources and 11targets registered on it — or wired into a 12`remotivelabs.topology.behavioral_model.BehavioralModel` when the ECU also needs its own 13callbacks. 14 15Requires the `mapping` extra: 16 17```bash 18pip install remotivelabs-topology[mapping] 19``` 20<!-- end-include --> 21 22## Mapping file format 23 24A mapping file is a YAML list of routing entries. Each entry pairs a `source` with one or 25more `target`s, and works on one of two levels: **message level** routes whole messages — 26a CAN/LIN frame, an Ethernet PDU, or whatever unit a custom type defines — while 27**signal level** maps a single value within one message. Signal-level entries may add a 28`transform`; message-level entries are always passthrough (the raw payload is copied 29without decode, and a `transform` on one fails validation). Both levels mix freely in 30one file. 31 32```yaml 33# yaml-language-server: $schema=https://files.remotivelabs.com/schemas/gateway-mapping-0.2.schema.json 34schema: https://files.remotivelabs.com/schemas/gateway-mapping-0.2.schema.json 35 36mappings: 37 # Message-level routing: one message to one target message 38 # Note: transforms are not allowed at message level 39 - source: 40 type: can 41 channel: RightDoor1CAN 42 frame: FrdmRightDoor1CanFrame01 43 target: 44 type: ethernet.pdu 45 channel: Insecure 46 source_socket: ZCInsecureUDP 47 target_socket: ZCInsecureCpEcuUDP 48 pdu: PduTrFrdmRightDoor1CanSignalPdu01 49 50 # Compact message-level routing: many messages between one channel pair 51 # This type of entry is what CLI generation produces from ARXML 52 - source: 53 type: can 54 channel: RightDoor1CAN 55 target: 56 type: ethernet.pdu 57 channel: Insecure 58 source_socket: ZCInsecureUDP 59 target_socket: ZCInsecureCpEcuUDP 60 messages: 61 FrdmRightDoor1CanFrame01: PduTrFrdmRightDoor1CanSignalPdu01 62 63 # Signal-level mapping CAN → LIN with a transform 64 - source: 65 type: can 66 frame: TurnLightControl 67 signal: LeftTurnLightRequest 68 channel: BodyCan0 69 target: 70 type: lin 71 frame: LpcLpc12LinFr01 72 signal: ExLiLpRearLiReqTurnIndcrLeLiCtrlLinFlg 73 channel: lin0 74 transform: 75 type: linear 76 factor: 1.0 77 min: 0 78 max: 255 79 80 # Fan-out: one source, a list of targets, shared transform 81 - source: 82 type: can 83 frame: TurnLightControl 84 signal: LeftTurnLightRequest 85 channel: BodyCan0 86 target: 87 - type: can 88 frame: FrontLightControl 89 signal: LeftIndicator 90 channel: FrontCan0 91 - type: can 92 frame: RearLightControl 93 signal: LeftIndicator 94 channel: RearCan0 95 transform: 96 type: passthrough 97``` 98 99`type` identifies the channel type; `can`, `lin`, and `ethernet.pdu` are built-in and 100executed by the framework. Any `custom.`-prefixed 101type is user-defined; the framework loads and validates the entry, but application code 102wires the I/O (see [Use cases](#use-cases)). 103 104## Execution model 105 106Every routing entry follows the same flow: 107 108``` 109source → transform → target 110``` 111 112- **source** — where values come from: a broker channel, or a custom source 113- **transform** — how each value is converted: `passthrough`, `linear`, `lookup`, or a custom transform 114- **target** — where the converted value goes: a broker channel, or a custom target 115 116These roles map directly to Python abstractions: a `remotivelabs.topology.mapping.Source` 117produces values, a `remotivelabs.topology.mapping.TransformFn` converts each one, and a 118`remotivelabs.topology.mapping.Target` consumes the result. 119 120`remotivelabs.topology.mapping.MappingModel` is the primary API: it loads a mapping file and 121runs every entry concurrently — message forwarding, signal transforms, and any custom sources, 122targets, or transforms registered on it (see [Use cases](#use-cases)) — so mixed files need no 123special handling. Under the hood, message-level entries run on 124`remotivelabs.topology.mapping.Forwarder` and built-in signal-level entries on 125`remotivelabs.topology.mapping.Transformer`. 126 127### Built-in types 128 129The built-in (`can`, `lin`, `ethernet.pdu`) source and target types are executed by the 130framework against the broker: a built-in **source** subscribes to its channel and feeds each 131received message or signal value into the flow; a built-in **target** publishes the result 132back to its channel. 133 134Target output is written the way each channel type expects, so a mapped ECU behaves like a 135real one: a **CAN** target drives a restbus (the frame keeps transmitting at its cycle time, 136with the mapped value updated in place), a **LIN** target populates the broker-side cache the 137master polls, and an **Ethernet PDU** target publishes directly. 138`remotivelabs.topology.mapping.MappingModel` builds the right namespace per target channel 139and owns its lifecycle. 140 141Because CAN/LIN targets hold the last value, unchanged values are skipped and sources feeding 142only such targets are subscribed **on change**. Forwarding to a CAN target is therefore 143**cyclic/sampled**, not a lossless 1:1 relay — sub-cycle bursts coalesce to the latest value. 144 145## Use cases 146 147| Use case | You write | Run it with | 148|----------|-----------|-------------| 149| Message forwarding between channels | a mapping file (often CLI-generated from ARXML) | `MappingModel` / its bundled CLI | 150| Signal mapping with built-in transforms | a mapping file | `MappingModel` | 151| Custom source | a mapping file + a `Source` impl | `MappingModel.register_source` | 152| Custom target | a mapping file + a `Target` impl | `MappingModel.register_target` | 153| Custom transform | a mapping file + a `TransformFn` impl | `MappingModel.register_transform` | 154| Mappings + your own ECU logic | a mapping file + callbacks | `BehavioralModel` + `handlers_from_mapping` | 155 156### Message forwarding between channels 157 158When the routing is already described by ARXML — typically a zone-controller or gateway 159ECU — the `remotive-topology` CLI generates the mapping file directly from it, with no 160hand-authored YAML or Python required: the generated mapping is automatically included in 161the generated topology and loaded by the resulting ECU container at runtime. See the 162[`remotive-topology` CLI docs](https://developer.remotivelabs.com/docs/remotive-cli/cli_man_pages#remotive-topology-gateway-mapping) 163for the generation flow. 164 165Hand-author the mapping file when there's no ARXML available (e.g. non-AUTOSAR systems or 166prototypes), or when the ARXML doesn't describe the routing you need (e.g. cross-bus mapping 167or topology-specific bridging not captured in the source artifacts). 168 169Either way, use `remotivelabs.topology.mapping.MappingModel` as the ECU's container entry point: 170 171```python 172.. include:: ../_docs/snippets/mapping_model.py 173``` 174 175Or, run the bundled CLI directly: 176 177```bash 178python -m remotivelabs.topology.cli.mapping --mapping my-custom.gateway-mapping.yaml 179``` 180 181A mapping `channel` is the bare bus name (e.g. `BodyCan0`), not a broker namespace — the same 182bus is exposed as `topology-BodyCan0` for standalone consumers or `RLCM-BodyCan0` when running 183as the RLCM ECU. The runtime resolves it as `<ecu>-<channel>`: the `topology` catch-all by 184default, the ECU name via `--ecu RLCM` (or `ecu="RLCM"` in code), or an empty string for flat 185namespaces that don't follow that scheme. Ethernet PDU channels fold their ARXML socket pair 186in — topology-generated brokers wire one namespace per SoAd socket connection, so an 187`ethernet.pdu` address resolves as `<ecu>-<source_socket>-<target_socket>-<channel>`. 188 189Note: Don't forget to package the mapping YAML into the container image so it's available at runtime. 190 191### Signal mapping with built-in transforms 192 193Hand-author signal-level entries with `passthrough`, `linear`, or `lookup` transforms (see the 194[format example](#mapping-file-format) above). They run exactly like message forwarding: 195`remotivelabs.topology.mapping.MappingModel` executes every signal-level entry with a built-in 196transform, alongside any message-level entries in the same file. 197 198### Custom source 199 200Implement the `remotivelabs.topology.mapping.Source` protocol — a class with a 201single `signals()` async-generator method — to plug a custom data origin (an input 202device, FMU, websocket, ...) into a mapping. Its constructor takes the entry's 203source address (authored YAML fields are read with `address["field"]`), plus an 204optional second argument for dependencies you pass at registration: 205 206```python 207model.register_source("custom.evdev", EvdevSource) # __init__(self, address) 208model.register_source("custom.mqtt", MqttSource, MqttArgs(client=c)) # __init__(self, address, args) 209``` 210 211`remotivelabs.topology.mapping.MappingModel` constructs one source per entry and 212runs the flow (source → transform → built-in target) alongside its other entries. 213 214Example — USB input device (evdev) mapped to a CAN signal 215(see `tests/fixtures/mappings/input_mapper_evdev.gateway-mapping.yaml`): 216 217```yaml 218- source: 219 type: custom.evdev # custom types are prefixed "custom." 220 signal: ABS_X 221 device_path: /dev/input/event4 # custom fields — read with address["device_path"], ... 222 source_type: 3 223 source_code: 0 224 target: 225 type: can 226 frame: SteeringWheelInfo 227 signal: SteeringWheelPosition 228 channel: BodyCan0 229 transform: 230 type: linear 231 factor: 0.1 232 min: -900.0 233 max: 900.0 234``` 235 236```python 237.. include:: ../_docs/snippets/mapping_custom_source.py 238``` 239 240### Custom target 241 242Implement the `remotivelabs.topology.mapping.Target` protocol — a class with a 243single `publish()` async method — to plug a custom destination (VISSR, websocket, 244file, ...) into a mapping. Constructed like a custom source — `__init__(self, address)` 245or `__init__(self, address, args)` with dependencies passed at registration (group them 246in a dataclass; `remotivelabs.topology.mapping.TargetArgs` is the optional 247convention base). Registering a built-in type (e.g. `"can"`) overrides the default 248broker-backed target for entries that involve a custom address. 249 250Example — broker scripted namespace (VSS) forwarded to a VISSR server 251(see `tests/fixtures/mappings/vss_namespace_to_vissr.gateway-mapping.yaml`): 252 253```yaml 254- source: 255 type: custom.vss # user-defined — channel below is the broker scripted namespace 256 signal: Vehicle.Speed 257 channel: vss 258 target: 259 type: custom.vissr # user-defined type string — implement the target yourself 260 signal: Vehicle.Speed 261 transform: 262 type: passthrough 263``` 264 265```python 266.. include:: ../_docs/snippets/mapping_custom_target.py 267``` 268 269### Custom transform 270 271Implement a `remotivelabs.topology.mapping.TransformFn` — a callable taking one signal value 272and returning the transformed value — for logic the built-in transforms can't express. 273Constructed like a custom source or target (`__init__(self, transform)` plus an optional 274`args` for dependencies), so instances may hold per-entry state: a toggle, a counter, a 275debounce. Custom transforms run in their own flow even between built-in channels. 276 277Mapping file: 278 279```yaml 280- source: 281 type: can 282 frame: HazardSwitch 283 signal: HazardRequest 284 channel: DriverCan 285 target: 286 type: can 287 frame: TurnLightControl 288 signal: HazardRequest 289 channel: BodyCan0 290 transform: 291 type: custom.hazard_toggle # toggle state machine — registered in code 292 initial: 0 # custom field → transform["initial"] 293``` 294 295Application code: 296 297```python 298.. include:: ../_docs/snippets/mapping_custom_transform.py 299``` 300 301### Mappings + your own ECU logic 302 303Use this when an ECU needs code that doesn't fit the `Source` / `Target` / `TransformFn` 304protocols — logic spanning multiple signals, frame context, or asynchronous side effects — 305in addition to its declarative mappings. 306 307The recommended shape is **two models under the same ECU** in the instance file: one 308container runs the mapping (`remotivelabs.topology.mapping.MappingModel` or the bundled CLI) 309and another runs your custom `remotivelabs.topology.behavioral_model.BehavioralModel` code. 310Each stays simple, and they scale and restart independently. 311 312For a single process, `remotivelabs.topology.mapping.handlers_from_mapping` converts the 313mapping file's signal-level entries into input handlers for a standard `BehavioralModel`; 314register your own callbacks alongside them. It converts only signal-level entries with 315built-in transforms — anything else in the file needs the two-model shape above. 316 317```python 318.. include:: ../_docs/snippets/mapping_behavioral_model.py 319``` 320 321<!-- end-include --> 322""" 323 324try: 325 import pydantic # noqa: F401 326 import yaml # noqa: F401 327except ImportError as e: 328 raise ImportError("remotivelabs.topology.mapping requires the 'mapping' extra: pip install remotivelabs-topology[mapping]") from e 329 330from remotivelabs.topology.mapping import models # re-exported as a submodule so pdoc renders it on its own page # noqa: F401 331from remotivelabs.topology.mapping.forwarder import Forwarder 332from remotivelabs.topology.mapping.handlers import handlers_from_mapping 333from remotivelabs.topology.mapping.loader import load_mapping 334from remotivelabs.topology.mapping.mapping_model import MappingModel 335from remotivelabs.topology.mapping.models import MAPPING_SCHEMA_URL 336from remotivelabs.topology.mapping.sources import Source, SourceArgs, TopologySource 337from remotivelabs.topology.mapping.targets import Target, TargetArgs, TopologyTarget 338from remotivelabs.topology.mapping.transformer import Transformer 339from remotivelabs.topology.mapping.transforms import TransformArgs, TransformFn, linear, lookup, passthrough, transform_fn_from_model 340 341__all__ = [ 342 # Schema models (pydantic) — submodule 343 "models", 344 # Schema identity 345 "MAPPING_SCHEMA_URL", 346 # Entry point 347 "load_mapping", 348 "MappingModel", 349 "handlers_from_mapping", 350 # Transform functions 351 "TransformFn", 352 "TransformArgs", 353 "passthrough", 354 "linear", 355 "lookup", 356 "transform_fn_from_model", 357 # Execution engines 358 "Forwarder", 359 "Transformer", 360 # Source / Target protocols, dependency-bundle bases, and broker reference implementations 361 "Source", 362 "SourceArgs", 363 "Target", 364 "TargetArgs", 365 "TopologySource", 366 "TopologyTarget", 367] 368 369# pdoc carries class/function docstrings through re-exports automatically, but loses docstrings on 370# re-exported type aliases (`Foo = T` followed by `"""..."""`). Restate them here so pdoc picks them up. 371__pdoc__ = { 372 "TransformFn": "Callables that transform one signal value into another, used in mapping flows.", 373}
11def load_mapping(path: Path) -> MappingConfig: 12 """ 13 Load a gateway-mapping YAML file. 14 15 Args: 16 path: Path to the mapping YAML file. 17 18 Returns: 19 Parsed and validated MappingConfig. 20 21 Raises: 22 ValueError: If the file does not contain a YAML mapping. 23 pydantic.ValidationError: If the mapping file fails structural validation. 24 """ 25 with open(path, encoding="utf-8") as f: 26 data = yaml.safe_load(f) 27 28 if not isinstance(data, dict): 29 raise ValueError(f"Expected a YAML mapping, got {type(data).__name__}") 30 31 return MappingConfig.model_validate(data)
Load a gateway-mapping YAML file.
Arguments:
- path: Path to the mapping YAML file.
Returns:
Parsed and validated MappingConfig.
Raises:
- ValueError: If the file does not contain a YAML mapping.
- pydantic.ValidationError: If the mapping file fails structural validation.
282class MappingModel: 283 """ 284 Loads a mapping file and runs its message forwarding, signal transforms, and registered custom flows. 285 286 Example instance YAML entry: 287 288 ```yaml 289 ecus: 290 zc: 291 models: 292 zc-fw: 293 type: container 294 container: 295 command: python -m remotivelabs.topology.cli.mapping --mapping my-custom.gateway-mapping.yaml --loglevel DEBUG 296 ``` 297 298 Delegates message-level entries to `Forwarder` (zero-decode passthrough) and signal-level 299 entries to `Transformer` (decode + transform + publish). Entries with custom source, target, 300 or transform types run when a factory is registered via `register_source` / `register_target` 301 / `register_transform`; entries with an unregistered custom type are skipped with a warning. 302 303 Output is protocol- and cadence-aware, driven by the mapping's declared address types and each 304 target frame's cycle time: cyclic CAN targets get a restbus and LIN targets a frame cache 305 (time-decoupled, COM-style gatewaying — sources feeding only such targets subscribe 306 `on_change`), while ethernet PDUs and cycle-less CAN frames are relayed one-shot per received 307 message (PduR-style gatewaying). `MappingModel` builds the managed namespaces and owns their 308 lifecycle. 309 310 `ecu` resolves each mapping `channel` to a broker namespace (default the 311 `topology` catch-all; pass the ECU name for a gateway, or an empty string for flat namespaces). 312 313 `broker_client` may be `None` for fully custom mappings (every source and target registered); 314 `run_forever()` raises if the mapping needs the broker and none was given. 315 """ 316 317 def __init__(self, config: MappingConfig, broker_client: BrokerClient | None = None, *, ecu: str = DEFAULT_ECU) -> None: 318 self._config = config 319 self._broker_client = broker_client 320 self._ecu = ecu 321 self._sources: dict[str, SourceFactory] = {} 322 self._targets: dict[str, TargetFactory] = {} 323 self._transforms: dict[str, TransformFactory] = {} 324 325 @classmethod 326 def from_mapping_file(cls, path: Path, broker_client: BrokerClient | None = None, *, ecu: str = DEFAULT_ECU) -> MappingModel: 327 """Load from a gateway-mapping YAML file.""" 328 return cls(load_mapping(path), broker_client, ecu=ecu) 329 330 @overload 331 def register_source(self, type: str, factory: Callable[[SignalAddress], Source]) -> None: ... 332 @overload 333 def register_source(self, type: str, factory: Callable[[SignalAddress, _A], Source], args: _A) -> None: ... 334 335 def register_source(self, type: str, factory: Callable[..., Source], args: Any = _UNSET) -> None: # noqa: A002 — mirrors the YAML `type` field 336 """ 337 Register a `Source` class (or factory) for an address `type` (e.g. `"custom.evdev"`). 338 339 It is constructed once per mapping entry with the entry's source address — authored YAML 340 fields are read with `address["field"]`. Dependencies go in `args`, passed as the second 341 constructor argument: a plain class with `__init__(self, address)` or `__init__(self, address, args)` 342 is all it takes (group several dependencies in a small dataclass — subclassing 343 `remotivelabs.topology.mapping.SourceArgs` is an optional convention). Register before 344 `run_forever()`. 345 """ 346 self._sources[type] = factory if args is _UNSET else (lambda address: factory(address, args)) 347 348 @overload 349 def register_target(self, type: str, factory: Callable[[SignalAddress], Target]) -> None: ... 350 @overload 351 def register_target(self, type: str, factory: Callable[[SignalAddress, _A], Target], args: _A) -> None: ... 352 353 def register_target(self, type: str, factory: Callable[..., Target], args: Any = _UNSET) -> None: # noqa: A002 — mirrors the YAML `type` field 354 """ 355 Register a `Target` class (or factory) for an address `type` (e.g. `"custom.vissr"`). 356 357 Constructed once per mapping entry with the entry's target address; dependencies go in `args`, 358 passed as the second constructor argument (see `register_source`). Registering a built-in 359 type (e.g. `"can"`) overrides the default broker-backed target for entries that involve a 360 custom address — the registered target then owns that output entirely (no broker namespace is 361 created for it). Register before `run_forever()`. 362 """ 363 self._targets[type] = factory if args is _UNSET else (lambda address: factory(address, args)) 364 365 @overload 366 def register_transform(self, type: str, factory: Callable[[CustomTransform], TransformFn]) -> None: ... 367 @overload 368 def register_transform(self, type: str, factory: Callable[[CustomTransform, _A], TransformFn], args: _A) -> None: ... 369 370 def register_transform(self, type: str, factory: Callable[..., TransformFn], args: Any = _UNSET) -> None: # noqa: A002 — mirrors the YAML `type` field 371 """ 372 Register a transform class (or factory) for a transform `type` (e.g. `"custom.toggle"`). 373 374 Constructed once per mapping entry with the entry's transform model — authored YAML fields 375 are read with `transform["field"]` — and called once per value (`__call__(self, value)` 376 returning the transformed value; instances may hold state, e.g. a toggle). Dependencies go 377 in `args`, passed as the second constructor argument (see `register_source`). Register 378 before `run_forever()`. 379 """ 380 self._transforms[type] = factory if args is _UNSET else (lambda transform: factory(transform, args)) 381 382 async def _open_target_namespaces(self, broker_client: BrokerClient, uses: dict[str, _NamespaceUse]) -> dict[str, TargetNamespace]: 383 """Build, open, and start the target namespace for every namespace the mapping writes to.""" 384 opened: dict[str, TargetNamespace] = {} 385 try: 386 for name, use in uses.items(): 387 if not use.messages: 388 continue # source-only: subscribed to by name, nothing to open for writing 389 target = await _target_namespace(broker_client, name, use) 390 opened[name] = target # recorded before any await, so a failure or cancellation mid-setup still closes it 391 await target.namespace.open() 392 if isinstance(target.namespace, CanNamespace) and target.cyclic_messages: 393 await target.namespace.restbus.start() 394 except BaseException: 395 # Close what was opened — including on cancellation, which is not an Exception. A started 396 # restbus must not keep transmitting from an abandoned attempt while the reconnect loop retries. 397 for target in opened.values(): 398 try: 399 await target.namespace.close() 400 except Exception: 401 _logger.debug("error closing namespace %s after failed build", target.namespace.name, exc_info=True) 402 raise 403 return opened 404 405 def _build_runnables(self, config: MappingConfig, target_namespaces: Mapping[str, TargetNamespace]) -> list[Runnable]: 406 """Build the engines (broker-backed entries) and pipes (registered custom flows) to run.""" 407 engines: list[Forwarder | Transformer] = [] 408 if self._broker_client is not None: 409 forwarder = Forwarder.from_mapping(config, self._broker_client, ecu=self._ecu, target_namespaces=target_namespaces) 410 transformer = Transformer.from_mapping(config, self._broker_client, ecu=self._ecu, target_namespaces=target_namespaces) 411 engines = [engine for engine in (forwarder, transformer) if engine.has_routes] 412 # Pipes write built-in targets through the same per-message publishers as the engines, so a 413 # cycle-less CAN target is relayed rather than parked in a restbus that never transmits it. 414 publisher_for = make_publisher_cache(self._broker_client, target_namespaces) if self._broker_client is not None else None 415 pipes = Pipe.from_mapping( 416 config, 417 self._broker_client, 418 publisher_for=publisher_for, 419 ecu=self._ecu, 420 sources=self._sources, 421 targets=self._targets, 422 transforms=self._transforms, 423 ) 424 return [*engines, *pipes] 425 426 @property 427 def _registrations(self) -> _Registrations: 428 return _Registrations(frozenset(self._sources), frozenset(self._targets), frozenset(self._transforms)) 429 430 async def _resolve(self, broker_client: BrokerClient) -> ResolvedMapping: 431 """Bind the mapping to the broker's current namespaces.""" 432 available = {namespace.name for namespace in await broker_client.list_namespaces()} 433 return ResolvedMapping.resolve(self._config, self._ecu, available, self._registrations) 434 435 async def run_forever(self) -> None: 436 """ 437 Run forwarding, transform, and registered custom flows indefinitely, reconnecting on transient errors. 438 439 Entries referencing namespaces the broker does not have are skipped with one aggregated 440 warning — a platform-generated mapping may cover more channels than the topology wires up. 441 The mapping is re-resolved on every reconnect attempt, so namespaces that appear later are 442 picked up. 443 444 Raises: 445 ValueError: If the mapping contains broker-backed entries but no `broker_client` was 446 given, or a namespace resolves under two different channel types. 447 """ 448 # Config errors (channel-type conflicts, missing broker client) surface here, before the retry loop. 449 uses = _namespace_uses(self._config, self._ecu, self._registrations) 450 if self._broker_client is None and uses: 451 raise ValueError("mapping contains broker-backed entries but no broker_client was given") 452 453 while True: 454 config = self._config 455 target_namespaces: dict[str, TargetNamespace] = {} 456 try: 457 if self._broker_client is not None and uses: 458 resolved = await self._resolve(self._broker_client) 459 if resolved.skipped: 460 _logger.warning("%s", resolved.skipped) 461 config = resolved.config 462 target_namespaces = await self._open_target_namespaces(self._broker_client, resolved.namespace_uses) 463 runnables = self._build_runnables(config, target_namespaces) 464 if not runnables: 465 _logger.warning("MappingModel has no routes — nothing to forward or transform") 466 return 467 await Pipeline(runnables).run_forever() 468 except asyncio.CancelledError: 469 raise 470 except Exception: 471 _logger.warning("MappingModel error — reconnecting in %.1fs", _RECONNECT_DELAY_S, exc_info=True) 472 await asyncio.sleep(_RECONNECT_DELAY_S) 473 finally: 474 for target in target_namespaces.values(): 475 try: 476 await target.namespace.close() 477 except Exception: 478 _logger.debug("error closing namespace %s", target.namespace.name, exc_info=True)
Loads a mapping file and runs its message forwarding, signal transforms, and registered custom flows.
Example instance YAML entry:
ecus:
zc:
models:
zc-fw:
type: container
container:
command: python -m remotivelabs.topology.cli.mapping --mapping my-custom.gateway-mapping.yaml --loglevel DEBUG
Delegates message-level entries to Forwarder (zero-decode passthrough) and signal-level
entries to Transformer (decode + transform + publish). Entries with custom source, target,
or transform types run when a factory is registered via register_source / register_target
/ register_transform; entries with an unregistered custom type are skipped with a warning.
Output is protocol- and cadence-aware, driven by the mapping's declared address types and each
target frame's cycle time: cyclic CAN targets get a restbus and LIN targets a frame cache
(time-decoupled, COM-style gatewaying — sources feeding only such targets subscribe
on_change), while ethernet PDUs and cycle-less CAN frames are relayed one-shot per received
message (PduR-style gatewaying). MappingModel builds the managed namespaces and owns their
lifecycle.
ecu resolves each mapping channel to a broker namespace (default the
topology catch-all; pass the ECU name for a gateway, or an empty string for flat namespaces).
broker_client may be None for fully custom mappings (every source and target registered);
run_forever() raises if the mapping needs the broker and none was given.
317 def __init__(self, config: MappingConfig, broker_client: BrokerClient | None = None, *, ecu: str = DEFAULT_ECU) -> None: 318 self._config = config 319 self._broker_client = broker_client 320 self._ecu = ecu 321 self._sources: dict[str, SourceFactory] = {} 322 self._targets: dict[str, TargetFactory] = {} 323 self._transforms: dict[str, TransformFactory] = {}
325 @classmethod 326 def from_mapping_file(cls, path: Path, broker_client: BrokerClient | None = None, *, ecu: str = DEFAULT_ECU) -> MappingModel: 327 """Load from a gateway-mapping YAML file.""" 328 return cls(load_mapping(path), broker_client, ecu=ecu)
Load from a gateway-mapping YAML file.
335 def register_source(self, type: str, factory: Callable[..., Source], args: Any = _UNSET) -> None: # noqa: A002 — mirrors the YAML `type` field 336 """ 337 Register a `Source` class (or factory) for an address `type` (e.g. `"custom.evdev"`). 338 339 It is constructed once per mapping entry with the entry's source address — authored YAML 340 fields are read with `address["field"]`. Dependencies go in `args`, passed as the second 341 constructor argument: a plain class with `__init__(self, address)` or `__init__(self, address, args)` 342 is all it takes (group several dependencies in a small dataclass — subclassing 343 `remotivelabs.topology.mapping.SourceArgs` is an optional convention). Register before 344 `run_forever()`. 345 """ 346 self._sources[type] = factory if args is _UNSET else (lambda address: factory(address, args))
Register a Source class (or factory) for an address type (e.g. "custom.evdev").
It is constructed once per mapping entry with the entry's source address — authored YAML
fields are read with address["field"]. Dependencies go in args, passed as the second
constructor argument: a plain class with __init__(self, address) or __init__(self, address, args)
is all it takes (group several dependencies in a small dataclass — subclassing
remotivelabs.topology.mapping.SourceArgs is an optional convention). Register before
run_forever().
353 def register_target(self, type: str, factory: Callable[..., Target], args: Any = _UNSET) -> None: # noqa: A002 — mirrors the YAML `type` field 354 """ 355 Register a `Target` class (or factory) for an address `type` (e.g. `"custom.vissr"`). 356 357 Constructed once per mapping entry with the entry's target address; dependencies go in `args`, 358 passed as the second constructor argument (see `register_source`). Registering a built-in 359 type (e.g. `"can"`) overrides the default broker-backed target for entries that involve a 360 custom address — the registered target then owns that output entirely (no broker namespace is 361 created for it). Register before `run_forever()`. 362 """ 363 self._targets[type] = factory if args is _UNSET else (lambda address: factory(address, args))
Register a Target class (or factory) for an address type (e.g. "custom.vissr").
Constructed once per mapping entry with the entry's target address; dependencies go in args,
passed as the second constructor argument (see register_source). Registering a built-in
type (e.g. "can") overrides the default broker-backed target for entries that involve a
custom address — the registered target then owns that output entirely (no broker namespace is
created for it). Register before run_forever().
370 def register_transform(self, type: str, factory: Callable[..., TransformFn], args: Any = _UNSET) -> None: # noqa: A002 — mirrors the YAML `type` field 371 """ 372 Register a transform class (or factory) for a transform `type` (e.g. `"custom.toggle"`). 373 374 Constructed once per mapping entry with the entry's transform model — authored YAML fields 375 are read with `transform["field"]` — and called once per value (`__call__(self, value)` 376 returning the transformed value; instances may hold state, e.g. a toggle). Dependencies go 377 in `args`, passed as the second constructor argument (see `register_source`). Register 378 before `run_forever()`. 379 """ 380 self._transforms[type] = factory if args is _UNSET else (lambda transform: factory(transform, args))
Register a transform class (or factory) for a transform type (e.g. "custom.toggle").
Constructed once per mapping entry with the entry's transform model — authored YAML fields
are read with transform["field"] — and called once per value (__call__(self, value)
returning the transformed value; instances may hold state, e.g. a toggle). Dependencies go
in args, passed as the second constructor argument (see register_source). Register
before run_forever().
435 async def run_forever(self) -> None: 436 """ 437 Run forwarding, transform, and registered custom flows indefinitely, reconnecting on transient errors. 438 439 Entries referencing namespaces the broker does not have are skipped with one aggregated 440 warning — a platform-generated mapping may cover more channels than the topology wires up. 441 The mapping is re-resolved on every reconnect attempt, so namespaces that appear later are 442 picked up. 443 444 Raises: 445 ValueError: If the mapping contains broker-backed entries but no `broker_client` was 446 given, or a namespace resolves under two different channel types. 447 """ 448 # Config errors (channel-type conflicts, missing broker client) surface here, before the retry loop. 449 uses = _namespace_uses(self._config, self._ecu, self._registrations) 450 if self._broker_client is None and uses: 451 raise ValueError("mapping contains broker-backed entries but no broker_client was given") 452 453 while True: 454 config = self._config 455 target_namespaces: dict[str, TargetNamespace] = {} 456 try: 457 if self._broker_client is not None and uses: 458 resolved = await self._resolve(self._broker_client) 459 if resolved.skipped: 460 _logger.warning("%s", resolved.skipped) 461 config = resolved.config 462 target_namespaces = await self._open_target_namespaces(self._broker_client, resolved.namespace_uses) 463 runnables = self._build_runnables(config, target_namespaces) 464 if not runnables: 465 _logger.warning("MappingModel has no routes — nothing to forward or transform") 466 return 467 await Pipeline(runnables).run_forever() 468 except asyncio.CancelledError: 469 raise 470 except Exception: 471 _logger.warning("MappingModel error — reconnecting in %.1fs", _RECONNECT_DELAY_S, exc_info=True) 472 await asyncio.sleep(_RECONNECT_DELAY_S) 473 finally: 474 for target in target_namespaces.values(): 475 try: 476 await target.namespace.close() 477 except Exception: 478 _logger.debug("error closing namespace %s", target.namespace.name, exc_info=True)
Run forwarding, transform, and registered custom flows indefinitely, reconnecting on transient errors.
Entries referencing namespaces the broker does not have are skipped with one aggregated warning — a platform-generated mapping may cover more channels than the topology wires up. The mapping is re-resolved on every reconnect attempt, so namespaces that appear later are picked up.
Raises:
- ValueError: If the mapping contains broker-backed entries but no
broker_clientwas given, or a namespace resolves under two different channel types.
77def handlers_from_mapping( 78 config: MappingConfig, 79 channel_map: dict[str, _HasName | str], 80) -> list[tuple[NamespaceName, InputHandler]]: 81 """ 82 Convert signal-level entries with built-in addresses in a MappingConfig into InputHandlers. 83 84 Designed for use with BehavioralModel: 85 86 ```python 87 bm = BehavioralModel( 88 "RLCM", 89 namespaces=[can_ns, lin_ns], 90 input_handlers=[ 91 *handlers_from_mapping(config, {"BodyCan0": can_ns, "lin0": lin_ns}), 92 can_ns.create_input_handler([FrameFilter("BrakeLightControl")], self.on_brake), 93 ], 94 ) 95 ``` 96 97 Fan-out entries produce one handler per (source, target) pair. A `lookup` transform with no 98 entry for an incoming value logs a warning and skips that value. 99 100 Entries with custom transforms are skipped with a warning — run those via 101 `MappingModel.register_transform`. Message-level entries (`RouteEntry` / `MessageMappingEntry`) 102 and custom (`custom.`-prefixed) addresses are silently skipped (handled by Forwarder or caller). 103 104 Note: this only covers signal-level entries with built-in transforms — message-level entries in 105 the same mapping file are dropped here. For mixed files the recommended shape is two models under 106 the same ECU in the instance file: a `MappingModel` container for the mapping and a 107 `BehavioralModel` container for the custom code. 108 109 Args: 110 config: Loaded MappingConfig. 111 channel_map: Maps the bare channel name (from the YAML) to a Namespace or broker namespace string. 112 Returns: 113 List of (target namespace, InputHandler) tuples to be registered on the BehavioralModel. 114 """ 115 result: list[tuple[NamespaceName, InputHandler]] = [] 116 117 def _ns_name(v: _HasName | str) -> str: 118 return v if isinstance(v, str) else v.name 119 120 for entry in config.mappings: 121 if not isinstance(entry, SignalMappingEntry): 122 continue # message-level entries (RouteEntry / MessageMappingEntry) → Forwarder 123 124 if isinstance(entry.transform, CustomTransform): 125 _logger.warning( 126 "custom transform %r on %s → %s: not supported by handlers_from_mapping — run it via MappingModel.register_transform", 127 entry.transform.type, 128 _describe_address(entry.source), 129 ", ".join(_describe_address(t) for t in entry.targets), 130 ) 131 continue 132 133 if not isinstance(entry.source, BuiltinSignalAddress): 134 continue 135 if entry.source.channel not in channel_map: 136 continue 137 138 for target in entry.targets: 139 if not isinstance(target, BuiltinSignalAddress): 140 continue 141 if target.channel not in channel_map: 142 continue 143 144 handler: InputHandler = _SignalMappingHandler( 145 source_frame=message_name(entry.source), 146 source_signal=entry.source.signal, 147 target_ns=_ns_name(channel_map[target.channel]), 148 target_signal=target.signal, 149 transform_fn=transform_fn_from_model(entry.transform), 150 ) 151 result.append((_ns_name(channel_map[entry.source.channel]), handler)) 152 153 return result
Convert signal-level entries with built-in addresses in a MappingConfig into InputHandlers.
Designed for use with BehavioralModel:
bm = BehavioralModel(
"RLCM",
namespaces=[can_ns, lin_ns],
input_handlers=[
*handlers_from_mapping(config, {"BodyCan0": can_ns, "lin0": lin_ns}),
can_ns.create_input_handler([FrameFilter("BrakeLightControl")], self.on_brake),
],
)
Fan-out entries produce one handler per (source, target) pair. A lookup transform with no
entry for an incoming value logs a warning and skips that value.
Entries with custom transforms are skipped with a warning — run those via
MappingModel.register_transform. Message-level entries (RouteEntry / MessageMappingEntry)
and custom (custom.-prefixed) addresses are silently skipped (handled by Forwarder or caller).
Note: this only covers signal-level entries with built-in transforms — message-level entries in
the same mapping file are dropped here. For mixed files the recommended shape is two models under
the same ECU in the instance file: a MappingModel container for the mapping and a
BehavioralModel container for the custom code.
Arguments:
- config: Loaded MappingConfig.
- channel_map: Maps the bare channel name (from the YAML) to a Namespace or broker namespace string.
Returns:
List of (target namespace, InputHandler) tuples to be registered on the BehavioralModel.
25@dataclass 26class TransformArgs: 27 """ 28 Optional convention base for a custom transform's dependency bundle. 29 30 Group the dependencies your transform needs in a small dataclass and pass it as `args` to 31 `remotivelabs.topology.mapping.MappingModel.register_transform` — it arrives as the 32 constructor's second argument. Subclassing this is optional; any object works. 33 """
Optional convention base for a custom transform's dependency bundle.
Group the dependencies your transform needs in a small dataclass and pass it as args to
remotivelabs.topology.mapping.MappingModel.register_transform — it arrives as the
constructor's second argument. Subclassing this is optional; any object works.
36def passthrough(value: SignalValue) -> SignalValue: 37 """Return value unchanged.""" 38 return value
Return value unchanged.
41def linear(factor: float, offset: float = 0.0, min: float | None = None, max: float | None = None) -> TransformFn: 42 """ 43 Return a transform that computes: output = clamp(factor * input + offset, min, max). 44 45 Args: 46 factor: Scaling factor. Required. 47 offset: Offset added after scaling. Default 0. 48 min: Optional lower clamp on output. 49 max: Optional upper clamp on output. 50 """ 51 52 def _apply(value: SignalValue) -> SignalValue: 53 result = factor * float(value) + offset # type: ignore[arg-type] 54 if min is not None and result < min: 55 result = min 56 if max is not None and result > max: 57 result = max 58 return result 59 60 return _apply
Return a transform that computes: output = clamp(factor * input + offset, min, max).
Arguments:
- factor: Scaling factor. Required.
- offset: Offset added after scaling. Default 0.
- min: Optional lower clamp on output.
- max: Optional upper clamp on output.
63def lookup(mapping: dict[int, int]) -> TransformFn: 64 """ 65 Return a transform that remaps discrete integer values via a lookup table. 66 67 Args: 68 mapping: Dict mapping input integer values to output integer values. 69 70 Raises: 71 KeyError: At call time if the input value is not in the mapping. Framework engines 72 (`remotivelabs.topology.mapping.Transformer`, `remotivelabs.topology.mapping.handlers_from_mapping`) 73 catch this per message, log a warning, and skip publishing that value. 74 """ 75 76 def _apply(value: SignalValue) -> SignalValue: 77 return mapping[int(value)] # type: ignore[arg-type] 78 79 return _apply
Return a transform that remaps discrete integer values via a lookup table.
Arguments:
- mapping: Dict mapping input integer values to output integer values.
Raises:
- KeyError: At call time if the input value is not in the mapping. Framework engines
(
remotivelabs.topology.mapping.Transformer,remotivelabs.topology.mapping.handlers_from_mapping) catch this per message, log a warning, and skip publishing that value.
82def transform_fn_from_model(t: Transform) -> TransformFn: 83 """ 84 Convert a built-in transform model to its `remotivelabs.topology.mapping.TransformFn` callable form. 85 86 Used by the engines and by application code that wants the same dispatch as the framework. 87 88 Raises: 89 ValueError: For `remotivelabs.topology.mapping.models.CustomTransform` — custom transforms 90 are resolved through the `remotivelabs.topology.mapping.MappingModel.register_transform` 91 registry, never here. 92 """ 93 if isinstance(t, PassthroughTransform): 94 return passthrough 95 if isinstance(t, LinearTransform): 96 return linear(t.factor, t.offset, t.min, t.max) 97 if isinstance(t, LookupTransform): 98 return lookup(t.mapping) 99 if isinstance(t, CustomTransform): 100 raise ValueError(f"custom transform {t.type!r} must be resolved via register_transform, not here") 101 raise ValueError(f"unsupported transform type: {type(t).__name__}")
Convert a built-in transform model to its remotivelabs.topology.mapping.TransformFn callable form.
Used by the engines and by application code that wants the same dispatch as the framework.
Raises:
- ValueError: For
remotivelabs.topology.mapping.models.CustomTransform— custom transforms are resolved through theremotivelabs.topology.mapping.MappingModel.register_transformregistry, never here.
77class Forwarder: 78 """ 79 Forwards messages between broker channels based on a routing table. 80 81 Supports CAN, LIN, and Ethernet PDU channels. No per-signal decode, no transforms. 82 83 Use `from_mapping()` to construct from a MappingConfig, or pass the routes directly if you 84 need to build them programmatically. 85 86 How a target message is published is decided by whether its namespace transmits it 87 cyclically, which `target_namespaces` (supplied by `remotivelabs.topology.mapping.MappingModel`) 88 records per namespace: 89 90 - **cyclic target** (a CAN frame with a cycle time in its database, or any LIN frame): the 91 value is held and transmitted at the target's own cycle — restbus for CAN, cache for LIN. 92 This is COM-style gatewaying; the source is subscribed `on_change`, so repeated identical 93 frames are not re-forwarded. 94 - **everything else** (sporadic CAN frames, ethernet PDUs): relayed one-shot, once per received 95 message, repeats included. This is PduR-style gatewaying — a restbus never transmits a frame 96 without a cycle time, so holding such a message would silently drop the relay. 97 98 Without `target_namespaces`, every message is relayed with a plain one-shot publish. 99 """ 100 101 def __init__( 102 self, 103 routes: _RoutingTable, 104 broker_client: BrokerClient, 105 *, 106 target_namespaces: Mapping[str, TargetNamespace] | None = None, 107 ) -> None: 108 self._routes = routes 109 self._broker_client = broker_client 110 111 publisher_for = make_publisher_cache(broker_client, target_namespaces) 112 self._plan: _PublishPlan = {} 113 self._on_change: dict[Route, bool] = {} 114 for source, targets in routes.items(): 115 self._plan[source] = [(publisher_for(tgt_namespace, tgt_message), tgt_message) for tgt_message, tgt_namespace in targets] 116 # on_change only when every target is transmitted cyclically (restbus/cache keeps the 117 # value alive); otherwise this is a relay and every frame must be forwarded. 118 self._on_change[source] = target_namespaces is not None and all_cyclic( 119 target_namespaces, ((tgt_namespace, tgt_message) for tgt_message, tgt_namespace in targets) 120 ) 121 122 @classmethod 123 def from_mapping( 124 cls, 125 config: MappingConfig, 126 broker_client: BrokerClient, 127 *, 128 ecu: str = DEFAULT_ECU, 129 target_namespaces: Mapping[str, TargetNamespace] | None = None, 130 ) -> Forwarder: 131 """ 132 Build a Forwarder from a unified gateway-mapping config. 133 134 Message-level entries (`RouteEntry` and `MessageMappingEntry`) are included; each built-in 135 message address in `MessageMappingEntry.targets` becomes a destination (fan-out). Signal-level 136 entries and custom addresses are silently skipped. 137 138 `ecu` resolves each `channel` to a broker namespace (default the `topology` 139 catch-all; pass the ECU name for a gateway, or an empty string for flat namespaces). 140 `target_namespaces` says, per broker namespace, which messages it transmits cyclically — 141 see the class docstring for how that decides the write path. 142 """ 143 return cls(_routes_from_mapping(config, ecu), broker_client, target_namespaces=target_namespaces) 144 145 @property 146 def has_routes(self) -> bool: 147 """Whether the config produced anything to forward.""" 148 return bool(self._routes) 149 150 async def _handle_frame(self, frame: Frame) -> None: 151 for publish, tgt_message in self._plan.get((frame.name, frame.namespace), ()): 152 await publish(tgt_message, frame.value) 153 154 async def run_forever(self) -> None: 155 """Subscribe to all source channels and forward messages to their targets indefinitely.""" 156 if not self._routes: 157 _logger.warning("Forwarder has no routes — nothing to forward") 158 return 159 await consume_subscriptions(self._broker_client, self._on_change, self._handle_frame, owner="Forwarder")
Forwards messages between broker channels based on a routing table.
Supports CAN, LIN, and Ethernet PDU channels. No per-signal decode, no transforms.
Use from_mapping() to construct from a MappingConfig, or pass the routes directly if you
need to build them programmatically.
How a target message is published is decided by whether its namespace transmits it
cyclically, which target_namespaces (supplied by remotivelabs.topology.mapping.MappingModel)
records per namespace:
- cyclic target (a CAN frame with a cycle time in its database, or any LIN frame): the
value is held and transmitted at the target's own cycle — restbus for CAN, cache for LIN.
This is COM-style gatewaying; the source is subscribed
on_change, so repeated identical frames are not re-forwarded. - everything else (sporadic CAN frames, ethernet PDUs): relayed one-shot, once per received message, repeats included. This is PduR-style gatewaying — a restbus never transmits a frame without a cycle time, so holding such a message would silently drop the relay.
Without target_namespaces, every message is relayed with a plain one-shot publish.
101 def __init__( 102 self, 103 routes: _RoutingTable, 104 broker_client: BrokerClient, 105 *, 106 target_namespaces: Mapping[str, TargetNamespace] | None = None, 107 ) -> None: 108 self._routes = routes 109 self._broker_client = broker_client 110 111 publisher_for = make_publisher_cache(broker_client, target_namespaces) 112 self._plan: _PublishPlan = {} 113 self._on_change: dict[Route, bool] = {} 114 for source, targets in routes.items(): 115 self._plan[source] = [(publisher_for(tgt_namespace, tgt_message), tgt_message) for tgt_message, tgt_namespace in targets] 116 # on_change only when every target is transmitted cyclically (restbus/cache keeps the 117 # value alive); otherwise this is a relay and every frame must be forwarded. 118 self._on_change[source] = target_namespaces is not None and all_cyclic( 119 target_namespaces, ((tgt_namespace, tgt_message) for tgt_message, tgt_namespace in targets) 120 )
122 @classmethod 123 def from_mapping( 124 cls, 125 config: MappingConfig, 126 broker_client: BrokerClient, 127 *, 128 ecu: str = DEFAULT_ECU, 129 target_namespaces: Mapping[str, TargetNamespace] | None = None, 130 ) -> Forwarder: 131 """ 132 Build a Forwarder from a unified gateway-mapping config. 133 134 Message-level entries (`RouteEntry` and `MessageMappingEntry`) are included; each built-in 135 message address in `MessageMappingEntry.targets` becomes a destination (fan-out). Signal-level 136 entries and custom addresses are silently skipped. 137 138 `ecu` resolves each `channel` to a broker namespace (default the `topology` 139 catch-all; pass the ECU name for a gateway, or an empty string for flat namespaces). 140 `target_namespaces` says, per broker namespace, which messages it transmits cyclically — 141 see the class docstring for how that decides the write path. 142 """ 143 return cls(_routes_from_mapping(config, ecu), broker_client, target_namespaces=target_namespaces)
Build a Forwarder from a unified gateway-mapping config.
Message-level entries (RouteEntry and MessageMappingEntry) are included; each built-in
message address in MessageMappingEntry.targets becomes a destination (fan-out). Signal-level
entries and custom addresses are silently skipped.
ecu resolves each channel to a broker namespace (default the topology
catch-all; pass the ECU name for a gateway, or an empty string for flat namespaces).
target_namespaces says, per broker namespace, which messages it transmits cyclically —
see the class docstring for how that decides the write path.
145 @property 146 def has_routes(self) -> bool: 147 """Whether the config produced anything to forward.""" 148 return bool(self._routes)
Whether the config produced anything to forward.
154 async def run_forever(self) -> None: 155 """Subscribe to all source channels and forward messages to their targets indefinitely.""" 156 if not self._routes: 157 _logger.warning("Forwarder has no routes — nothing to forward") 158 return 159 await consume_subscriptions(self._broker_client, self._on_change, self._handle_frame, owner="Forwarder")
Subscribe to all source channels and forward messages to their targets indefinitely.
43class Transformer: 44 """ 45 Applies signal-level transforms between broker channels. 46 47 Subscribes once per source broker channel, covering all messages any signal-level 48 `remotivelabs.topology.mapping.models.SignalMappingEntry` needs on that channel. For each incoming message, 49 looks up routes keyed by `(message_name, channel)`, extracts the signal value, runs the transform, 50 and calls the route's publish callable. A `lookup` transform that has no entry for an incoming 51 value logs a warning and skips that value — the loop never crashes on unmapped values. 52 53 When `target_namespaces` is supplied (by `remotivelabs.topology.mapping.MappingModel`) the 54 target is written the way its cadence calls for — a message its namespace transmits cyclically 55 (a cyclic CAN frame via the restbus, a LIN frame via the cache) is held, with unchanged values 56 skipped; ethernet PDUs and cycle-less CAN frames are published one-shot. Otherwise a plain 57 one-shot publish is used. Peer to `remotivelabs.topology.mapping.Forwarder`, which handles 58 message-level passthrough. 59 """ 60 61 def __init__( 62 self, 63 routes: _RoutingTable, 64 broker_client: BrokerClient, 65 *, 66 on_change: dict[tuple[MessageName, Channel], bool] | None = None, 67 ) -> None: 68 self._routes = routes 69 self._broker_client = broker_client 70 # on_change defaults to off for every source (safe passthrough) when not provided. 71 self._on_change = on_change or {key: False for key in routes} 72 73 @classmethod 74 def from_mapping( 75 cls, 76 config: MappingConfig, 77 broker_client: BrokerClient, 78 *, 79 ecu: str = DEFAULT_ECU, 80 target_namespaces: Mapping[str, TargetNamespace] | None = None, 81 ) -> Transformer: 82 """ 83 Build a Transformer from a gateway-mapping config. 84 85 `ecu` resolves each `channel` to a broker namespace (default the `topology` 86 catch-all; pass the ECU name for a gateway, or an empty string for flat namespaces). 87 `target_namespaces` says, per broker namespace, which messages it transmits cyclically: 88 those targets are written into the restbus/cache and their sources subscribed `on_change`; 89 any other target is published one-shot and its source forwards every frame. 90 91 Includes only `remotivelabs.topology.mapping.models.SignalMappingEntry` rows with a built-in 92 signal address (`CanSignalAddress` / `LinSignalAddress` / `EthernetPduSignalAddress`) as source and a 93 built-in transform. Each built-in signal address in `SignalMappingEntry.targets` 94 becomes a route (fan-out). Skips message-level entries (`RouteEntry` / `MessageMappingEntry` → 95 `Forwarder`), custom addresses, and custom transforms (both run as pipes when registered). 96 """ 97 routes: _RoutingTable = defaultdict(list) 98 target_pairs: dict[tuple[MessageName, Channel], list[tuple[Channel, MessageName]]] = defaultdict(list) 99 publisher_for = make_publisher_cache(broker_client, target_namespaces) 100 101 for entry in config.mappings: 102 if not isinstance(entry, SignalMappingEntry): 103 continue 104 if not isinstance(entry.source, BuiltinSignalAddress): 105 continue 106 if isinstance(entry.transform, CustomTransform): 107 continue # runs as a Pipe when registered — see Pipe.from_mapping 108 109 transform_fn = transform_fn_from_model(entry.transform) 110 source_key = (message_name(entry.source), entry.source.broker_namespace(ecu)) 111 for target in entry.targets: 112 if not isinstance(target, BuiltinSignalAddress): 113 continue 114 target_namespace = target.broker_namespace(ecu) 115 publish = functools.partial(publisher_for(target_namespace, message_name(target)), target.signal) 116 routes[source_key].append(_Route(signal_name=entry.source.signal, transform=transform_fn, publish=publish)) 117 target_pairs[source_key].append((target_namespace, message_name(target))) 118 119 on_change = {key: target_namespaces is not None and all_cyclic(target_namespaces, pairs) for key, pairs in target_pairs.items()} 120 return cls(dict(routes), broker_client, on_change=on_change) 121 122 @property 123 def has_routes(self) -> bool: 124 """Whether the config produced anything to transform.""" 125 return bool(self._routes) 126 127 async def _handle_frame(self, frame: Frame) -> None: 128 for route in self._routes.get((frame.name, frame.namespace), ()): 129 # route.signal_name is the mapping's signal name as-authored. How the broker keys 130 # signals in `frame.signals` is the broker's concern — keep this naming-agnostic; 131 # don't hardcode a message-qualification scheme here. 132 value = frame.signals.get(route.signal_name) 133 if value is None: 134 continue 135 try: 136 transformed = route.transform(value) 137 except KeyError: 138 _logger.warning("No lookup mapping for value %r of %s on %s — skipping", value, route.signal_name, frame.namespace) 139 continue 140 await route.publish(transformed) 141 142 async def run_forever(self) -> None: 143 """Subscribe to all source channels and apply transforms indefinitely.""" 144 if not self._routes: 145 _logger.warning("Transformer has no routes — nothing to transform") 146 return 147 await consume_subscriptions(self._broker_client, self._on_change, self._handle_frame, owner="Transformer")
Applies signal-level transforms between broker channels.
Subscribes once per source broker channel, covering all messages any signal-level
remotivelabs.topology.mapping.models.SignalMappingEntry needs on that channel. For each incoming message,
looks up routes keyed by (message_name, channel), extracts the signal value, runs the transform,
and calls the route's publish callable. A lookup transform that has no entry for an incoming
value logs a warning and skips that value — the loop never crashes on unmapped values.
When target_namespaces is supplied (by remotivelabs.topology.mapping.MappingModel) the
target is written the way its cadence calls for — a message its namespace transmits cyclically
(a cyclic CAN frame via the restbus, a LIN frame via the cache) is held, with unchanged values
skipped; ethernet PDUs and cycle-less CAN frames are published one-shot. Otherwise a plain
one-shot publish is used. Peer to remotivelabs.topology.mapping.Forwarder, which handles
message-level passthrough.
61 def __init__( 62 self, 63 routes: _RoutingTable, 64 broker_client: BrokerClient, 65 *, 66 on_change: dict[tuple[MessageName, Channel], bool] | None = None, 67 ) -> None: 68 self._routes = routes 69 self._broker_client = broker_client 70 # on_change defaults to off for every source (safe passthrough) when not provided. 71 self._on_change = on_change or {key: False for key in routes}
73 @classmethod 74 def from_mapping( 75 cls, 76 config: MappingConfig, 77 broker_client: BrokerClient, 78 *, 79 ecu: str = DEFAULT_ECU, 80 target_namespaces: Mapping[str, TargetNamespace] | None = None, 81 ) -> Transformer: 82 """ 83 Build a Transformer from a gateway-mapping config. 84 85 `ecu` resolves each `channel` to a broker namespace (default the `topology` 86 catch-all; pass the ECU name for a gateway, or an empty string for flat namespaces). 87 `target_namespaces` says, per broker namespace, which messages it transmits cyclically: 88 those targets are written into the restbus/cache and their sources subscribed `on_change`; 89 any other target is published one-shot and its source forwards every frame. 90 91 Includes only `remotivelabs.topology.mapping.models.SignalMappingEntry` rows with a built-in 92 signal address (`CanSignalAddress` / `LinSignalAddress` / `EthernetPduSignalAddress`) as source and a 93 built-in transform. Each built-in signal address in `SignalMappingEntry.targets` 94 becomes a route (fan-out). Skips message-level entries (`RouteEntry` / `MessageMappingEntry` → 95 `Forwarder`), custom addresses, and custom transforms (both run as pipes when registered). 96 """ 97 routes: _RoutingTable = defaultdict(list) 98 target_pairs: dict[tuple[MessageName, Channel], list[tuple[Channel, MessageName]]] = defaultdict(list) 99 publisher_for = make_publisher_cache(broker_client, target_namespaces) 100 101 for entry in config.mappings: 102 if not isinstance(entry, SignalMappingEntry): 103 continue 104 if not isinstance(entry.source, BuiltinSignalAddress): 105 continue 106 if isinstance(entry.transform, CustomTransform): 107 continue # runs as a Pipe when registered — see Pipe.from_mapping 108 109 transform_fn = transform_fn_from_model(entry.transform) 110 source_key = (message_name(entry.source), entry.source.broker_namespace(ecu)) 111 for target in entry.targets: 112 if not isinstance(target, BuiltinSignalAddress): 113 continue 114 target_namespace = target.broker_namespace(ecu) 115 publish = functools.partial(publisher_for(target_namespace, message_name(target)), target.signal) 116 routes[source_key].append(_Route(signal_name=entry.source.signal, transform=transform_fn, publish=publish)) 117 target_pairs[source_key].append((target_namespace, message_name(target))) 118 119 on_change = {key: target_namespaces is not None and all_cyclic(target_namespaces, pairs) for key, pairs in target_pairs.items()} 120 return cls(dict(routes), broker_client, on_change=on_change)
Build a Transformer from a gateway-mapping config.
ecu resolves each channel to a broker namespace (default the topology
catch-all; pass the ECU name for a gateway, or an empty string for flat namespaces).
target_namespaces says, per broker namespace, which messages it transmits cyclically:
those targets are written into the restbus/cache and their sources subscribed on_change;
any other target is published one-shot and its source forwards every frame.
Includes only remotivelabs.topology.mapping.models.SignalMappingEntry rows with a built-in
signal address (CanSignalAddress / LinSignalAddress / EthernetPduSignalAddress) as source and a
built-in transform. Each built-in signal address in SignalMappingEntry.targets
becomes a route (fan-out). Skips message-level entries (RouteEntry / MessageMappingEntry →
Forwarder), custom addresses, and custom transforms (both run as pipes when registered).
122 @property 123 def has_routes(self) -> bool: 124 """Whether the config produced anything to transform.""" 125 return bool(self._routes)
Whether the config produced anything to transform.
142 async def run_forever(self) -> None: 143 """Subscribe to all source channels and apply transforms indefinitely.""" 144 if not self._routes: 145 _logger.warning("Transformer has no routes — nothing to transform") 146 return 147 await consume_subscriptions(self._broker_client, self._on_change, self._handle_frame, owner="Transformer")
Subscribe to all source channels and apply transforms indefinitely.
23class Source(Protocol): 24 """ 25 Contract for a signal source in a mapping flow. 26 27 Implement this protocol to plug a custom data origin (an input device, FMU, 28 websocket, ...) into a mapping, and register it via 29 `remotivelabs.topology.mapping.MappingModel.register_source`. The framework 30 drives the source by iterating `signals()`; each yielded value is fed through 31 the entry's transform and pushed to the target. 32 33 The constructor takes the entry's source address — plus an optional second argument for 34 dependencies passed at registration (`register_source("custom.x", MySource, args)`): 35 36 ```python 37 class MySource: 38 def __init__(self, address: SignalAddress, args: MyArgs) -> None: 39 self._topic = address["topic"] 40 self._client = args.client 41 42 async def signals(self) -> AsyncIterator[SignalValue]: 43 async for raw in self._client.events(self._topic): 44 yield raw.value 45 ``` 46 """ 47 48 # Plain `def` on purpose: implementations are async generators (`async def` + `yield`), whose 49 # `signals()` call returns an AsyncIterator directly — `async def` here would mean a coroutine. 50 def signals(self) -> AsyncIterator[SignalValue]: 51 """Yield signal values until the source is exhausted or cancelled.""" 52 ...
Contract for a signal source in a mapping flow.
Implement this protocol to plug a custom data origin (an input device, FMU,
websocket, ...) into a mapping, and register it via
remotivelabs.topology.mapping.MappingModel.register_source. The framework
drives the source by iterating signals(); each yielded value is fed through
the entry's transform and pushed to the target.
The constructor takes the entry's source address — plus an optional second argument for
dependencies passed at registration (register_source("custom.x", MySource, args)):
class MySource:
def __init__(self, address: SignalAddress, args: MyArgs) -> None:
self._topic = address["topic"]
self._client = args.client
async def signals(self) -> AsyncIterator[SignalValue]:
async for raw in self._client.events(self._topic):
yield raw.value
1945def _no_init_or_replace_init(self, *args, **kwargs): 1946 cls = type(self) 1947 1948 if cls._is_protocol: 1949 raise TypeError('Protocols cannot be instantiated') 1950 1951 # Already using a custom `__init__`. No need to calculate correct 1952 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1953 if cls.__init__ is not _no_init_or_replace_init: 1954 return 1955 1956 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1957 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1958 # searches for a proper new `__init__` in the MRO. The new `__init__` 1959 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1960 # instantiation of the protocol subclass will thus use the new 1961 # `__init__` and no longer call `_no_init_or_replace_init`. 1962 for base in cls.__mro__: 1963 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1964 if init is not _no_init_or_replace_init: 1965 cls.__init__ = init 1966 break 1967 else: 1968 # should not happen 1969 cls.__init__ = object.__init__ 1970 1971 cls.__init__(self, *args, **kwargs)
12@dataclass 13class SourceArgs: 14 """ 15 Optional convention base for a custom source's dependency bundle. 16 17 Group the dependencies your `Source` needs in a small dataclass and pass it as `args` to 18 `remotivelabs.topology.mapping.MappingModel.register_source` — it arrives as the constructor's 19 second argument. Subclassing this is optional; any object works. 20 """
Optional convention base for a custom source's dependency bundle.
Group the dependencies your Source needs in a small dataclass and pass it as args to
remotivelabs.topology.mapping.MappingModel.register_source — it arrives as the constructor's
second argument. Subclassing this is optional; any object works.
25class Target(Protocol): 26 """ 27 Contract for a signal target in a mapping flow. 28 29 Implement this protocol to plug a custom destination (VISSR, websocket, 30 file, ...) into a mapping, and register it via 31 `remotivelabs.topology.mapping.MappingModel.register_target`. The framework 32 calls `publish(value)` once per transformed value yielded by the source. 33 34 The constructor takes the entry's target address — plus an optional second argument for 35 dependencies passed at registration (`register_target("custom.x", MyTarget, args)`): 36 37 ```python 38 class MyTarget: 39 def __init__(self, address: SignalAddress, args: MyArgs) -> None: 40 self._topic = address["topic"] 41 self._client = args.client 42 43 async def publish(self, value: SignalValue) -> None: 44 await self._client.send(self._topic, value) 45 ``` 46 """ 47 48 async def publish(self, value: SignalValue) -> None: 49 """Send one (already-transformed) value to the target.""" 50 ...
Contract for a signal target in a mapping flow.
Implement this protocol to plug a custom destination (VISSR, websocket,
file, ...) into a mapping, and register it via
remotivelabs.topology.mapping.MappingModel.register_target. The framework
calls publish(value) once per transformed value yielded by the source.
The constructor takes the entry's target address — plus an optional second argument for
dependencies passed at registration (register_target("custom.x", MyTarget, args)):
class MyTarget:
def __init__(self, address: SignalAddress, args: MyArgs) -> None:
self._topic = address["topic"]
self._client = args.client
async def publish(self, value: SignalValue) -> None:
await self._client.send(self._topic, value)
1945def _no_init_or_replace_init(self, *args, **kwargs): 1946 cls = type(self) 1947 1948 if cls._is_protocol: 1949 raise TypeError('Protocols cannot be instantiated') 1950 1951 # Already using a custom `__init__`. No need to calculate correct 1952 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1953 if cls.__init__ is not _no_init_or_replace_init: 1954 return 1955 1956 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1957 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1958 # searches for a proper new `__init__` in the MRO. The new `__init__` 1959 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1960 # instantiation of the protocol subclass will thus use the new 1961 # `__init__` and no longer call `_no_init_or_replace_init`. 1962 for base in cls.__mro__: 1963 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1964 if init is not _no_init_or_replace_init: 1965 cls.__init__ = init 1966 break 1967 else: 1968 # should not happen 1969 cls.__init__ = object.__init__ 1970 1971 cls.__init__(self, *args, **kwargs)
14@dataclass 15class TargetArgs: 16 """ 17 Optional convention base for a custom target's dependency bundle. 18 19 Group the dependencies your `Target` needs in a small dataclass and pass it as `args` to 20 `remotivelabs.topology.mapping.MappingModel.register_target` — it arrives as the constructor's 21 second argument. Subclassing this is optional; any object works. 22 """
Optional convention base for a custom target's dependency bundle.
Group the dependencies your Target needs in a small dataclass and pass it as args to
remotivelabs.topology.mapping.MappingModel.register_target — it arrives as the constructor's
second argument. Subclassing this is optional; any object works.
55class TopologySource: 56 """ 57 Subscribes to a signal on a broker channel and yields its values. 58 59 Reference implementation of `Source`. The `namespace` is the resolved broker namespace; 60 use `from_address` to resolve it from a signal address's `channel` via `ecu`. 61 """ 62 63 def __init__(self, *, namespace: str, frame: str, signal: str, broker_client: BrokerClient) -> None: 64 self._namespace = namespace 65 self._frame = frame 66 self._signal = signal 67 self._broker_client = broker_client 68 69 @classmethod 70 def from_address(cls, address: BuiltinSignalAddress, broker_client: BrokerClient, *, ecu: str = DEFAULT_ECU) -> TopologySource: 71 return cls( 72 namespace=address.broker_namespace(ecu), 73 frame=message_name(address), 74 signal=address.signal, 75 broker_client=broker_client, 76 ) 77 78 async def signals(self) -> AsyncIterator[SignalValue]: 79 stream = await self._broker_client.subscribe_frames((self._namespace, [FrameSubscription(name=self._frame)])) 80 async for frame in stream: 81 value = frame.signals.get(self._signal) 82 if value is not None: 83 yield value
Subscribes to a signal on a broker channel and yields its values.
Reference implementation of Source. The namespace is the resolved broker namespace;
use from_address to resolve it from a signal address's channel via ecu.
69 @classmethod 70 def from_address(cls, address: BuiltinSignalAddress, broker_client: BrokerClient, *, ecu: str = DEFAULT_ECU) -> TopologySource: 71 return cls( 72 namespace=address.broker_namespace(ecu), 73 frame=message_name(address), 74 signal=address.signal, 75 broker_client=broker_client, 76 )
53class TopologyTarget: 54 """ 55 Publishes signal values to a signal on a broker `Namespace`, the protocol-appropriate way. 56 57 Reference implementation of `Target`. Given a core `Namespace`, the write path follows its 58 type: a `CanNamespace` writes via its restbus (cyclic), a `LinNamespace` writes the cache, 59 anything else does a one-shot publish; unchanged values on the stateful (restbus/cache) targets 60 are skipped. The caller owns the namespace lifecycle (`open()`, and `restbus.start()` for CAN) 61 and may share one namespace across many targets — e.g. one `CanNamespace` for a bus, one 62 `TopologyTarget` per signal it emits. 63 64 Given a ready `Publisher` instead, that is used as-is. `MappingModel` passes the per-message 65 publisher the engines use, so a target message the namespace does not hold — a cycle-less CAN 66 frame — is relayed one-shot rather than written into a restbus that never transmits it. 67 """ 68 69 def __init__(self, target: Namespace | Publisher, signal: str) -> None: 70 self._signal = signal 71 self._publish = make_publisher(target) if isinstance(target, Namespace) else target 72 73 @classmethod 74 def from_address(cls, address: BuiltinSignalAddress, publish: Publisher) -> TopologyTarget: 75 return cls(publish, address.signal) 76 77 async def publish(self, value: SignalValue) -> None: 78 await self._publish(self._signal, value)
Publishes signal values to a signal on a broker Namespace, the protocol-appropriate way.
Reference implementation of Target. Given a core Namespace, the write path follows its
type: a CanNamespace writes via its restbus (cyclic), a LinNamespace writes the cache,
anything else does a one-shot publish; unchanged values on the stateful (restbus/cache) targets
are skipped. The caller owns the namespace lifecycle (open(), and restbus.start() for CAN)
and may share one namespace across many targets — e.g. one CanNamespace for a bus, one
TopologyTarget per signal it emits.
Given a ready Publisher instead, that is used as-is. MappingModel passes the per-message
publisher the engines use, so a target message the namespace does not hold — a cycle-less CAN
frame — is relayed one-shot rather than written into a restbus that never transmits it.