rusty_esp_iroh_esp/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]
2#![deny(unsafe_code)]
3//! `rusty_esp_iroh-esp` — what a chip adds to the std node.
4//!
5//! iroh runs on **Track A only** (std on ESP-IDF, the configuration n0
6//! proved). The node and client are `rusty_esp_iroh-host`, unchanged; this
7//! crate holds the ESP-IDF specifics: registering `eventfd` so tokio's I/O
8//! driver works, SNTP before any TLS, the mDNS advertisement the home
9//! computer's pair client browses for, and the identity loaded from NVS
10//! through `rusty_esp_mid-esp`.
11//!
12//! `unsafe` is denied crate-wide; the one FFI call (`esp_vfs_eventfd_register`)
13//! opts in per block with a `// SAFETY:` comment.
14//!
15//! The `esp-hal` feature is not iroh on bare metal (there is none): it is
16//! [`hal`], the two-slot OTA sink and the "this image works" mark the
17//! core's update session needs on a `no_std` chip.
18
19#[cfg(feature = "alloc")]
20extern crate alloc;
21
22// iroh has no Track B: it needs std (tokio, rustls), and a no_std node
23// reaches the mesh through rusty_esp_iroh-bridge. What Track B does get is
24// the chip's half of the signed-update path, `hal`.
25#[cfg(feature = "esp-hal")]
26pub mod hal;
27
28pub use rusty_esp_iroh_core as core;
29
30/// Which track this build of the crate was compiled for.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Track {
33 /// No chip backend compiled in.
34 Host,
35 /// Track A — std on ESP-IDF.
36 EspIdf,
37}
38
39/// The track this crate was built with.
40pub const TRACK: Track = if cfg!(feature = "esp-idf") {
41 Track::EspIdf
42} else {
43 Track::Host
44};
45
46#[cfg(feature = "esp-idf")]
47pub mod idf {
48 //! Track A glue over esp-idf-svc 0.52.
49
50 #[cfg(any(esp_idf_comp_mdns_enabled, esp_idf_comp_espressif__mdns_enabled))]
51 use std::net::IpAddr;
52 use std::time::Duration;
53
54 #[cfg(any(esp_idf_comp_mdns_enabled, esp_idf_comp_espressif__mdns_enabled))]
55 use esp_idf_svc::mdns::EspMdns;
56 use esp_idf_svc::sntp::{EspSntp, SyncStatus};
57 use esp_idf_svc::sys::EspError;
58 #[cfg(any(esp_idf_comp_mdns_enabled, esp_idf_comp_espressif__mdns_enabled))]
59 use rusty_esp_iroh_core::sidecar::SERVICE_TYPE;
60 #[cfg(any(esp_idf_comp_mdns_enabled, esp_idf_comp_espressif__mdns_enabled))]
61 use rusty_esp_iroh_host::Node;
62
63 /// Whether the `espressif/mdns` IDF component was compiled into this
64 /// firmware (it arrives through `[package.metadata.esp-idf-sys]`, which
65 /// esp-idf-sys only reads when its `cargo metadata --locked` succeeds —
66 /// mission plan §8). Without it `advertise_sidecar` does not exist and
67 /// the device is reachable by ticket only.
68 pub const MDNS_COMPILED_IN: bool = cfg!(any(
69 esp_idf_comp_mdns_enabled,
70 esp_idf_comp_espressif__mdns_enabled
71 ));
72
73 pub use rusty_esp_mid_esp::idf::{EspNvsKv, EspRng, IDENTITY_PARTITION, Protection};
74
75 pub use ota::EspOtaSink;
76
77 /// The two-slot OTA sink (N5) over ESP-IDF's `esp_ota_*` API.
78 ///
79 /// The inactive app partition takes the bytes, `finish` ends the write
80 /// and makes that partition the boot partition, and
81 /// [`EspOtaSink::mark_running_valid`] is what a freshly booted image
82 /// calls once its endpoint is up — without it the bootloader rolls
83 /// back on the next reset (`CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE`).
84 ///
85 /// **The one fenced `unsafe` in this crate.** `esp-idf-svc`'s safe
86 /// `EspOta` / `EspOtaUpdate` pair ties the update handle's lifetime to
87 /// a borrow of the singleton, which cannot live inside a `Box<dyn
88 /// OtaSink + Send>` without a self-reference; the C API's handle is a
89 /// plain integer and the partition a pointer ESP-IDF owns for the life
90 /// of the program, so the sink keeps those and calls the same six
91 /// functions `esp-idf-svc` does, in the same order.
92 #[allow(unsafe_code)]
93 mod ota {
94 use esp_idf_svc::sys::{
95 EspError, esp, esp_ota_abort, esp_ota_begin, esp_ota_end,
96 esp_ota_get_next_update_partition, esp_ota_handle_t,
97 esp_ota_mark_app_valid_cancel_rollback, esp_ota_set_boot_partition, esp_ota_write,
98 esp_partition_t,
99 };
100 use rusty_esp_iroh_core::esp_core::error::{Error, Result};
101 use rusty_esp_iroh_core::ota::OtaSink;
102
103 /// The inactive slot as an [`OtaSink`].
104 #[derive(Debug, Default)]
105 pub struct EspOtaSink {
106 /// `*const esp_partition_t` as an address: ESP-IDF owns the
107 /// partition table for the life of the program, and an address
108 /// is `Send` where a raw pointer is not.
109 partition: usize,
110 handle: Option<esp_ota_handle_t>,
111 }
112
113 impl EspOtaSink {
114 /// A sink over the next update partition.
115 #[must_use]
116 pub fn new() -> Self {
117 Self::default()
118 }
119
120 /// Tell the bootloader the running image is good (cancels the
121 /// pending rollback). Call once the endpoint is up.
122 pub fn mark_running_valid() -> core::result::Result<(), EspError> {
123 // SAFETY: a plain ESP-IDF call with no arguments.
124 esp!(unsafe { esp_ota_mark_app_valid_cancel_rollback() })
125 }
126 }
127
128 impl OtaSink for EspOtaSink {
129 fn begin(&mut self, image_len: u32) -> Result<()> {
130 if self.handle.is_some() {
131 return Err(Error::Busy);
132 }
133 // SAFETY: a null argument asks ESP-IDF for the partition after
134 // the running one; the returned pointer is into the partition
135 // table ESP-IDF keeps for the life of the program.
136 let partition = unsafe { esp_ota_get_next_update_partition(core::ptr::null()) };
137 if partition.is_null() {
138 return Err(Error::Unsupported);
139 }
140 // SAFETY: `partition` is the pointer ESP-IDF just returned;
141 // `handle` is a local ESP-IDF fills.
142 let size = unsafe { (*partition).size };
143 if u64::from(image_len) > u64::from(size) {
144 return Err(Error::BufferTooSmall {
145 needed: image_len as usize,
146 });
147 }
148 let mut handle: esp_ota_handle_t = 0;
149 // SAFETY: as above; `image_len` is the exact size, which lets
150 // ESP-IDF erase only what it must.
151 esp!(unsafe { esp_ota_begin(partition, image_len as usize, &mut handle) })
152 .map_err(|_| Error::Hardware)?;
153 self.partition = partition as usize;
154 self.handle = Some(handle);
155 Ok(())
156 }
157
158 fn write(&mut self, chunk: &[u8]) -> Result<()> {
159 let handle = self.handle.ok_or(Error::Busy)?;
160 if chunk.is_empty() {
161 return Ok(());
162 }
163 // SAFETY: `handle` came from `esp_ota_begin`; the buffer is a
164 // live slice for the duration of the call.
165 esp!(unsafe { esp_ota_write(handle, chunk.as_ptr().cast(), chunk.len()) })
166 .map_err(|_| Error::Hardware)
167 }
168
169 fn finish(&mut self) -> Result<()> {
170 let handle = self.handle.take().ok_or(Error::Busy)?;
171 let partition = self.partition as *const esp_partition_t;
172 // SAFETY: the handle is live until `esp_ota_end` consumes it;
173 // the partition pointer is the one `begin` stored.
174 esp!(unsafe { esp_ota_end(handle) }).map_err(|_| Error::Corrupt)?;
175 esp!(unsafe { esp_ota_set_boot_partition(partition) }).map_err(|_| Error::Hardware)
176 }
177
178 fn abort(&mut self) {
179 if let Some(handle) = self.handle.take() {
180 // SAFETY: the handle is live; abort releases it.
181 let _ = unsafe { esp_ota_abort(handle) };
182 }
183 }
184 }
185 }
186
187 /// Register the `eventfd` VFS tokio's I/O driver (mio) needs. Call once
188 /// before building the runtime; `max_fds` of 5 is what n0 uses.
189 pub fn register_eventfd(max_fds: usize) -> Result<(), EspError> {
190 let config = esp_idf_svc::sys::esp_vfs_eventfd_config_t {
191 max_fds,
192 ..Default::default()
193 };
194 // SAFETY: `config` is a fully initialised POD struct that outlives the
195 // call; the function registers a VFS driver and has no other
196 // preconditions. Called once at boot.
197 #[allow(unsafe_code)]
198 let code = unsafe { esp_idf_svc::sys::esp_vfs_eventfd_register(&config) };
199 EspError::convert(code)
200 }
201
202 /// Start SNTP and wait up to `timeout` for the first sync. TLS (the relay,
203 /// pkarr) needs a sane clock; LAN-direct does not, so a timeout is a
204 /// warning, not an error. Keep the returned handle alive to keep syncing.
205 pub fn sync_time(timeout: Duration) -> Result<(EspSntp<'static>, bool), EspError> {
206 let sntp = EspSntp::new_default()?;
207 let started = std::time::Instant::now();
208 while sntp.get_sync_status() != SyncStatus::Completed {
209 if started.elapsed() > timeout {
210 return Ok((sntp, false));
211 }
212 std::thread::sleep(Duration::from_millis(250));
213 }
214 Ok((sntp, true))
215 }
216
217 /// Advertise `_mata-oem-sidecar._tcp.local.` with the node's TXT record so
218 /// the home computer's pair client lists the device. The service port is
219 /// the iroh UDP port (the record's `iroh_direct` carries the same); the
220 /// instance name is the model. Keep the returned handle alive.
221 #[cfg(any(esp_idf_comp_mdns_enabled, esp_idf_comp_espressif__mdns_enabled))]
222 pub fn advertise_sidecar(
223 node: &Node,
224 hostname: &str,
225 ips: &[IpAddr],
226 ) -> Result<EspMdns, EspError> {
227 advertise_parts(
228 hostname,
229 "Janus device",
230 SERVICE_TYPE,
231 node.port(),
232 &node.sidecar_txt(ips),
233 )
234 }
235
236 /// The same advertisement from its parts, for a caller that has the TXT
237 /// record and the port but not the [`Node`] — a generated sketch, whose
238 /// node lives inside the `rusty_esp_arduino` facade and is never handed
239 /// out. `service_type` is the full mDNS type; ESP-IDF wants the service
240 /// and protocol labels separately, and splitting it is this function's
241 /// job so no caller has to know that. Keep the returned handle alive.
242 #[cfg(any(esp_idf_comp_mdns_enabled, esp_idf_comp_espressif__mdns_enabled))]
243 pub fn advertise_parts(
244 hostname: &str,
245 instance: &str,
246 service_type: &str,
247 port: u16,
248 txt: &[(String, String)],
249 ) -> Result<EspMdns, EspError> {
250 let mut mdns = EspMdns::take()?;
251 mdns.set_hostname(hostname)?;
252 mdns.set_instance_name(instance)?;
253 let pairs: Vec<(&str, &str)> = txt.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
254 let (service, rest) = service_type
255 .split_once('.')
256 .unwrap_or(("_mata-oem-sidecar", "_tcp.local."));
257 let proto = rest.split_once('.').map_or("_tcp", |(p, _)| p);
258 mdns.add_service(Some(instance), service, proto, port, &pairs)?;
259 log::info!(
260 "mdns: {hostname}.local {service}.{proto} port {port} with {} TXT keys",
261 pairs.len()
262 );
263 Ok(mdns)
264 }
265}