Skip to main content

m5stack_core/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Board support crate for the **M5Stack Fire27** (ESP32) and **CoreS3**
3//! (ESP32-S3).
4//!
5//! Provides chip-agnostic peripheral drivers ([`driver`]), a shared async I2C
6//! bus and reusable `embassy`-based IO task loops ([`io`]), and board bring-up
7//! helpers ([`board`]).
8//!
9//! The crate also owns the board/chip boilerplate a binary would otherwise
10//! hand-roll, so a consumer's `main` collapses to a thin entry shell:
11//!
12//! - [`mem::init_heap`] — the global heap (esp-alloc DRAM regions + HIL-proven
13//!   per-board sizes; `heap` feature, implied by `psram`).
14//! - [`io::console::install`] — one-call logging over the chip's native
15//!   transport (UART0 / USB-Serial-JTAG CDC) + an RTC panic breadcrumb
16//!   ([`io::console::take_panic_breadcrumb`]) + (`app-desc` feature) the
17//!   firmware identity, logged once as the very first BSP-emitted line.
18//! - the `panic-handler` feature exports the `#[panic_handler]`, and
19//!   [`app_desc!`] the esp-idf app descriptor (`app-desc` feature, implied by
20//!   `heap`) — plus [`app_elf_sha256`], and, under `identity`, an enforced
21//!   build-time git identity in `app_desc!()`'s version field (see the
22//!   README's "Firmware identity" section).
23//! - [`board::run_app_core`] — the second-core harness (`multicore` feature).
24//! - [`io::input_caps`] — the board's input model (keypad vs pointer), so a UI
25//!   installs the matching indev without hardcoding the board.
26//!
27//! Exactly one board feature must be enabled: `fire27` (xtensa-esp32) or
28//! `cores3` (xtensa-esp32s3). Radio (`ble`/`wifi`/`wifi-sta`/`coex`), `heap`/
29//! `psram`/`app-desc`/`identity`, `console-serial`, `panic-handler`, and
30//! `multicore` are orthogonal opt-ins. See the README for the full feature
31//! matrix and usage examples.
32// `no_std` except for host tests: only the hardware-free modules build there
33// (everything touching the chip is gated on `target_os = "none"` below).
34#![cfg_attr(not(test), no_std)]
35// `#[embassy_executor::task]` expands to an associated-type `impl Trait`. Only
36// the two tasks need it — `console::drain_task` and `wifi::sta::wifi_task` — so
37// gating on their features keeps every other build free of an unused-feature
38// warning.
39#![cfg_attr(
40    any(feature = "console-serial", feature = "wifi-sta"),
41    feature(impl_trait_in_assoc_type)
42)]
43// `PsramSafe` (mem::, `psram` feature) is a Send/Sync-style auto trait with a
44// negative impl. The item is `#[cfg(psram)]`, but cfg stripping happens after
45// parsing, so the syntax is still seen in a psram-free `heap` build — hence the
46// gate follows `heap`, the feature that pulls the module in at all.
47#![cfg_attr(feature = "heap", feature(auto_traits, negative_impls))]
48// `PsramSafe`'s negative impl names `Atomic<T>`. A library feature, so unlike
49// the syntax gate above the `psram` cfg suffices.
50#![cfg_attr(feature = "psram", feature(generic_atomic))]
51// Inline asm is still unstable on Xtensa, and two modules use it: `stack` reads
52// the stack pointer on every on-target build, and `board::run_app_core`'s
53// APP-core idle loop (`multicore`) uses `waiti`.
54#![cfg_attr(target_arch = "xtensa", feature(asm_experimental_arch))]
55
56// Link-only: pins esp-rom-sys to the version esp-hal's code actually needs
57// (esp-hal still under-constrains it to ~0.1 while calling newer APIs). Referenced
58// here so the pin in Cargo.toml survives `cargo package` rather than being
59// dropped as an unused dependency.
60#[cfg(target_os = "none")]
61use esp_rom_sys as _;
62
63#[cfg(target_os = "none")]
64#[macro_use]
65mod fmt;
66
67/// Replaces embassy-executor's `Spawner::must_spawn`, dropped in 0.10: panics
68/// on pool exhaustion with call-site context. Works for `Spawner` and
69/// `SendSpawner`.
70#[macro_export]
71macro_rules! must_spawn {
72    ($spawner:expr, $task:expr) => {
73        $spawner.spawn(
74            $task.unwrap_or_else(|e| {
75                ::core::panic!(concat!("spawn ", stringify!($task), ": {:?}"), e)
76            }),
77        )
78    };
79}
80
81#[cfg(target_os = "none")]
82pub mod board;
83#[cfg(target_os = "none")]
84pub mod driver;
85pub mod io;
86#[cfg(feature = "heap")]
87pub mod mem;
88/// Board health: scheduling latency, heap regions, thread stacks.
89#[cfg(feature = "monitor")]
90pub mod monitor;
91#[cfg(target_os = "none")]
92pub mod stack;
93/// Re-exported so `init_heap_sized!` resolves `esp_alloc` and the `#[ram]`
94/// attribute at the caller's site, without the caller having to import either
95/// or depend on the exact versions this crate pins.
96#[cfg(feature = "heap")]
97pub use {esp_alloc, esp_hal};
98
99/// BSP-provided `#[panic_handler]` (opt in with the `panic-handler` feature).
100/// Body is [`io::console::on_panic`]: record the RTC breadcrumb, best-effort
101/// drain the ring over the raw transport, then halt and let the RWDT recover.
102/// A consumer that wants its own panic policy simply leaves the feature off.
103#[cfg(feature = "panic-handler")]
104#[panic_handler]
105fn panic(info: &core::panic::PanicInfo) -> ! {
106    crate::io::console::on_panic(info)
107}
108
109// `app_desc!` wraps esp-bootloader-esp-idf's `esp_app_desc!`. The bootloader
110// crate is pulled by the `app-desc` feature (implied by `heap`); re-exported
111// (hidden) so the macro can name it from the call site without the binary
112// depending on it directly.
113#[cfg(feature = "app-desc")]
114#[doc(hidden)]
115pub use esp_bootloader_esp_idf as __bootloader;
116
117/// Reads back the descriptor [`app_desc!`] emits.
118///
119/// [`app_desc!`] expands to a `static` named `ESP_APP_DESC` **at its call
120/// site** (i.e. in the binary, not this crate), so this reads it back by its
121/// linker symbol (`esp_app_desc`, `EspAppDesc` is `#[repr(C)]`) rather than by
122/// path — the one way a BSP function can reach a descriptor the *consumer*
123/// created. Requires [`app_desc!`] to have been invoked somewhere in the
124/// binary: otherwise this fails to **link**, not silently reads zeroes.
125///
126/// This indirection matters beyond just "how do we reach it": reading
127/// `ESP_APP_DESC` via an `extern` symbol, rather than by path from *inside*
128/// the same crate that defines it, is what keeps [`app_elf_sha256`] correct.
129/// `espflash` patches that field into the flashed image **after**
130/// compilation — the compiler only ever sees the macro's zero initializer.
131/// A same-crate path read of a `static` with a compiler-visible initializer
132/// is free to const-fold to that initializer (needing a `read_volatile` to
133/// stop it); an `extern` read of a symbol whose initializer lives in a
134/// *different* compilation unit has no initializer to see in the first
135/// place, so the hazard cannot arise — no volatile needed. `version` has no
136/// such concern (nothing patches it post-link), but `app_elf_sha256` does:
137/// don't "simplify" this back to a path reference.
138#[cfg(feature = "app-desc")]
139pub fn app_desc() -> &'static __bootloader::EspAppDesc {
140    unsafe extern "C" {
141        #[link_name = "esp_app_desc"]
142        static ESP_APP_DESC: __bootloader::EspAppDesc;
143    }
144    unsafe { &ESP_APP_DESC }
145}
146
147/// Bytes budget for [`__pkg_version_bytes`] — plenty for any real semver
148/// string (`"1.2.3"` is 5 bytes; `"1.0.0-beta.12"` is 13). Unlike the
149/// identity mark, a too-long crate version here is a cosmetic display
150/// nicety, not an identity-tracking risk, so it's a silent truncation, not
151/// enforced by a compile-time assertion the way `app_desc!`'s mark is.
152#[cfg(feature = "app-desc")]
153#[doc(hidden)]
154pub const PKG_VERSION_BYTES: usize = 16;
155
156/// Zero-pads/truncates `s` into a fixed-size, C-safe byte array — the same
157/// shape `EspAppDesc`'s own fields use, chosen deliberately: a plain `&str`
158/// (a fat pointer) has no stable ABI for an `extern` static to read back
159/// across the crate boundary the way [`app_desc()`] reads `EspAppDesc`
160/// (which is `#[repr(C)]`); a fixed byte array does. Used only by
161/// [`app_desc!`]'s expansion, to export `CARGO_PKG_VERSION` for
162/// [`pkg_version()`] to read back — needed because `identity` repurposes
163/// `EspAppDesc::version` for the git mark, so the crate version isn't
164/// available there anymore.
165#[cfg(feature = "app-desc")]
166#[doc(hidden)]
167pub const fn __str_to_fixed<const N: usize>(s: &str) -> [u8; N] {
168    let bytes = s.as_bytes();
169    let mut out = [0u8; N];
170    let mut i = 0;
171    while i < bytes.len() && i < N {
172        out[i] = bytes[i];
173        i += 1;
174    }
175    out
176}
177
178/// Reads back the `CARGO_PKG_VERSION` [`app_desc!`] exports alongside the
179/// descriptor — see [`__str_to_fixed`] for why this needs its own static
180/// rather than reusing [`app_desc()`]'s mechanism.
181///
182/// Gated on `identity`, not merely `app-desc`: without `identity` the
183/// descriptor's own `version` field still holds `CARGO_PKG_VERSION`, so
184/// [`log_boot_identity`] reads it straight from there and this reader has no
185/// caller. `app_desc!` exports the symbol in **both** cases, so a consumer that
186/// wants it can still link against it — only this crate's private reader is
187/// conditional.
188#[cfg(all(feature = "app-desc", feature = "identity"))]
189fn pkg_version() -> &'static str {
190    unsafe extern "C" {
191        #[link_name = "m5stack_core_pkg_version"]
192        static PKG_VERSION: [u8; PKG_VERSION_BYTES];
193    }
194    let bytes = unsafe { &PKG_VERSION };
195    let len = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
196    core::str::from_utf8(&bytes[..len]).unwrap_or("?")
197}
198
199/// The ELF's content hash, straight from the esp-idf application descriptor —
200/// the first bytes distinguish two images built from the same commit with
201/// different uncommitted edits. Unambiguous with no consumer input needed: it
202/// is a function of the linked image, computed and patched in by `espflash`.
203/// Requires [`app_desc!`] to have been invoked (see [`app_desc()`]).
204#[cfg(feature = "app-desc")]
205pub fn app_elf_sha256() -> &'static [u8; 32] {
206    app_desc().app_elf_sha256()
207}
208
209/// Logs the descriptor's version (plain `CARGO_PKG_VERSION`, or the enforced
210/// `<pkg>/<bin>/<features>/<hash><dirty>` git mark under `identity` — which
211/// already carries the binary name, so it isn't repeated separately there),
212/// the crate's `version=` (always the real `CARGO_PKG_VERSION`, even under
213/// `identity` where the descriptor's own version field no longer holds it —
214/// see [`pkg_version()`]), and a 6-byte `app_elf_sha256` prefix, once, as
215/// early as possible on boot — called by [`io::console::install`], not meant
216/// to be called directly. Like [`app_elf_sha256`], requires [`app_desc!`] to
217/// have been invoked somewhere in the binary (a link error otherwise, not a
218/// silent no-op): any binary enabling `app-desc` — directly, or via `heap` —
219/// is expected to call [`app_desc!`], matching this crate's existing "thin
220/// entry shell" framing.
221#[cfg(feature = "app-desc")]
222pub(crate) fn log_boot_identity() {
223    use core::fmt::Write as _;
224
225    let desc = app_desc();
226    let sha = desc.app_elf_sha256();
227    let mut hex = heapless::String::<12>::new();
228    for byte in &sha[..6] {
229        let _ = write!(hex, "{byte:02x}");
230    }
231    #[cfg(feature = "identity")]
232    log::info!(
233        "{} {} version={} app_elf_sha256={hex}",
234        io::console::markers::IDENTITY,
235        desc.version(),
236        pkg_version()
237    );
238    #[cfg(not(feature = "identity"))]
239    log::info!(
240        "{} {} version={} app_elf_sha256={hex}",
241        io::console::markers::IDENTITY,
242        desc.project_name(),
243        desc.version()
244    );
245}
246
247/// Emit the esp-idf application descriptor. Invoke once **in the binary** (not
248/// the BSP) so it captures the *application's* `CARGO_PKG_VERSION`. Thin wrapper
249/// over `esp_bootloader_esp_idf::esp_app_desc!` so the binary keeps a single
250/// `m5stack_core::app_desc!();` line instead of naming the bootloader crate.
251///
252/// With the `identity` feature off (default), the descriptor's version field
253/// is plain `CARGO_PKG_VERSION`, as always. With `identity` on, this same call
254/// site — unchanged — instead requires `M5STACK_CORE_BUILD_MARK`, a build-time
255/// git descriptor the consumer's own `build.rs` sets (see the
256/// `m5stack-core-build` crate). BSP owns the mechanism, never the content: if
257/// the `build.rs` wiring is missing, `env!()` fails to compile in the
258/// *consumer's* crate — a real compile error, not a silent fallback.
259///
260/// `project_name` is `CARGO_BIN_NAME`, not `CARGO_PKG_NAME`: a package can
261/// have more than one `[[bin]]`, and only the per-binary compilation (where
262/// this macro expands) knows which one is being built — `CARGO_PKG_NAME`
263/// would report the same value for every binary in a multi-bin package.
264///
265/// Also exports `CARGO_PKG_VERSION` under its own linker symbol (see
266/// [`__str_to_fixed`]) — even though the descriptor's own `version` field
267/// already holds it here, `identity`'s arm below doesn't have that field
268/// free, so both arms export it the same way for [`log_boot_identity`] /
269/// [`pkg_version()`] to read uniformly.
270#[cfg(all(feature = "app-desc", not(feature = "identity")))]
271#[macro_export]
272macro_rules! app_desc {
273    () => {
274        #[unsafe(export_name = "m5stack_core_pkg_version")]
275        #[used]
276        static __M5STACK_CORE_PKG_VERSION: [u8; $crate::PKG_VERSION_BYTES] =
277            $crate::__str_to_fixed(env!("CARGO_PKG_VERSION"));
278        $crate::__bootloader::esp_app_desc!(
279            env!("CARGO_PKG_VERSION"),
280            env!("CARGO_BIN_NAME"),
281            $crate::__bootloader::BUILD_TIME,
282            $crate::__bootloader::BUILD_DATE,
283            $crate::__bootloader::ESP_IDF_COMPATIBLE_VERSION,
284            $crate::__bootloader::MMU_PAGE_SIZE,
285            0,
286            u16::MAX,
287            $crate::__bootloader::SECURE_VERSION
288        );
289    };
290}
291
292/// See the non-`identity` [`app_desc!`] above — same default call site. The
293/// version field becomes `CARGO_PKG_NAME` + `CARGO_BIN_NAME` joined with the
294/// git mark (`<pkg>/<bin>/<features>/<hash><dirty>`, e.g.
295/// `demos/display/crypto-opt/0f63a4926303+`) — both names included for the
296/// same reason as `project_name` above (a package can have more than one
297/// `[[bin]]`, and disambiguating *which package* matters too once several
298/// crates in a workspace all use `identity`), joined here (rather than by
299/// `m5stack-core-build`) because only this per-binary compilation knows
300/// `CARGO_BIN_NAME`; a `build.rs` runs once per *package* and can't know
301/// which binary it's describing. `CARGO_PKG_VERSION` is exported separately
302/// (see [`__str_to_fixed`]) since the descriptor's `version` field is now
303/// the mark, not the crate version.
304///
305/// `EspAppDesc::version` is a fixed 32-byte C string with no reserved NUL
306/// terminator (see `m5stack-core-build`'s docs) — 31 bytes is the true safe
307/// ceiling, and real package/binary names routinely don't leave room for a
308/// features tag alongside a 12-hex commit (a package/binary pair over ~17
309/// bytes combined already eats the whole budget). Enforced here as a real
310/// compile error, not a silent truncation.
311///
312/// **`app_desc!("prefix")`** — an optional string-literal argument replaces
313/// the automatic `CARGO_PKG_NAME`/`CARGO_BIN_NAME` join with exactly what you
314/// pass, e.g. `app_desc!("oxichg/evcc-hl")`. This is the lever for a project
315/// whose real names don't fit: nothing here truncates or abbreviates on your
316/// behalf (an automatic scheme is a guess, and a wrong guess in an identity
317/// string is worse than no identity — see `#43`'s own reasoning for not
318/// letting the BSP derive a commit itself), so *you* decide what the prefix
319/// says and how long it is. `project_name` still reports the real
320/// `CARGO_BIN_NAME` regardless — only the mark's prefix is overridable.
321/// Default (no argument) is unaffected and unchanged for every existing
322/// caller.
323#[cfg(all(feature = "app-desc", feature = "identity"))]
324#[macro_export]
325macro_rules! app_desc {
326    () => {
327        const _: () = ::core::assert!(
328            ::core::concat!(
329                ::core::env!("CARGO_PKG_NAME"), "/", ::core::env!("CARGO_BIN_NAME"), "/",
330                ::core::env!("M5STACK_CORE_BUILD_MARK")
331            ).len() <= 31,
332            "m5stack_core::app_desc!(): the identity mark (CARGO_PKG_NAME + '/' + CARGO_BIN_NAME \
333             + '/' + M5STACK_CORE_BUILD_MARK) exceeds 31 bytes (EspAppDesc::version's safe \
334             ceiling — see m5stack-core-build's docs). Shorten the `features` tag passed to \
335             emit_identity_env(), or pass a shorter prefix explicitly: \
336             app_desc!(\"short-pkg/short-bin\") instead of the default \
337             CARGO_PKG_NAME/CARGO_BIN_NAME."
338        );
339        #[unsafe(export_name = "m5stack_core_pkg_version")]
340        #[used]
341        static __M5STACK_CORE_PKG_VERSION: [u8; $crate::PKG_VERSION_BYTES] =
342            $crate::__str_to_fixed(env!("CARGO_PKG_VERSION"));
343        $crate::__bootloader::esp_app_desc!(
344            ::core::concat!(
345                ::core::env!("CARGO_PKG_NAME"), "/", ::core::env!("CARGO_BIN_NAME"), "/",
346                ::core::env!("M5STACK_CORE_BUILD_MARK")
347            ),
348            env!("CARGO_BIN_NAME"),
349            $crate::__bootloader::BUILD_TIME,
350            $crate::__bootloader::BUILD_DATE,
351            $crate::__bootloader::ESP_IDF_COMPATIBLE_VERSION,
352            $crate::__bootloader::MMU_PAGE_SIZE,
353            0,
354            u16::MAX,
355            $crate::__bootloader::SECURE_VERSION
356        );
357    };
358    ($prefix:literal) => {
359        const _: () = ::core::assert!(
360            ::core::concat!($prefix, "/", ::core::env!("M5STACK_CORE_BUILD_MARK")).len() <= 31,
361            "m5stack_core::app_desc!(\"prefix\"): the identity mark (prefix + '/' + \
362             M5STACK_CORE_BUILD_MARK) exceeds 31 bytes (EspAppDesc::version's safe ceiling — see \
363             m5stack-core-build's docs). Shorten the `features` tag passed to \
364             emit_identity_env(), or the prefix passed here."
365        );
366        #[unsafe(export_name = "m5stack_core_pkg_version")]
367        #[used]
368        static __M5STACK_CORE_PKG_VERSION: [u8; $crate::PKG_VERSION_BYTES] =
369            $crate::__str_to_fixed(env!("CARGO_PKG_VERSION"));
370        $crate::__bootloader::esp_app_desc!(
371            ::core::concat!($prefix, "/", ::core::env!("M5STACK_CORE_BUILD_MARK")),
372            env!("CARGO_BIN_NAME"),
373            $crate::__bootloader::BUILD_TIME,
374            $crate::__bootloader::BUILD_DATE,
375            $crate::__bootloader::ESP_IDF_COMPATIBLE_VERSION,
376            $crate::__bootloader::MMU_PAGE_SIZE,
377            0,
378            u16::MAX,
379            $crate::__bootloader::SECURE_VERSION
380        );
381    };
382}