diff --git a/Cargo.toml b/Cargo.toml index aa5c1164..e9c3a3f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,10 +55,7 @@ esp32s3-hal = { version = "0.11.0", optional = true, features = [ ] } # esp32s2 = { version = "0.15.0", optional = true } esp32s3 = { version = "0.20.0", optional = true } -esp-backtrace = { version = "0.7.0", features = [ - "panic-handler", - "exception-handler", -] } # add "halt-cores" +esp-backtrace = { version = "0.7.0" } esp-println = { version = "0.5.0", default-features = false, features = [ "critical-section", "colors", @@ -90,7 +87,7 @@ critical-section = "1.1" device-descriptor = { path = "device-descriptor" } register-access = { path = "register-access" } gui = { path = "gui" } -ads129x = { path = "ads129x" } +ads129x = { path = "ads129x", features = ["defmt"] } max17055 = { path = "max17055", optional = true } signal-processing = { path = "signal-processing", features = ["nostd"] } replace_with = { version = "0.1", default-features = false, features = [ diff --git a/ads129x/Cargo.toml b/ads129x/Cargo.toml index b44855df..3cdc14d9 100644 --- a/ads129x/Cargo.toml +++ b/ads129x/Cargo.toml @@ -12,3 +12,9 @@ embedded-hal = { workspace = true } embedded-hal-async = { workspace = true } log = { workspace = true } register-access = { path = "../register-access" } +defmt = { version = "0.3.5", optional = true } + +[features] +default = ["debug"] +defmt = ["dep:defmt", "device-descriptor/defmt"] +debug = ["device-descriptor/debug"] diff --git a/ads129x/src/lib.rs b/ads129x/src/lib.rs index ed6c1bb8..9614f702 100644 --- a/ads129x/src/lib.rs +++ b/ads129x/src/lib.rs @@ -23,7 +23,9 @@ pub enum Error { Transfer(SpiE), } -#[derive(Copy, Clone, Debug, Default)] +#[derive(Copy, Clone, Default)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[cfg_attr(feature = "debug", derive(Debug))] pub struct ConfigRegisters { pub config1: Config1, pub config2: Config2, @@ -379,6 +381,8 @@ where } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[cfg_attr(feature = "debug", derive(Debug))] pub struct Sample { sample: i32, } @@ -395,6 +399,8 @@ impl Sample { } } +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[cfg_attr(feature = "debug", derive(Debug))] pub struct AdsData { status: LoffStat, ch1: Sample, diff --git a/bad-server/src/lib.rs b/bad-server/src/lib.rs index 070843e4..9eafa191 100644 --- a/bad-server/src/lib.rs +++ b/bad-server/src/lib.rs @@ -240,7 +240,7 @@ where } } - log::debug!("Buffer size: {pos}"); + log::debug!("Buffer size: {}", pos); let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; let mut req = httparse::Request::new(&mut headers); @@ -254,7 +254,7 @@ where // We need to read more } Err(e) => { - log::warn!("Parsing request failed: {e}"); + log::warn!("Parsing request failed: {}", e); return Err(HandleError::RequestParse(e)); } }; diff --git a/bad-server/src/request.rs b/bad-server/src/request.rs index e07d2bd6..330ec857 100644 --- a/bad-server/src/request.rs +++ b/bad-server/src/request.rs @@ -30,7 +30,7 @@ impl<'req, 's, C: Connection> Request<'req, 's, C> { return Err(ResponseStatus::BadRequest); }; - log::info!("[{}] {path}", method.as_str()); + log::info!("[{}] {}", method.as_str(), path); Ok(Self { method, @@ -54,7 +54,7 @@ impl<'req, 's, C: Connection> Request<'req, 's, C> { while !self.is_complete() && !buffer.is_empty() { read += self.read(&mut buffer[read..]).await?; } - log::debug!("Read {read} bytes"); + log::debug!("Read {} bytes", read); Ok(&mut buffer[..read]) } diff --git a/config-site/src/handlers/add_new_network.rs b/config-site/src/handlers/add_new_network.rs index ef7d50a2..b357a2f6 100644 --- a/config-site/src/handlers/add_new_network.rs +++ b/config-site/src/handlers/add_new_network.rs @@ -18,7 +18,7 @@ impl<'a> AddNewNetwork<'a> { status: ResponseStatus, message: &str, ) -> Result<(), HandleError> { - log::warn!("Request error: {status:?}, {message}"); + log::warn!("Request error: {:?}, {}", status, message); request .send_response(status) .await? @@ -49,7 +49,7 @@ impl RequestHandler for AddNewNetwork<'_> { let post_body = match core::str::from_utf8(post_data) { Ok(body) => body, Err(err) => { - log::warn!("Invalid UTF-8 in POST body: {err}"); + log::warn!("Invalid UTF-8 in POST body: {}", err); return self .request_error( request, @@ -59,7 +59,7 @@ impl RequestHandler for AddNewNetwork<'_> { .await; } }; - log::debug!("POST body: {post_body:?}"); + log::debug!("POST body: {:?}", post_body); let (ssid, pass) = post_body.split_once('\n').unwrap_or((post_body, "")); diff --git a/config-site/src/handlers/delete_network.rs b/config-site/src/handlers/delete_network.rs index bba9ab4e..63bee5ba 100644 --- a/config-site/src/handlers/delete_network.rs +++ b/config-site/src/handlers/delete_network.rs @@ -18,7 +18,7 @@ impl<'a> DeleteNetwork<'a> { status: ResponseStatus, message: &str, ) -> Result<(), HandleError> { - log::warn!("Request error: {status:?}, {message}"); + log::warn!("Request error: {:?}, {}", status, message); request .send_response(status) .await? @@ -49,7 +49,7 @@ impl RequestHandler for DeleteNetwork<'_> { let post_body = match core::str::from_utf8(post_data) { Ok(body) => body, Err(err) => { - log::warn!("Invalid UTF-8 in POST body: {err}"); + log::warn!("Invalid UTF-8 in POST body: {}", err); return self .request_error( request, @@ -59,12 +59,12 @@ impl RequestHandler for DeleteNetwork<'_> { .await; } }; - log::debug!("POST body: {post_body:?}"); + log::debug!("POST body: {:?}", post_body); let index = match usize::from_str(post_body) { Ok(index) => index, Err(err) => { - log::warn!("Invalid index in POST body: {err}"); + log::warn!("Invalid index in POST body: {}", err); return self .request_error( request, diff --git a/device-descriptor/Cargo.toml b/device-descriptor/Cargo.toml index 0ad923f1..3e9380c1 100644 --- a/device-descriptor/Cargo.toml +++ b/device-descriptor/Cargo.toml @@ -6,3 +6,9 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +defmt = { version = "0.3.5", optional = true } + +[features] +default = ["debug"] +defmt = ["dep:defmt"] +debug = [] diff --git a/device-descriptor/src/lib.rs b/device-descriptor/src/lib.rs index 6b0f59e6..58a27f01 100644 --- a/device-descriptor/src/lib.rs +++ b/device-descriptor/src/lib.rs @@ -151,7 +151,9 @@ macro_rules! define_register_type { $name:ident = $value:expr ),+ }) => { - #[derive(Debug, PartialEq, Copy, Clone)] + #[derive(PartialEq, Copy, Clone)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + #[cfg_attr(feature = "debug", derive(Debug))] pub enum $type { $( $(#[$variant_attr])* @@ -185,7 +187,9 @@ macro_rules! register { $($(#[$field_meta:meta])* $field:ident($($field_args:tt)*): $type:ty ),* } ) => { $(#[$meta])* - #[derive(Debug, Copy, Clone)] + #[derive(Copy, Clone)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + #[cfg_attr(feature = "debug", derive(Debug))] #[must_use] #[allow(non_camel_case_types)] pub struct $reg { diff --git a/max17055/Cargo.toml b/max17055/Cargo.toml index 4ae1a5bd..fa9d41cf 100644 --- a/max17055/Cargo.toml +++ b/max17055/Cargo.toml @@ -12,3 +12,9 @@ embedded-hal = { workspace = true } embedded-hal-async = { workspace = true } log = { workspace = true } register-access = { path = "../register-access" } +defmt = { version = "0.3.5", optional = true } + +[features] +default = ["debug"] +defmt = ["dep:defmt", "device-descriptor/defmt"] +debug = ["device-descriptor/debug"] diff --git a/max17055/src/lib.rs b/max17055/src/lib.rs index 3a9f3504..2451215d 100644 --- a/max17055/src/lib.rs +++ b/max17055/src/lib.rs @@ -252,7 +252,7 @@ impl Max17055 { const DEVICE_ADDR: u8 = 0x36; pub fn new(i2c: I2C, config: DesignData) -> Self { - log::debug!("Design data: {config:?}"); + log::debug!("Design data: {:?}", config); Self { i2c, config } } diff --git a/src/backtrace.rs b/src/backtrace.rs new file mode 100644 index 00000000..c67afd91 --- /dev/null +++ b/src/backtrace.rs @@ -0,0 +1,76 @@ +use defmt::Debug2Format; +use esp_backtrace::arch; + +#[panic_handler] +fn panic_handler(info: &core::panic::PanicInfo) -> ! { + use defmt::println; + + println!(" "); + println!(" "); + + if let Some(location) = info.location() { + let (file, line, column) = (location.file(), location.line(), location.column()); + println!( + "!! A panic occured in '{}', at line {}, column {}", + file, line, column + ); + } else { + println!("!! A panic occured at an unknown location"); + } + + println!(" "); + println!("{:#?}", Debug2Format(info)); + println!(" "); + println!("Backtrace:"); + println!(" "); + + for e in arch::backtrace() { + if let Some(addr) = e { + println!("{:#X}", addr); + } + } + + halt(); +} + +#[no_mangle] +#[link_section = ".rwtext"] +unsafe fn __user_exception(cause: arch::ExceptionCause, context: arch::Context) { + use defmt::println; + + println!("\n\nException occured '{:?}'", Debug2Format(&cause)); + println!("{:?}", Debug2Format(&context)); + + for e in arch::backtrace() { + if let Some(addr) = e { + println!("{:#X}", addr); + } + } + + println!(""); + println!(""); + println!(""); + + halt(); +} + +fn halt() -> ! { + mod registers { + pub(crate) const SW_CPU_STALL: u32 = 0x600080bc; + pub(crate) const OPTIONS0: u32 = 0x60008000; + } + + let sw_cpu_stall = registers::SW_CPU_STALL as *mut u32; + let options0 = registers::OPTIONS0 as *mut u32; + + unsafe { + sw_cpu_stall.write_volatile( + sw_cpu_stall.read_volatile() & !(0b111111 << 20) & !(0b111111 << 26) + | (0x21 << 20) + | (0x21 << 26), + ); + options0.write_volatile(options0.read_volatile() & !(0b1111) | 0b1010); + } + + loop {} +} diff --git a/src/board/drivers/battery_adc.rs b/src/board/drivers/battery_adc.rs index 685470b8..280e2fc1 100644 --- a/src/board/drivers/battery_adc.rs +++ b/src/board/drivers/battery_adc.rs @@ -17,7 +17,7 @@ use embassy_futures::yield_now; use embassy_time::{Duration, Ticker}; use embedded_hal_old::adc::{Channel, OneShot}; -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, defmt::Format)] pub struct BatteryAdcData { pub voltage: u16, pub charge_current: u16, @@ -92,7 +92,7 @@ pub async fn monitor_task_adc( task_control .run_cancellable(async { let mut timer = Ticker::every(Duration::from_millis(10)); - log::info!("ADC monitor started"); + defmt::info!("ADC monitor started"); battery.lock().await.enable.set_high().unwrap(); @@ -118,7 +118,7 @@ pub async fn monitor_task_adc( }; state.data = Some(average); - log::debug!("Battery data: {average:?}"); + defmt::debug!("Battery data: {:?}", averate); sample_count = 0; @@ -135,5 +135,5 @@ pub async fn monitor_task_adc( battery.lock().await.enable.set_low().unwrap(); - log::info!("Monitor exited"); + defmt::info!("Monitor exited"); } diff --git a/src/board/drivers/battery_fg.rs b/src/board/drivers/battery_fg.rs index 59fe1ff1..f4a40605 100644 --- a/src/board/drivers/battery_fg.rs +++ b/src/board/drivers/battery_fg.rs @@ -7,7 +7,7 @@ use crate::{ board::drivers::battery_monitor::SharedBatteryState, task_control::TaskControlToken, Shared, }; -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, defmt::Format)] pub struct BatteryFgData { pub voltage: u16, pub percentage: u8, @@ -57,7 +57,7 @@ pub async fn monitor_task_fg( task_control .run_cancellable(async { let mut timer = Ticker::every(Duration::from_secs(1)); - log::info!("Fuel gauge monitor started"); + defmt::info!("Fuel gauge monitor started"); fuel_gauge.lock().await.enable(&mut Delay).await; @@ -68,7 +68,7 @@ pub async fn monitor_task_fg( let mut state = battery_state.lock().await; state.data = Some(data); } - log::debug!("Battery data: {data:?}"); + defmt::debug!("Battery data: {:?}", data); timer.next().await; } @@ -76,5 +76,5 @@ pub async fn monitor_task_fg( .await; fuel_gauge.lock().await.disable(); - log::info!("Monitor exited"); + defmt::info!("Monitor exited"); } diff --git a/src/board/drivers/frontend.rs b/src/board/drivers/frontend.rs index 3f0553ba..50b221c8 100644 --- a/src/board/drivers/frontend.rs +++ b/src/board/drivers/frontend.rs @@ -191,7 +191,7 @@ where self.frontend.device_id = Some(device_id); - log::info!("ADC device id: {:?}", device_id); + defmt::info!("ADC device id: {}", device_id); let config = self.frontend.config(); self.frontend.adc.apply_configuration_async(&config).await?; diff --git a/src/board/initialized.rs b/src/board/initialized.rs index 0dd1c7dd..badcef55 100644 --- a/src/board/initialized.rs +++ b/src/board/initialized.rs @@ -48,7 +48,7 @@ impl Board { return; } - log::info!("Saving config"); + defmt::info!("Saving config"); self.config_changed = false; if let Some(storage) = self.storage.as_mut() { @@ -56,10 +56,10 @@ impl Board { .store_writer("config", self.config, OnCollision::Overwrite) .await { - log::error!("Failed to save config: {e:?}"); + defmt::error!("Failed to save config: {:?}", defmt::Debug2Format(&e)); } } else { - log::warn!("Storage unavailable"); + defmt::warn!("Storage unavailable"); } } diff --git a/src/board/wifi/ap.rs b/src/board/wifi/ap.rs index f553b1ba..4317b85a 100644 --- a/src/board/wifi/ap.rs +++ b/src/board/wifi/ap.rs @@ -80,7 +80,7 @@ impl ApState { resources: &'static mut StackResources<3>, mut rng: Rng, ) -> Self { - log::info!("Configuring AP"); + defmt::info!("Configuring AP"); let (wifi_interface, controller) = esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Ap).unwrap(); @@ -107,16 +107,16 @@ impl ApState { pub(super) async fn start(&mut self) -> Ap { if !self.started { - log::info!("Starting AP"); + defmt::info!("Starting AP"); let spawner = Spawner::for_current_executor().await; - log::info!("Starting AP task"); + defmt::info!("Starting AP task"); spawner.must_spawn(ap_task( self.controller.clone(), self.connection_task_control.token(), self.client_count.clone(), )); - log::info!("Starting NET task"); + defmt::info!("Starting NET task"); spawner.must_spawn(net_task(self.stack.clone(), self.net_task_control.token())); self.started = true; @@ -130,7 +130,7 @@ impl ApState { pub(super) async fn stop(&mut self) { if self.started { - log::info!("Stopping AP"); + defmt::info!("Stopping AP"); let _ = join( self.connection_task_control.stop_from_outside(), self.net_task_control.stop_from_outside(), @@ -141,7 +141,7 @@ impl ApState { self.controller.lock().await.stop().await.unwrap(); } - log::info!("Stopped AP"); + defmt::info!("Stopped AP"); self.started = false; } } @@ -159,8 +159,8 @@ pub(super) async fn ap_task( ) { task_control .run_cancellable(async { - log::info!("Start connection task"); - log::debug!( + defmt::info!("Start connection task"); + defmt::debug!( "Device capabilities: {:?}", controller.lock().await.get_capabilities() ); @@ -175,10 +175,10 @@ pub(super) async fn ap_task( .await .set_configuration(&client_config) .unwrap(); - log::info!("Starting wifi"); + defmt::info!("Starting wifi"); controller.lock().await.start().await.unwrap(); - log::info!("Wifi started!"); + defmt::info!("Wifi started!"); loop { if let WifiStackState::ApStart @@ -198,18 +198,18 @@ pub(super) async fn ap_task( if events.contains(WifiEvent::ApStaconnected) { let old_count = client_count.fetch_add(1, Ordering::Release); - log::info!("Client connected, {} total", old_count + 1); + defmt::info!("Client connected, {} total", old_count + 1); } if events.contains(WifiEvent::ApStadisconnected) { let old_count = client_count.fetch_sub(1, Ordering::Release); - log::info!("Client disconnected, {} left", old_count - 1); + defmt::info!("Client disconnected, {} left", old_count - 1); } if events.contains(WifiEvent::ApStop) { - log::info!("AP stopped"); + defmt::info!("AP stopped"); return; } - log::info!("Event processing done"); + defmt::info!("Event processing done"); } } }) diff --git a/src/board/wifi/mod.rs b/src/board/wifi/mod.rs index ea4ab83c..caa79ca9 100644 --- a/src/board/wifi/mod.rs +++ b/src/board/wifi/mod.rs @@ -54,7 +54,7 @@ enum WifiDriverState { impl WifiDriverState { fn initialize(&mut self, clocks: &Clocks<'_>) { if let WifiDriverState::Uninitialized(_) = self { - log::info!("Initializing Wifi driver"); + defmt::info!("Initializing Wifi driver"); // The replacement value doesn't matter as we immediately overwrite it, // but we need to move out of the resources if let WifiDriverState::Uninitialized(resources) = self.replace_with(WifiMode::Ap) { @@ -68,7 +68,7 @@ impl WifiDriverState { ) .unwrap(), ); - log::info!("Wifi driver initialized"); + defmt::info!("Wifi driver initialized"); } else { unsafe { unreachable_unchecked() } } diff --git a/src/board/wifi/sta.rs b/src/board/wifi/sta.rs index 8e2d36be..281c46f5 100644 --- a/src/board/wifi/sta.rs +++ b/src/board/wifi/sta.rs @@ -108,7 +108,7 @@ impl StaState { resources: &'static mut StackResources<3>, mut rng: Rng, ) -> Self { - log::info!("Configuring STA"); + defmt::info!("Configuring STA"); let (wifi_interface, controller) = esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Sta).unwrap(); @@ -137,7 +137,7 @@ impl StaState { pub(super) async fn stop(&mut self) { if self.started { - log::info!("Stopping STA"); + defmt::info!("Stopping STA"); let _ = join( self.connection_task_control.stop_from_outside(), self.net_task_control.stop_from_outside(), @@ -148,17 +148,17 @@ impl StaState { self.controller.lock().await.stop().await.unwrap(); } - log::info!("Stopped STA"); + defmt::info!("Stopped STA"); self.started = false; } } pub(super) async fn start(&mut self) -> Sta { if !self.started { - log::info!("Starting STA"); + defmt::info!("Starting STA"); let spawner = Spawner::for_current_executor().await; - log::info!("Starting STA task"); + defmt::info!("Starting STA task"); spawner.must_spawn(sta_task( self.controller.clone(), self.networks.clone(), @@ -167,7 +167,7 @@ impl StaState { self.stack.clone(), self.connection_task_control.token(), )); - log::info!("Starting NET task"); + defmt::info!("Starting NET task"); spawner.must_spawn(net_task(self.stack.clone(), self.net_task_control.token())); self.started = true; @@ -200,20 +200,20 @@ pub(super) async fn sta_task( 'scan_and_connect: loop { state.store(ConnectionState::NotConnected, Ordering::Release); if !matches!(controller.lock().await.is_started(), Ok(true)) { - log::info!("Starting wifi"); + defmt::info!("Starting wifi"); controller.lock().await.start().await.unwrap(); - log::info!("Wifi started!"); + defmt::info!("Wifi started!"); } let connect_to = 'select: loop { - log::info!("Scanning..."); + defmt::info!("Scanning..."); let mut scan_results = Box::new(controller.lock().await.scan_n::().await); match scan_results.as_mut() { Ok((ref mut visible_networks, network_count)) => { - log::info!("Found {network_count} access points"); + defmt::info!("Found {} access points", network_count); // Sort by signal strength, descending visible_networks @@ -246,13 +246,13 @@ pub(super) async fn sta_task( *preference = NetworkPreference::Preferred; } } - Err(err) => log::warn!("Scan failed: {err:?}"), + Err(err) => defmt::warn!("Scan failed: {:?}", defmt::Debug2Format(&err)), } Timer::after(SCAN_PERIOD).await; }; - log::info!("Connecting to {}...", connect_to.ssid); + defmt::info!("Connecting to {}...", connect_to.ssid); state.store(ConnectionState::Connecting, Ordering::Release); controller @@ -268,12 +268,12 @@ pub(super) async fn sta_task( for _ in 0..CONNECT_RETRY_COUNT { match controller.lock().await.connect().await { Ok(_) => { - log::info!("Waiting to get IP address..."); + defmt::info!("Waiting to get IP address..."); let wait_for_ip = async { loop { if let Some(config) = stack.config_v4() { - log::info!("Got IP: {}", config.address); + defmt::info!("Got IP: {}", config.address); break; } Timer::after(Duration::from_millis(500)).await; @@ -288,7 +288,7 @@ pub(super) async fn sta_task( match select(wait_for_ip, wait_for_disconnect).await { Either::First(_) => { - log::info!("Wifi connected!"); + defmt::info!("Wifi connected!"); state.store(ConnectionState::Connected, Ordering::Release); // keep pending Disconnected event to avoid a race condition @@ -300,18 +300,21 @@ pub(super) async fn sta_task( // TODO: figure out if we should deprioritize, retry or just loop back // to the beginning. Maybe we could use a timer? - log::info!("Wifi disconnected!"); + defmt::info!("Wifi disconnected!"); state.store(ConnectionState::NotConnected, Ordering::Release); continue 'scan_and_connect; } Either::Second(_) => { - log::info!("Wifi disconnected!"); + defmt::info!("Wifi disconnected!"); state.store(ConnectionState::NotConnected, Ordering::Release); } } } Err(e) => { - log::warn!("Failed to connect to wifi: {e:?}"); + defmt::warn!( + "Failed to connect to wifi: {:?}", + defmt::Debug2Format(&e) + ); state.store(ConnectionState::NotConnected, Ordering::Release); Timer::after(CONNECT_RETRY_PERIOD).await; } diff --git a/src/heap.rs b/src/heap.rs index 1591ce0c..430d1c03 100644 --- a/src/heap.rs +++ b/src/heap.rs @@ -11,7 +11,7 @@ pub fn init_heap() { unsafe { let heap_size = HEAP.len(); - log::info!("Heap size: {heap_size}"); + defmt::info!("Heap size: {}", heap_size); ALLOCATOR.init(addr_of_mut!(HEAP).cast(), heap_size); } } diff --git a/src/main.rs b/src/main.rs index 6a623e5d..3eba9668 100644 --- a/src/main.rs +++ b/src/main.rs @@ -57,6 +57,7 @@ use crate::{ }, }; +mod backtrace; mod board; mod defmt_backend; mod heap; @@ -72,11 +73,13 @@ pub type Shared = Rc>; pub type SharedGuard<'a, T> = MutexGuard<'a, NoopRawMutex, T>; #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum AppError { Adc, } #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum AppState { AdcSetup, Initialize, @@ -119,10 +122,10 @@ fn main() -> ! { let _stack_protection = stack_protection::StackMonitor::protect((stack_start + 4)..stack_end); #[cfg(feature = "hw_v1")] - log::info!("Hardware version: v1"); + defmt::info!("Hardware version: v1"); #[cfg(feature = "hw_v2")] - log::info!("Hardware version: v2"); + defmt::info!("Hardware version: v2"); let executor = singleton!(Executor::new()); executor.run(move |spawner| { @@ -138,7 +141,7 @@ async fn setup_storage( let storage = match Storage::mount(unsafe { &mut READ_CACHE }).await { Ok(storage) => Ok(storage), Err(StorageError::NotFormatted) => { - log::info!("Formatting storage"); + defmt::info!("Formatting storage"); Storage::format_and_mount(unsafe { &mut READ_CACHE }).await } e => e, @@ -147,7 +150,7 @@ async fn setup_storage( match storage { Ok(storage) => Some(singleton!(storage)), Err(e) => { - log::error!("Failed to mount storage: {:?}", e); + defmt::error!("Failed to mount storage: {:?}", defmt::Debug2Format(&e)); None } } @@ -160,7 +163,7 @@ where static CONFIG: StaticCell = StaticCell::new(); if let Some(storage) = storage { - log::info!( + defmt::info!( "Storage: {} / {} used", storage.capacity() - storage.free_bytes(), storage.capacity() @@ -170,17 +173,17 @@ where Ok(mut config) => match config.read_loadable::(storage).await { Ok(config) => CONFIG.init(config.into_config()), Err(e) => { - log::warn!("Failed to read config file: {e:?}. Reverting to defaults"); + defmt::warn!("Failed to read config file: {}. Reverting to defaults", e); CONFIG.init(Config::default()) } }, Err(e) => { - log::warn!("Failed to load config: {e:?}. Reverting to defaults"); + defmt::warn!("Failed to load config: {}. Reverting to defaults", e); CONFIG.init(Config::default()) } } } else { - log::warn!("Storage unavailable. Using default config"); + defmt::warn!("Storage unavailable. Using default config"); CONFIG.init(Config::default()) } } @@ -231,7 +234,7 @@ async fn main_task(_spawner: Spawner, resources: StartupResources) { let mut state = AppState::AdcSetup; loop { - log::info!("New app state: {state:?}"); + defmt::info!("New app state: {}", state); state = match state { AppState::AdcSetup => adc_setup(&mut board).await, AppState::Initialize => initialize(&mut board).await, diff --git a/src/stack_protection.rs b/src/stack_protection.rs index 3f27a479..f45c547f 100644 --- a/src/stack_protection.rs +++ b/src/stack_protection.rs @@ -21,7 +21,7 @@ fn conjure() -> DebugAssist<'static> { impl StackMonitor { pub fn protect(stack: Range) -> Self { - log::info!( + defmt::info!( "StackMonitor::protect({:#x}, {})", stack.start, stack.end - stack.start diff --git a/src/states/measure.rs b/src/states/measure.rs index cd2287e9..fbd9a56e 100644 --- a/src/states/measure.rs +++ b/src/states/measure.rs @@ -122,7 +122,7 @@ async fn measure_impl( let ret = match frontend.read_clksel().await { Ok(PinState::Low) => { - log::info!("CLKSEL low, enabling faster clock speeds"); + defmt::info!("CLKSEL low, enabling faster clock speeds"); let result = frontend.enable_fast_clock().await; if result.is_ok() { @@ -202,8 +202,9 @@ async fn measure_impl( } if debug_print_timer.is_elapsed() { - log::debug!( - "Collected {samples} samples in {}ms", + defmt::debug!( + "Collected {} samples in {}ms", + samples, debug_print_timer.elapsed().as_millis() ); samples = 0; @@ -251,7 +252,7 @@ async fn read_ecg( match frontend.read().await { Ok(sample) => { if !frontend.is_touched() { - log::info!("Not touched, stopping"); + defmt::info!("Not touched, stopping"); return Ok(()); } @@ -259,13 +260,13 @@ async fn read_ecg( .try_send(Message::Sample(sample.ch1_sample())) .is_err() { - log::warn!("Sample lost"); + defmt::warn!("Sample lost"); } } Err(e) => return Err(e), } } - log::info!("Stop requested, stopping"); + defmt::info!("Stop requested, stopping"); Ok(()) } diff --git a/src/states/menu/display.rs b/src/states/menu/display.rs index baad73d6..6c598774 100644 --- a/src/states/menu/display.rs +++ b/src/states/menu/display.rs @@ -78,7 +78,7 @@ pub async fn display_menu(board: &mut Board) -> AppState { } if &menu_values != menu_screen.content.data() { - log::debug!("Settings changed"); + defmt::debug!("Settings changed"); let new = *menu_screen.content.data(); if menu_values.brightness != new.brightness { board.config_changed = true; @@ -111,7 +111,7 @@ pub async fn display_menu(board: &mut Board) -> AppState { ticker.next().await; } - log::info!("Menu timeout"); + defmt::info!("Menu timeout"); board.save_config().await; AppState::Shutdown } diff --git a/src/states/menu/main.rs b/src/states/menu/main.rs index 72695f06..9ffb82df 100644 --- a/src/states/menu/main.rs +++ b/src/states/menu/main.rs @@ -36,7 +36,7 @@ pub async fn main_menu(board: &mut Board) -> AppState { }; let mut exit_timer = Timeout::new(MENU_IDLE_DURATION); - log::info!("Free heap: {} bytes", ALLOCATOR.free()); + defmt::info!("Free heap: {} bytes", ALLOCATOR.free()); let builder = Menu::with_style("Main menu", menu_style()); @@ -128,6 +128,6 @@ pub async fn main_menu(board: &mut Board) -> AppState { ticker.next().await; } - log::info!("Menu timeout"); + defmt::info!("Menu timeout"); AppState::Shutdown } diff --git a/src/states/menu/mod.rs b/src/states/menu/mod.rs index 74eeaeea..837ccc4a 100644 --- a/src/states/menu/mod.rs +++ b/src/states/menu/mod.rs @@ -7,6 +7,7 @@ pub mod wifi_ap; pub mod wifi_sta; #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum AppMenu { Main, Display, diff --git a/src/states/menu/wifi_ap.rs b/src/states/menu/wifi_ap.rs index 819f4f01..697b3ae0 100644 --- a/src/states/menu/wifi_ap.rs +++ b/src/states/menu/wifi_ap.rs @@ -146,7 +146,7 @@ async fn webserver_task( context: Rc, mut task_control: TaskControlToken<()>, ) { - log::info!("Started webserver task"); + defmt::info!("Started webserver task"); task_control .run_cancellable(async { let mut resources = Box::new(WebserverResources { @@ -191,5 +191,5 @@ async fn webserver_task( .await; }) .await; - log::info!("Stopped webserver task"); + defmt::info!("Stopped webserver task"); }