Skip to content

Commit

Permalink
Merge pull request #82 from nerwalt/defmt-feature
Browse files Browse the repository at this point in the history
defmt is now a feature
  • Loading branch information
Ragarnoy authored Jul 13, 2024
2 parents 63ddbb8 + 300ff84 commit 1d54532
Show file tree
Hide file tree
Showing 13 changed files with 64 additions and 43 deletions.
9 changes: 5 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ categories = ["embedded", "no-std"]
readme = "README.md"
license = "MIT"
edition = "2021"
version = "0.1.2"
version = "0.1.3"
rust-version = "1.77"

[dependencies]
a121-sys = { version = "0.4", features = ["distance", "presence"] }
defmt = "0.3.5"
defmt-rtt = "0.4.0"

defmt = { version = "0.3", optional = true }

embedded-hal = "1.0.0"
embedded-hal-async = "1.0.0"
Expand All @@ -32,8 +32,9 @@ cc = "1.0"
distance = ["a121-sys/distance"]
presence = ["a121-sys/presence"]
libm = ["dep:libm", "num/libm"]
nightly-logger = []
nightly-logger = ["defmt"]
std = []
defmt = ["dep:defmt"]

[profile.dev]
lto = true
Expand Down
2 changes: 1 addition & 1 deletion examples/xe121_l433rc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021"

[dependencies]
a121-rs = { path = "../../../a121-rs", features = ["distance"] }
a121-rs = { path = "../../../a121-rs", features = ["distance", "defmt"] }

panic-probe = { version = "0.3", features = ["print-defmt"] }

Expand Down
1 change: 0 additions & 1 deletion examples/xe125-nightly/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#![warn(missing_docs)]

use core::num::NonZeroU8;
use defmt::trace;

use num::Zero;

Expand Down Expand Up @@ -81,9 +80,11 @@ impl Drop for RadarConfig {
impl RadarConfig {
/// Creates a new radar configuration instance with a specified ID.
pub fn new() -> Self {
trace!("Creating radar configuration");
#[cfg(feature = "defmt")]
defmt::trace!("Creating radar configuration");
let inner = unsafe { acc_config_create() };
trace!("Radar configuration created");
#[cfg(feature = "defmt")]
defmt::trace!("Radar configuration created");
Self {
inner,
num_subsweep: None,
Expand Down
3 changes: 2 additions & 1 deletion src/config/profile.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use a121_sys::acc_config_profile_t_ACC_CONFIG_PROFILE_1;

#[derive(Debug, PartialEq, defmt::Format)]
#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
/// Radar profiles indicating different settings for the sensor's RX and TX paths.
pub enum RadarProfile {
/// Profile 1
Expand Down
7 changes: 4 additions & 3 deletions src/detector/distance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use crate::sensor::calibration::CalibrationResult;
use crate::sensor::error::SensorError;
use a121_sys::*;
use core::ffi::c_void;
use defmt::trace;
use embedded_hal::digital::OutputPin;
use embedded_hal_async::delay::DelayNs;
use embedded_hal_async::digital::Wait;
Expand Down Expand Up @@ -64,7 +63,8 @@ where
pub fn new(radar: &'radar mut Radar<Ready, SINT, ENABLE, DLY>) -> Self {
let config = RadarDistanceConfig::default();
let inner = InnerRadarDistanceDetector::new(&config);
trace!("{:?}", DistanceSizes::new(&inner));
#[cfg(feature = "defmt")]
defmt::trace!("{:?}", DistanceSizes::new(&inner));
Self {
radar,
inner,
Expand All @@ -78,7 +78,8 @@ where
config: RadarDistanceConfig,
) -> Self {
let inner = InnerRadarDistanceDetector::new(&config);
trace!("{:?}", DistanceSizes::new(&inner));
#[cfg(feature = "defmt")]
defmt::trace!("{:?}", DistanceSizes::new(&inner));
Self {
radar,
inner,
Expand Down
9 changes: 6 additions & 3 deletions src/detector/distance/results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@ use a121_sys::{
};

/// Enumerates possible errors that can occur during the processing of radar data.
#[derive(Debug, Copy, Clone, defmt::Format)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ProcessDataError {
CalibrationNeeded,
ProcessingFailed,
Unavailable,
}

/// Represents a single detected distance and its strength.
#[derive(Debug, Default, Copy, Clone, defmt::Format)]
#[derive(Debug, Default, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Distance {
pub distance: f32,
pub strength: f32,
Expand Down Expand Up @@ -136,7 +138,8 @@ impl Default for DynamicResult {
///
/// This struct holds information about the required buffer sizes for distance detection
/// operations, including the static part of the detector calibration result.
#[derive(Debug, defmt::Format)]
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub(super) struct DistanceSizes {
pub buffer_size: usize,
pub detector_cal_result_static_size: usize,
Expand Down
4 changes: 3 additions & 1 deletion src/detector/presence/results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ impl Default for PresenceResult<'_> {
}

/// Enumerates possible errors that can occur during the processing of radar data for presence detection.
#[derive(Debug, Copy, Clone, defmt::Format)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ProcessDataError {
CalibrationNeeded,
ProcessingFailed,
Expand Down Expand Up @@ -117,6 +118,7 @@ impl Default for PresenceMetadata {
Self {
inner: acc_detector_presence_metadata_t {
start_m: 0.0,
end_m: 6.0,
step_length_m: 0.0,
num_points: 0,
profile: acc_config_profile_t_ACC_CONFIG_PROFILE_5,
Expand Down
53 changes: 31 additions & 22 deletions src/hal.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use core::cell::RefCell;
use core::ffi::{c_char, c_void, CStr};
use defmt::trace;
use core::ffi::{c_char, c_void};

#[cfg(feature = "defmt")]
use core::ffi::CStr;

use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::blocking_mutex::Mutex;
Expand Down Expand Up @@ -75,15 +77,18 @@ impl AccHalImpl {
#[allow(dead_code)]
extern "C" fn transfer16_function(
_sensor_id: acc_sensor_id_t,
buffer: *mut u16,
buffer_length: usize,
_buffer: *mut u16,
_buffer_length: usize,
) {
let tmp_buf = unsafe { core::slice::from_raw_parts_mut(buffer, buffer_length) };
trace!(
"Transfer16 function called: buffer={:#X} (size:{})",
tmp_buf,
buffer_length
);
#[cfg(feature = "defmt")]
{
let tmp_buf = unsafe { core::slice::from_raw_parts_mut(_buffer, _buffer_length) };
defmt::trace!(
"Transfer16 function called: buffer={:#X} (size:{})",
tmp_buf,
_buffer_length
);
}
// Borrow a mutable reference to the SpiBus
SPI_INSTANCE.lock(|cell| unsafe {
let mut binding = cell.borrow_mut();
Expand Down Expand Up @@ -118,7 +123,8 @@ impl AccHalImpl {
/// Panics if the HAL registration fails.
#[inline(always)]
pub fn register(&self) {
trace!("Registering HAL");
#[cfg(feature = "defmt")]
defmt::trace!("Registering HAL");
let result = unsafe { acc_rss_hal_register(&self.inner) };
assert!(result, "Failed to register HAL");
}
Expand Down Expand Up @@ -157,6 +163,7 @@ unsafe extern "C" fn logger(
let module = unsafe { CStr::from_ptr(module) };
let format = unsafe { CStr::from_ptr(format) };
let message = format.to_str().unwrap_or("");

match level {
0 => defmt::error!("{}: {}", module.to_str().unwrap_or(""), message),
1 => defmt::warn!("{}: {}", module.to_str().unwrap_or(""), message),
Expand All @@ -172,16 +179,18 @@ unsafe extern "C" fn logger(
/// # Safety
/// This function is unsafe because it takes a raw pointer.
#[no_mangle]
pub unsafe extern "C" fn rust_log(level: u32, message: *const c_char) {
let c_str = unsafe { CStr::from_ptr(message) };
let str_slice = c_str.to_str().unwrap_or("");

match level {
0 => defmt::error!("{}", str_slice),
1 => defmt::warn!("{}", str_slice),
2 => defmt::info!("{}", str_slice),
3 => defmt::debug!("{}", str_slice),
4 => defmt::trace!("{}", str_slice),
_ => defmt::error!("Unknown log level: {}", level),
pub unsafe extern "C" fn rust_log(_level: u32, _message: *const c_char) {
#[cfg(feature = "defmt")]
{
let c_str = unsafe { CStr::from_ptr(_message) };
let str_slice = c_str.to_str().unwrap_or("");
match _level {
0 => defmt::error!("{}", str_slice),
1 => defmt::warn!("{}", str_slice),
2 => defmt::info!("{}", str_slice),
3 => defmt::debug!("{}", str_slice),
4 => defmt::trace!("{}", str_slice),
_ => defmt::error!("Unknown log level: {}", _level),
}
}
}
1 change: 1 addition & 0 deletions src/radar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ pub struct RssVersion {
version: u32,
}

#[cfg(feature = "defmt")]
impl defmt::Format for RssVersion {
fn format(&self, f: defmt::Formatter) {
defmt::write!(f, "{}.{}.{}", self.major(), self.minor(), self.patch())
Expand Down
7 changes: 4 additions & 3 deletions src/sensor.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use core::ffi::c_void;

use core::ops::{Deref, DerefMut};
use defmt::trace;
use embedded_hal::digital::OutputPin;
use embedded_hal_async::delay::DelayNs;

Expand Down Expand Up @@ -79,7 +78,8 @@ where
/// # Returns
/// `Some(Sensor)` if the sensor instance was successfully created, `None` otherwise.
pub fn new(sensor_id: u32, enable_pin: ENABLE, delay: DLY) -> Option<Self> {
trace!("Creating sensor {}", sensor_id);
#[cfg(feature = "defmt")]
defmt::trace!("Creating sensor {}", sensor_id);
let inner = InnerSensor::new(sensor_id)?;
Some(Self {
inner,
Expand Down Expand Up @@ -196,7 +196,8 @@ where
);
}
if ret {
trace!("Sensor prepared");
#[cfg(feature = "defmt")]
defmt::trace!("Sensor prepared");
Ok(())
} else {
Err(SensorError::PrepareFailed)
Expand Down
1 change: 1 addition & 0 deletions src/sensor/calibration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub struct CalibrationResult {
inner: acc_cal_result_t,
}

#[cfg(feature = "defmt")]
impl defmt::Format for CalibrationResult {
fn format(&self, f: defmt::Formatter) {
defmt::write!(f, "{:?}", self.inner.data)
Expand Down
3 changes: 2 additions & 1 deletion src/sensor/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#[derive(Debug, Copy, Clone, defmt::Format)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SensorError {
CalibrationFailed,
PrepareFailed,
Expand Down

0 comments on commit 1d54532

Please sign in to comment.