From d150c707001daefb5eedc2abca7a6b2bd060e67b Mon Sep 17 00:00:00 2001 From: Hubald Verzijl Date: Tue, 16 Sep 2025 16:19:33 +0200 Subject: [PATCH] Use signals instead of mutex. --- src/communication.rs | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/src/communication.rs b/src/communication.rs index 00799da..2a7154e 100644 --- a/src/communication.rs +++ b/src/communication.rs @@ -1,9 +1,9 @@ use defmt::info; use embassy_executor::Spawner; -use embassy_sync::mutex::Mutex; use embassy_sync::blocking_mutex::raw::{ThreadModeRawMutex, CriticalSectionRawMutex}; use embassy_sync::signal::Signal; +use embassy_futures::select::{select, Either}; use embassy_stm32::usb::Driver; use embassy_stm32::{peripherals, uid, usb}; @@ -159,7 +159,7 @@ pub async fn set_green_led_handler(_context: &mut Context, _header: VarHeader, r LED_FREQUENCY_SIGNAL.signal(rqst); } -static STOP: Mutex = Mutex::new(false); +static STOP: Signal = Signal::new(); #[embassy_executor::task] pub async fn start_single_impedance_handler(context: SpawnCtx, header: VarHeader, rqst: StartImpedance, sender: Sender) { @@ -183,31 +183,39 @@ pub async fn start_single_impedance_handler(context: SpawnCtx, header: VarHeader } let mut seq: u8 = 0; - while !*STOP.lock().await { + loop { + let stop_fut = STOP.wait(); + let recv_fut = IMPEDANCE_CHANNEL.receive(); - let msg = IMPEDANCE_CHANNEL.receive().await; - - if sender - .publish::(seq.into(), &msg) - .await - .is_err() - { - defmt::error!("Topic send error!"); - break; + match select(stop_fut, recv_fut).await { + Either::First(_) => { + info!("Stop signal received."); + break; + } + Either::Second(msg) => { + if sender + .publish::(seq.into(), &msg) + .await + .is_err() + { + defmt::error!("Topic send error!"); + break; + } + seq = seq.wrapping_add(1); + } } - seq = seq.wrapping_add(1); } context.impedance_setup.lock().await.running = false; info!("Impedance measurement stopped."); - *STOP.lock().await = false; + STOP.reset(); } pub async fn stop_single_impedance_handler(context: &mut Context, _header: VarHeader, _rqst: ()) -> bool { info!("Stop impedance measurement"); let was_busy = context.impedance_setup.lock().await.running; if was_busy { - *STOP.lock().await = true; + STOP.signal(()); } was_busy } \ No newline at end of file