nros_platform/board/entry.rs
1//! [`BoardEntry`] — Phase 212.N.1.
2//!
3//! The single boot-driver trait every Entry pkg `main.rs` invokes:
4//!
5//! ```ignore
6//! fn main() {
7//! let _ = <MyBoard as BoardEntry>::run(|runtime| {
8//! run_plan(runtime) // codegen-emitted (212.N.4)
9//! });
10//! }
11//! ```
12//!
13//! `run` owns the full lifecycle:
14//!
15//! 1. [`super::BoardInit::init_hardware`]
16//! 2. device bring-up — link layer to L2, then the carrier / DHCP gate if the
17//! board has an IP stack. This is the `run` BODY's job, usually delegated to
18//! a family helper (`nros_board_freertos::run_entry`, …). There is no mixin
19//! trait for it: phase-206 W4 / issue 1067 removed `TransportBringup` and
20//! `NetworkWait`, which had zero and zero production callers respectively,
21//! and whose "skipped if not implemented" order was not expressible in Rust.
22//! 4. Open executor, build `RuntimeCtx`, invoke `setup(runtime)`.
23//! 5. Spin executor to completion (or termination signal).
24//! 6. [`super::BoardExit::exit_success`] / `exit_failure`.
25//!
26//! The exact body lives in the family driver crates (212.N.2); the
27//! trait here pins the signature so codegen + user Entry pkg can
28//! call it without knowing the family.
29
30use super::runtime::RuntimeCtx;
31
32/// Deploy-metadata overlay threaded from `nros::main!()` into the board's
33/// boot config (issue #48 cause 1).
34///
35/// The `nros::main!()` macro reads the Entry pkg's
36/// `[package.metadata.nros.deploy.<board>]` block at expansion time and bakes
37/// the present keys here. Each field is `None` when the deploy block omitted
38/// it, so the board overlays only the supplied values onto its own
39/// `Config::default()` (the firmware's compiled-in default stays the source of
40/// truth for everything the deploy block does not name).
41///
42/// Boards whose `BoardEntry::run` ignores network/locator config (POSIX hosts,
43/// RTIC/Embassy MCUs that take their transport elsewhere) inherit the default
44/// [`BoardEntry::run_with_deploy`] body, which drops the overlay and calls
45/// [`BoardEntry::run`] — so adding a *network* field here never touches those
46/// boards. The exception is [`node_name`](DeployOverlay::node_name): hosted
47/// boards override `run_with_deploy` to apply it to the boot config (issue #98),
48/// since the ROS graph node name is a launch identity, not a network knob.
49#[derive(Clone, Copy, Default, Debug)]
50pub struct DeployOverlay {
51 /// `locator = "tcp/10.0.2.2:7451"` — the zenoh/RMW endpoint the firmware
52 /// dials. `None` → keep the board default.
53 pub locator: Option<&'static str>,
54 /// The image's resolved network (RFC-0103 D10f, phase-497 W2): the
55 /// `NROS_IMAGE_NET` text `nros sync` rendered from `[image.<id>.net.<if>]`,
56 /// `[network.<name>]` and the board's `[board.net]`, baked verbatim.
57 /// `None` → the image states no interface; keep the board default. Decoded
58 /// by `nros_board_common::image_net` — this crate carries it, it does not
59 /// read it.
60 ///
61 /// It replaced three fields (`ip`, `gateway`, `netmask`) that `nros::main!`
62 /// lowered from `system.toml` itself: the macro has no board catalog, so it
63 /// could not take a board's default network or derive a MAC, and one fact
64 /// would have resolved two ways.
65 pub net: Option<&'static str>,
66 /// `domain_id = 0` — ROS 2 domain. `None` → keep the board default.
67 pub domain_id: Option<u32>,
68 /// `[image.<id>] transport = "serial"` — the LINK kind the image rides
69 /// (RFC-0086 D2). `None` → the board's default link. Read by
70 /// [`BoardEntry::setup_transport`] (phase-244.D1), which may install a
71 /// board custom transport for it BEFORE the linked RMW registers.
72 ///
73 /// Typed, not a string (issue 1601): phase-445 W6 moved the leaf key from
74 /// the RMW name (`"xrce"`) to the link kind (`"serial"`), and the one
75 /// board reading it kept comparing against `"xrce"` — a comparison that
76 /// could no longer be true and compiled anyway. A [`LinkKind`] cannot be
77 /// compared against an RMW name.
78 pub transport: Option<LinkKind>,
79 /// `rmw = "xrce"` — the RMW backend the image declares (`[image.<id>]
80 /// rmw` > `[image_defaults] rmw` > `[system] rmw`), verbatim. `None` → not
81 /// declared (a Form 2 entry, or a leaf with no `system.toml`).
82 ///
83 /// The BACKEND choice, which [`transport`](Self::transport) is not: an
84 /// XRCE image over a UART states both, and a board that registers a
85 /// backend keys on this field (issue 1601).
86 pub rmw: Option<&'static str>,
87 /// The ROS graph node name for the primary session, baked from the launch
88 /// file's single `<node name=…>` / `system.toml` `[[component]].name` (issue
89 /// #98). `None` → the board default (`from_env()`'s `"node"`). Only set by
90 /// `nros::main!` when the launch declares exactly one node — multiple nodes
91 /// share one primary session, so naming it after one component would be
92 /// wrong (per-node naming is the deferred multi-node piece). Applied to the
93 /// boot `ExecutorConfig` by the board, so unlike `locator` this IS honored on
94 /// hosted boards (locator stays env-driven; node name is a launch identity).
95 pub node_name: Option<&'static str>,
96 /// Issue #101 / RFC-0045 — the patchable baked boot-config static
97 /// (`.nros_boot_config`), emitted by `nros::main!` for embedded targets and
98 /// read by the board to resolve node_name/locator/domain. `None` on hosted /
99 /// when the macro emits no static.
100 pub boot_config: Option<&'static nros_platform_api::BakedBootConfig>,
101}
102
103impl DeployOverlay {
104 /// Does the image declare RMW `rmw` riding link `link`? Both halves are
105 /// required: the backend is `rmw`, the link is `[image.<id>] transport`,
106 /// and neither stands in for the other (issue 1601).
107 pub fn selects(&self, rmw: &str, link: LinkKind) -> bool {
108 self.rmw == Some(rmw) && self.transport == Some(link)
109 }
110}
111
112/// The link kind an image rides — `[image.<id>] transport` (RFC-0086 D2).
113///
114/// The same three words as `nros_orchestration_ir::leaf_system::TRANSPORT_KINDS`
115/// (and `nros_platform_config`'s copy), which `nros::main!` maps onto these
116/// variants: an unknown word is refused when the leaf is read, and a word the
117/// macro maps to a variant missing here fails the image's compile. It names a
118/// LINK, never an RMW — `"xrce"` is not one (issue 1601).
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub enum LinkKind {
121 /// A byte-stream link (UART, USB-CDC, …).
122 Serial,
123 /// TCP over the board's IP stack.
124 Tcp,
125 /// UDP over the board's IP stack.
126 Udp,
127}
128
129impl LinkKind {
130 /// Every link kind, in `TRANSPORT_KINDS` order.
131 pub const ALL: [LinkKind; 3] = [LinkKind::Serial, LinkKind::Tcp, LinkKind::Udp];
132
133 /// The `system.toml` spelling.
134 pub const fn name(self) -> &'static str {
135 match self {
136 LinkKind::Serial => "serial",
137 LinkKind::Tcp => "tcp",
138 LinkKind::Udp => "udp",
139 }
140 }
141
142 /// Parse the `system.toml` spelling; `None` for anything that is not a
143 /// link kind — an RMW name included.
144 pub fn from_name(name: &str) -> Option<Self> {
145 Self::ALL.into_iter().find(|k| k.name() == name)
146 }
147}
148
149/// Per-board boot driver.
150///
151/// Implementations live in the family driver crates
152/// (`nros-board-linux`, `nros-board-freertos`, …). Per-board crates
153/// (`nros-board-mps2-an385-freertos`, …) plug the family.
154pub trait BoardEntry: super::Board {
155 /// Drive the full boot → user-closure → exit flow.
156 ///
157 /// `setup` receives a `&mut RuntimeCtx` with overlay knobs projected
158 /// from the launch file at BUILD time (there is no CLI parse; see
159 /// [`super::RuntimeCtx`]). Returning `Err` from `setup` makes
160 /// `run` route to [`super::BoardExit::exit_failure`]; `Ok`
161 /// proceeds to executor spin + clean exit.
162 ///
163 /// **Returns `Result`, not `!`.** The legacy
164 /// `nros-board-common::board_init::BoardEntry::run` diverged;
165 /// 212.N keeps the option to return so unit tests can drive it
166 /// in a hosted process without `exit()` killing the test
167 /// harness. Production boards still call `exit_*` from inside
168 /// `run`'s body after spin returns.
169 fn run<F, E>(setup: F) -> Result<(), E>
170 where
171 F: FnOnce(&mut RuntimeCtx<'_>) -> Result<(), E>,
172 E: core::fmt::Debug;
173
174 /// Boot like [`run`](Self::run) but apply a deploy-metadata overlay to the
175 /// board's boot config first (issue #48 cause 1).
176 ///
177 /// The default body **ignores** `deploy` and forwards to
178 /// [`run`](Self::run); boards that compile a network/locator config (the
179 /// FreeRTOS / bare-metal firmware boards) override it to overlay the
180 /// supplied fields onto their `Config::default()`. `nros::main!()` calls
181 /// this (not `run`) for `target_os = "none"` OwnedSpin targets so the
182 /// `[package.metadata.nros.deploy.<board>]` block stops being inert.
183 fn run_with_deploy<F, E>(_deploy: &DeployOverlay, setup: F) -> Result<(), E>
184 where
185 F: FnOnce(&mut RuntimeCtx<'_>) -> Result<(), E>,
186 E: core::fmt::Debug,
187 {
188 Self::run(setup)
189 }
190
191 /// phase-271 (issue #110) — boot like [`run_with_deploy`](Self::run_with_deploy)
192 /// but size the executor's callback table + arena to the entry's OWN declared
193 /// topology (`max_cbs` / `max_sched_contexts`, from the entry's
194 /// `[package.metadata.nros.entry]`), instead of the workspace-global
195 /// `NROS_EXECUTOR_MAX_CBS` build const.
196 ///
197 /// Sizes are plain `usize`s (not `nros::ExecutorSizing`) because
198 /// `nros-platform` sits below `nros`; the hosted board converts them. A
199 /// `max_sched_contexts` of `0` means "use the build default". The **default
200 /// body IGNORES the sizing** and forwards to
201 /// [`run_with_deploy`](Self::run_with_deploy), so every board except the
202 /// hosted (Linux) one — which opens via `Executor::open` and could grow its
203 /// arena — is byte-identical; `nros-board-linux` overrides this to
204 /// `Executor::open_sized`. `nros::main!()` emits this (instead of
205 /// `run_with_deploy`) only when the entry declares `max_callbacks`.
206 fn run_with_deploy_sized<F, E>(
207 deploy: &DeployOverlay,
208 _max_cbs: usize,
209 _max_sched_contexts: usize,
210 setup: F,
211 ) -> Result<(), E>
212 where
213 F: FnOnce(&mut RuntimeCtx<'_>) -> Result<(), E>,
214 E: core::fmt::Debug,
215 {
216 Self::run_with_deploy(deploy, setup)
217 }
218
219 /// **Custom-transport install seam.** Install a board-specific transport
220 /// selected by `deploy.rmw` + `deploy.transport`, BEFORE the linked RMW registers
221 /// (phase-244.D1).
222 ///
223 /// `nros::main!()` always emits a `setup_transport` call (gated on
224 /// `target_os = "none"`) immediately before `__register_linked_rmw()`,
225 /// so that the vtable is in place before the XRCE backend registers —
226 /// the ordering `set_custom_transport_ops` requires.
227 ///
228 /// **This method is intentionally kept** — it is not dead code. The
229 /// **default no-op** is correct for every board whose transport is
230 /// registered automatically (Zenoh, native sockets, etc.). The only
231 /// current override is **`nros-board-mps2-an385`** with the
232 /// `xrce-transport` feature, which installs an XRCE-over-UART vtable
233 /// when the image declares `rmw = "xrce"` over `transport = "serial"`
234 /// ([`DeployOverlay::selects`]). Future boards that need to
235 /// pre-register a custom transport vtable should override this method in
236 /// the same pattern.
237 ///
238 /// Failures are the board's to handle (it owns `exit_failure`).
239 fn setup_transport(_deploy: &DeployOverlay) {}
240}
241
242#[cfg(test)]
243mod link_kind_tests {
244 use super::{DeployOverlay, LinkKind};
245
246 #[test]
247 fn link_kinds_round_trip_and_an_rmw_name_is_not_one() {
248 for k in LinkKind::ALL {
249 assert_eq!(LinkKind::from_name(k.name()), Some(k));
250 }
251 for rmw in ["xrce", "zenoh", "cyclonedds", "uorb"] {
252 assert_eq!(
253 LinkKind::from_name(rmw),
254 None,
255 "`{rmw}` is an RMW, not a link"
256 );
257 }
258 }
259
260 /// Issue 1601: the XRCE-over-UART image declares `rmw = "xrce"` and
261 /// `transport = "serial"`; the board's predicate must answer yes to that
262 /// pair and no when either half is something else.
263 #[test]
264 fn selects_needs_both_the_rmw_and_the_link() {
265 let xrce_uart = DeployOverlay {
266 rmw: Some("xrce"),
267 transport: Some(LinkKind::Serial),
268 ..Default::default()
269 };
270 assert!(xrce_uart.selects("xrce", LinkKind::Serial));
271 assert!(!xrce_uart.selects("zenoh", LinkKind::Serial));
272 assert!(!xrce_uart.selects("xrce", LinkKind::Udp));
273 let zenoh_serial = DeployOverlay {
274 rmw: Some("zenoh"),
275 transport: Some(LinkKind::Serial),
276 ..Default::default()
277 };
278 assert!(!zenoh_serial.selects("xrce", LinkKind::Serial));
279 assert!(!DeployOverlay::default().selects("xrce", LinkKind::Serial));
280 }
281}