Skip to content

Commit

Permalink
Use defmt in app
Browse files Browse the repository at this point in the history
  • Loading branch information
bugadani committed Aug 26, 2023
1 parent 2712ad5 commit a00137f
Show file tree
Hide file tree
Showing 27 changed files with 207 additions and 93 deletions.
8 changes: 3 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ embassy-net = { version = "0.1.0", features = [
"udp",
"dhcpv4",
"medium-ethernet",
"defmt"
] }
embassy-sync = { version = "0.2.0" }

Expand Down Expand Up @@ -55,10 +56,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",
Expand Down Expand Up @@ -90,7 +88,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 = [
Expand Down
6 changes: 6 additions & 0 deletions ads129x/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
8 changes: 7 additions & 1 deletion ads129x/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ pub enum Error<SpiE> {
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,
Expand Down Expand Up @@ -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,
}
Expand All @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions bad-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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));
}
};
Expand Down
4 changes: 2 additions & 2 deletions bad-server/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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])
}
Expand Down
6 changes: 3 additions & 3 deletions config-site/src/handlers/add_new_network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl<'a> AddNewNetwork<'a> {
status: ResponseStatus,
message: &str,
) -> Result<(), HandleError<C>> {
log::warn!("Request error: {status:?}, {message}");
log::warn!("Request error: {:?}, {}", status, message);
request
.send_response(status)
.await?
Expand Down Expand Up @@ -49,7 +49,7 @@ impl<C: Connection> RequestHandler<C> 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,
Expand All @@ -59,7 +59,7 @@ impl<C: Connection> RequestHandler<C> 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, ""));

Expand Down
8 changes: 4 additions & 4 deletions config-site/src/handlers/delete_network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl<'a> DeleteNetwork<'a> {
status: ResponseStatus,
message: &str,
) -> Result<(), HandleError<C>> {
log::warn!("Request error: {status:?}, {message}");
log::warn!("Request error: {:?}, {}", status, message);
request
.send_response(status)
.await?
Expand Down Expand Up @@ -49,7 +49,7 @@ impl<C: Connection> RequestHandler<C> 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,
Expand All @@ -59,12 +59,12 @@ impl<C: Connection> RequestHandler<C> 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,
Expand Down
6 changes: 6 additions & 0 deletions device-descriptor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []
8 changes: 6 additions & 2 deletions device-descriptor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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])*
Expand Down Expand Up @@ -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 {
Expand Down
6 changes: 6 additions & 0 deletions max17055/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
2 changes: 1 addition & 1 deletion max17055/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ impl<I2C> Max17055<I2C> {
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 }
}

Expand Down
76 changes: 76 additions & 0 deletions src/backtrace.rs
Original file line number Diff line number Diff line change
@@ -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 {}
}
8 changes: 4 additions & 4 deletions src/board/drivers/battery_adc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();

Expand All @@ -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;

Expand All @@ -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");
}
8 changes: 4 additions & 4 deletions src/board/drivers/battery_fg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;

Expand All @@ -68,13 +68,13 @@ 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;
}
})
.await;

fuel_gauge.lock().await.disable();
log::info!("Monitor exited");
defmt::info!("Monitor exited");
}
2 changes: 1 addition & 1 deletion src/board/drivers/frontend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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?;
Expand Down
6 changes: 3 additions & 3 deletions src/board/initialized.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,18 @@ impl Board {
return;
}

log::info!("Saving config");
defmt::info!("Saving config");
self.config_changed = false;

if let Some(storage) = self.storage.as_mut() {
if let Err(e) = storage
.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");
}
}

Expand Down
Loading

0 comments on commit a00137f

Please sign in to comment.