From c05168bec880faddc61b86051423326fd9db66e2 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 19 Oct 2023 09:11:56 +0700 Subject: [PATCH] Make control/wakeup wait for connect before starting the countdown --- src/mqtt/mod.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index 0dc2f20..a0b1cf5 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -968,10 +968,28 @@ async fn handle_mqtt_message( } => { let reply = match message.parse::() { Ok(secs) => { - let wake_time = Instant::now() + Duration::from_secs(secs * 60); if let Ok(permit) = camera.permit().await { + let (tx, rx) = mpsc(1); + + // By using a run_task we can delay the countdown until AFTER we are connected + let _ = camera.run_task(|cam| { + let tx = tx.clone(); + Box::pin(async move { + let _ = tx.try_send(()); // Camera online, start the countdown + AnyResult::Ok(()) + }) + }); + + // This task waits for the `run_task` to send the OK then starts the countdown + // to drop the permit tokio::task::spawn(async move { - sleep_until(wake_time).await; + // Wait for connection then start the countdown + let _ = rx.recv().await; + + log::debug!("Wakeup counting down"); + sleep(Duration::from_secs(secs * 60)).await; + + log::debug!("Wakeup complete"); drop(permit); }); "OK"