unprobe/lib.rs
1#![no_std]
2
3//! Probe-less development for RP2040/RP2350 with [Embassy](https://embassy.dev).
4//!
5//! No debug probe? With `unprobe`, a debug build gets:
6//! - **Logging over USB serial** with the usual `info!`, `warn!`, `error!`, `debug!`, `trace!`.
7//! - **Panic capture:** the message survives a reset and is printed on the next boot.
8//! The firmware then halts there instead of running again, like stopping at a breakpoint.
9//! - **HardFault and stack overflow capture:** reported the same way, with the source line
10//! (the CLI looks it up). On the RP2350 the stack limit register turns a stack overflow
11//! into a fault instead of silent memory corruption, like flip-link.
12//! - **Stack usage:** [`stack_usage`] tells how deep the stack has been so far.
13//! - **Flashing without the BOOTSEL button:** the `unprobe` CLI opens the port at 1200 baud
14//! and the board reboots into BOOTSEL by itself.
15//!
16//! In a **release** build all of this disappears: no USB stack, no logger, no format strings,
17//! no fault handler. The binary is the same as one built without `unprobe` (the panic handler
18//! behaves exactly like `panic-halt`).
19//!
20//! # Usage
21//!
22//! ```ignore
23//! use unprobe::info;
24//!
25//! #[embassy_executor::main]
26//! async fn main(spawner: Spawner) {
27//! let p = embassy_rp::init(Default::default());
28//! unprobe::init!(spawner, p.USB);
29//! info!("hello from {}", "unprobe");
30//! }
31//! ```
32//!
33//! Use the `unprobe` CLI as the cargo runner (`cargo install unprobe-cli`), in
34//! `.cargo/config.toml`:
35//!
36//! ```toml
37//! [target.'cfg(all(target_arch = "arm", target_os = "none"))']
38//! runner = "unprobe run"
39//! ```
40//!
41//! `cargo run` then flashes the board and streams the log into the terminal.
42//!
43//! [`init!`] needs an async context: if the previous boot panicked or faulted, it prints the
44//! report and never returns, so the application does not run again until you reflash or replug.
45//!
46//! ## Device identity, log level and format
47//!
48//! ```ignore
49//! unprobe::init!(spawner, p.USB, unprobe::Config {
50//! product: "My Board",
51//! level: log::LevelFilter::Info,
52//! format: unprobe::Format::Detailed, // or Format::Custom(your_fn)
53//! ..unprobe::Config::new()
54//! });
55//! ```
56//!
57//! The log buffer is 2048 bytes; set `UNPROBE_BUFFER_SIZE` in the `[env]` section of your
58//! `.cargo/config.toml` to change it.
59//!
60//! If you change the VID/PID, pass them to the CLI too: `unprobe run --vid 1234 --pid 5678`.
61//!
62//! ## Sharing USB with your own device
63//!
64//! If the firmware already uses USB (HID, MIDI, ...), add the log port to your own builder
65//! instead. The device then appears as a composite device. Driver, interrupt, VID/PID and
66//! `UsbDevice::run` stay yours; only [`Config::level`] is used. In release, nothing is added.
67//!
68//! ```ignore
69//! let mut builder = embassy_usb::Builder::new(driver, config, ...);
70//! unprobe::attach!(spawner, &mut builder); // first, before your own classes
71//! // ... add your own classes ...
72//! spawner.spawn(usb_task(builder.build())).unwrap();
73//! unprobe::halt_if_panicked!();
74//! ```
75//!
76//! # Cargo features
77//!
78//! All are on by default. With `default-features = false`, only the logger is left.
79//!
80//! - `panic-handler`: provides the `#[panic_handler]`. Turn it off to use your own
81//! (for example `panic-halt` or `panic-probe`).
82//! - `hardfault-handler`: provides the `HardFault` handler and, on the RP2350, the stack
83//! limit. Turn it off to use your own `#[exception] fn HardFault`.
84//! - `bootsel-touch`: opening the port at 1200 baud reboots the board into BOOTSEL.
85//! Without it, you have to press the button for every flash.
86//!
87//! # Notes
88//!
89//! - Use the macros from this crate (`unprobe::info!`). Calling `log::info!` directly
90//! also works in debug builds, but in release it leaves the call in the binary unless
91//! your app enables the `log` feature `release_max_level_off`.
92//! - `unprobe` installs itself as the `log` logger. If another logger is already installed,
93//! it doesn't panic: it prints a notice over USB, and log output goes to that logger.
94//! - Debug and release are told apart by `debug_assertions` (`cargo build` vs
95//! `cargo build --release`).
96//! - The chip feature of `embassy-rp` (`rp235xa`, `rp2040`, ...) is chosen by your application.
97
98#[cfg(all(debug_assertions, feature = "hardfault-handler", target_arch = "arm"))]
99mod fault;
100#[cfg(debug_assertions)]
101mod logger;
102#[cfg(feature = "panic-handler")]
103mod panic;
104#[cfg(all(debug_assertions, target_arch = "arm"))]
105mod stack;
106mod uptime;
107#[cfg(debug_assertions)]
108mod usb;
109
110pub use uptime::{Uptime, uptime};
111
112#[cfg(debug_assertions)]
113pub use log::{debug, error, info, trace, warn};
114
115/// USB device identity and log level. Only used in debug builds.
116///
117/// Start from [`Config::new`] and override what you need:
118/// `unprobe::Config { product: "My Board", ..unprobe::Config::new() }`.
119#[derive(Clone, Copy)]
120pub struct Config {
121 /// USB vendor ID. Default `0xc0de` (a test ID, also used by the Embassy examples).
122 pub vid: u16,
123 /// USB product ID. Default `0xcafe`.
124 pub pid: u16,
125 /// Manufacturer string shown by the OS. Default `"unprobe"`.
126 pub manufacturer: &'static str,
127 /// Product string shown by the OS. Default `"unprobe console"`.
128 pub product: &'static str,
129 /// Most verbose level that is sent. Default [`log::LevelFilter::Trace`].
130 pub level: log::LevelFilter,
131 /// How a log line looks. Default [`Format::Plain`].
132 pub format: Format,
133 /// Fill the unused stack with a pattern at start, so [`stack_usage`] can measure it.
134 /// Default `true`. Turn it off if something else lives in that RAM, e.g. a heap that
135 /// starts at `cortex_m_rt::heap_start()`.
136 pub measure_stack: bool,
137}
138
139/// Formats one log line (without the line ending). See [`Format::Custom`].
140pub type FormatFn = fn(&mut dyn core::fmt::Write, &log::Record) -> core::fmt::Result;
141
142/// How a log line looks. Only used in debug builds.
143#[derive(Clone, Copy)]
144pub enum Format {
145 /// `[INFO] message`
146 Plain,
147 /// The time since boot ([`uptime`]), level, message, and where it was logged:
148 /// ```text
149 /// 1.234567 INFO message
150 /// └─ blinky @ src/main.rs:23
151 /// ```
152 Detailed,
153 /// Your own function. It may write several lines (separate them with `"\r\n"`).
154 ///
155 /// ```ignore
156 /// fn my_format(w: &mut dyn core::fmt::Write, r: &log::Record) -> core::fmt::Result {
157 /// write!(w, "{} {} {}", unprobe::uptime().as_millis(), r.level(), r.args())
158 /// }
159 /// ```
160 Custom(FormatFn),
161}
162
163/// How much of the stack was used so far (the deepest point), see [`stack_usage`].
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub struct StackUsage {
166 /// Bytes used at the deepest point so far.
167 pub used: usize,
168 /// Bytes available in total.
169 pub size: usize,
170}
171
172impl core::fmt::Display for StackUsage {
173 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
174 write!(f, "{} of {} bytes", self.used, self.size)
175 }
176}
177
178/// The deepest the stack has been since boot: `info!("stack: {}", unprobe::stack_usage().unwrap())`.
179///
180/// `None` in release builds, before `init!`, with [`Config::measure_stack`] off, or with an
181/// unusual stack layout. It scans the unused stack, which takes about a millisecond.
182pub fn stack_usage() -> Option<StackUsage> {
183 #[cfg(all(debug_assertions, target_arch = "arm"))]
184 return stack::usage();
185 #[cfg(not(all(debug_assertions, target_arch = "arm")))]
186 None
187}
188
189impl Config {
190 /// The default configuration (usable in `const` context).
191 pub const fn new() -> Self {
192 Self {
193 vid: 0xc0de,
194 pid: 0xcafe,
195 manufacturer: "unprobe",
196 product: "unprobe console",
197 level: log::LevelFilter::Trace,
198 format: Format::Plain,
199 measure_stack: true,
200 }
201 }
202}
203
204impl Default for Config {
205 fn default() -> Self {
206 Self::new()
207 }
208}
209
210/// Reboots the chip into BOOTSEL (USB mass storage) mode, as if the button was held.
211///
212/// Available in release builds too; it only takes up space if you call it.
213pub fn reboot_to_bootsel() {
214 embassy_rp::rom_data::reset_to_usb_boot(0, 0);
215}
216
217#[cfg(debug_assertions)]
218#[doc(hidden)]
219pub mod __private {
220 pub use embassy_rp;
221
222 use crate::Config;
223 use embassy_executor::Spawner;
224 use embassy_rp::interrupt::typelevel::{Binding, USBCTRL_IRQ};
225 use embassy_rp::peripherals::USB;
226 use embassy_rp::usb::{Driver, InterruptHandler};
227 use embassy_usb::class::cdc_acm::CdcAcmClass;
228
229 use core::sync::atomic::{AtomicBool, Ordering};
230
231 /// The previous boot ended in a panic or HardFault: the app must not run again.
232 pub(crate) static PANICKED: AtomicBool = AtomicBool::new(false);
233 /// USB and the logger are fully set up (a panic can be reported over USB).
234 /// Starts out false on every boot (.bss).
235 pub(crate) static USB_UP: AtomicBool = AtomicBool::new(false);
236
237 fn start(spawner: Spawner, class: CdcAcmClass<'static, Driver<'static, USB>>, config: Config) {
238 #[cfg(target_arch = "arm")]
239 crate::stack::setup(config.measure_stack);
240 let report = panic_report().or_else(fault_report);
241 PANICKED.store(report.is_some(), Ordering::Relaxed);
242 let (sender, receiver, control) = class.split_with_control();
243 spawner
244 .spawn(crate::usb::control_task(control, receiver))
245 .unwrap();
246 spawner
247 .spawn(crate::logger::log_task(sender, report))
248 .unwrap();
249 if crate::logger::init_logger(config.level, config.format).is_err() {
250 // Not a panic: that would happen again on every boot.
251 crate::logger::notice(
252 "[unprobe] another logger is already installed (log::set_logger); log output goes there, not to USB",
253 );
254 }
255 // Only now: a panic during setup goes to BOOTSEL instead of a reset loop.
256 USB_UP.store(true, Ordering::Relaxed);
257 }
258
259 #[cfg(feature = "panic-handler")]
260 fn panic_report() -> Option<crate::logger::Report> {
261 crate::panic::take_report()
262 }
263
264 #[cfg(not(feature = "panic-handler"))]
265 fn panic_report() -> Option<crate::logger::Report> {
266 None
267 }
268
269 #[cfg(all(feature = "hardfault-handler", target_arch = "arm"))]
270 fn fault_report() -> Option<crate::logger::Report> {
271 crate::fault::take_report()
272 }
273
274 #[cfg(not(all(feature = "hardfault-handler", target_arch = "arm")))]
275 fn fault_report() -> Option<crate::logger::Report> {
276 None
277 }
278
279 /// Never returns if the previous boot panicked or faulted; USB (log + BOOTSEL) keeps running.
280 pub async fn halt_if_panicked() {
281 if PANICKED.load(Ordering::Relaxed) {
282 core::future::pending::<()>().await;
283 }
284 }
285
286 pub fn init(
287 spawner: Spawner,
288 usb_periph: embassy_rp::Peri<'static, USB>,
289 irqs: impl Binding<USBCTRL_IRQ, InterruptHandler<USB>>,
290 config: Config,
291 ) {
292 let class = crate::usb::init_usb(spawner, usb_periph, irqs, &config);
293 start(spawner, class, config);
294 }
295
296 pub fn attach(
297 spawner: Spawner,
298 builder: &mut embassy_usb::Builder<'static, Driver<'static, USB>>,
299 config: Config,
300 ) {
301 start(spawner, crate::usb::add_class(builder), config);
302 }
303}
304
305/// Starts unprobe on the USB peripheral (the firmware uses USB for nothing else).
306///
307/// ```ignore
308/// unprobe::init!(spawner, p.USB);
309/// unprobe::init!(spawner, p.USB, unprobe::Config { product: "My Board", ..unprobe::Config::new() });
310/// ```
311///
312/// - Call it once, early in an async function (usually `main`), before code that can panic.
313/// A panic before it reboots the board into BOOTSEL, since the message can't be shown yet.
314/// - If the previous boot panicked, it prints the report and **never returns**.
315/// - It binds `USBCTRL_IRQ` itself, so don't bind that interrupt elsewhere. To share USB
316/// with your own device, use [`attach!`] instead.
317/// - Release: does nothing; `p.USB` is just consumed.
318#[cfg(debug_assertions)]
319#[macro_export]
320macro_rules! init {
321 ($spawner:expr, $usb:expr) => {
322 $crate::init!($spawner, $usb, $crate::Config::new())
323 };
324 ($spawner:expr, $usb:expr, $config:expr) => {{
325 $crate::__private::embassy_rp::bind_interrupts!(struct __UnprobeIrqs {
326 USBCTRL_IRQ => $crate::__private::embassy_rp::usb::InterruptHandler<
327 $crate::__private::embassy_rp::peripherals::USB,
328 >;
329 });
330 $crate::__private::init($spawner, $usb, __UnprobeIrqs, $config);
331 $crate::halt_if_panicked!();
332 }};
333}
334
335/// For [`attach!`] users: call right after spawning your USB device task, in an async function.
336///
337/// If the previous boot panicked, it never returns: the report is shown over USB and the
338/// application does not run again. [`init!`] does this by itself. Release: does nothing.
339#[cfg(debug_assertions)]
340#[macro_export]
341macro_rules! halt_if_panicked {
342 () => {
343 $crate::__private::halt_if_panicked().await
344 };
345}
346
347#[cfg(not(debug_assertions))]
348#[macro_export]
349macro_rules! halt_if_panicked {
350 () => {{}};
351}
352
353/// Release: nothing happens; the USB peripheral is just consumed.
354#[cfg(not(debug_assertions))]
355#[macro_export]
356macro_rules! init {
357 ($spawner:expr, $usb:expr) => {{
358 let _ = $spawner;
359 let _ = $usb;
360 }};
361 ($spawner:expr, $usb:expr, $config:expr) => {{
362 let _ = $spawner;
363 let _ = $usb;
364 let _: $crate::Config = $config;
365 }};
366}
367
368/// Adds the log port to your own USB device (composite device).
369///
370/// ```ignore
371/// unprobe::attach!(spawner, &mut builder);
372/// // ... add your own classes, build and spawn the device ...
373/// unprobe::halt_if_panicked!();
374/// ```
375///
376/// - Call it **before** adding your own classes. The log port then gets the lowest
377/// interface number, which is how the `unprobe` CLI tells it apart from your own
378/// serial ports (they share the VID/PID).
379/// - `builder` is an `embassy_usb::Builder<'static, embassy_rp::usb::Driver<'static, USB>>`.
380/// Your device must keep `composite_with_iads` on (the `embassy_usb::Config` default).
381/// - Driver, interrupt binding, VID/PID and `UsbDevice::run` stay yours; from the optional
382/// [`Config`] only `level` is used.
383/// - Call [`halt_if_panicked!`] after spawning the device, so a panic report can be shown.
384/// - Release: the builder is left untouched.
385#[cfg(debug_assertions)]
386#[macro_export]
387macro_rules! attach {
388 ($spawner:expr, $builder:expr) => {
389 $crate::attach!($spawner, $builder, $crate::Config::new())
390 };
391 ($spawner:expr, $builder:expr, $config:expr) => {
392 $crate::__private::attach($spawner, $builder, $config)
393 };
394}
395
396/// Release: the builder is left untouched.
397#[cfg(not(debug_assertions))]
398#[macro_export]
399macro_rules! attach {
400 ($spawner:expr, $builder:expr) => {{
401 let _ = $spawner;
402 let _ = $builder;
403 }};
404 ($spawner:expr, $builder:expr, $config:expr) => {{
405 let _ = $spawner;
406 let _ = $builder;
407 let _: $crate::Config = $config;
408 }};
409}
410
411// Release: the arguments are still type-checked (so no unused warnings),
412// but `if false` lets the compiler remove them completely.
413#[cfg(not(debug_assertions))]
414#[macro_export]
415macro_rules! info {
416 ($($arg:tt)+) => {{ if false { let _ = ::core::format_args!($($arg)+); } }};
417}
418#[cfg(not(debug_assertions))]
419#[macro_export]
420macro_rules! warn {
421 ($($arg:tt)+) => {{ if false { let _ = ::core::format_args!($($arg)+); } }};
422}
423#[cfg(not(debug_assertions))]
424#[macro_export]
425macro_rules! error {
426 ($($arg:tt)+) => {{ if false { let _ = ::core::format_args!($($arg)+); } }};
427}
428#[cfg(not(debug_assertions))]
429#[macro_export]
430macro_rules! debug {
431 ($($arg:tt)+) => {{ if false { let _ = ::core::format_args!($($arg)+); } }};
432}
433#[cfg(not(debug_assertions))]
434#[macro_export]
435macro_rules! trace {
436 ($($arg:tt)+) => {{ if false { let _ = ::core::format_args!($($arg)+); } }};
437}