From ab961382ba9f0b47a3832a3452ad41ea0207e4ee Mon Sep 17 00:00:00 2001 From: Jared Burce Date: Thu, 29 Oct 2020 06:30:20 -0700 Subject: [PATCH] Move audio playback to toplevel, out of sse stream generation --- src/main.rs | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/main.rs b/src/main.rs index 0d10408..b00ba8d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,7 +4,7 @@ use std::process; use std::sync::{Arc, Mutex}; use std::time::Duration; -use futures_util::{stream, StreamExt}; +use futures_util::{FutureExt, select, stream, StreamExt}; #[allow(unused_imports)] use log::{debug, error, info, trace}; use rppal::gpio::{Gpio, Level, Trigger}; use smallvec::SmallVec; @@ -46,8 +46,27 @@ async fn main() { pin.set_async_interrupt(Trigger::FallingEdge, move |level| button_pressed(level, &clients)) .expect("set interrupt"); - let warp = warp(events_clients); - warp.await; + let (tx, rx) = mpsc::channel(1); + events_clients.lock().unwrap().push(tx); + let pushes = rx.for_each(|()| { + if !audio_busy() { + trace!("Playing doorbell chime"); + match process::Command::new("mplayer") + .arg(OUTDOOR_CHIME_FILE) + .stdout(process::Stdio::null()) + .stderr(process::Stdio::null()) + .spawn() { + Ok(child) => { AUDIO_CHILD.with(|cell| cell.replace(Some(child))); }, + Err(err) => error!("Error playing outdoor chime: {}", err) + }; + } else { debug!("doorbell still ringing, not playing new chime"); } + futures_util::future::ready(()) + }); + + select! { + _ = warp(events_clients).fuse() => (), + _ = pushes.fuse() => () + } } async fn warp(clients: Arc; CHANNEL_VEC_SIZE]>>>) { @@ -72,18 +91,6 @@ async fn warp(clients: Arc; CHANNEL_VEC_SIZE]>> }), rx.map(|()| { - if !audio_busy() { - trace!("Playing doorbell chime"); - match process::Command::new("mplayer") - .arg(OUTDOOR_CHIME_FILE) - .stdout(process::Stdio::null()) - .stderr(process::Stdio::null()) - .spawn() { - Ok(child) => { AUDIO_CHILD.with(|cell| cell.replace(Some(child))); }, - Err(err) => error!("Error playing outdoor chime: {}", err) - }; - } else { debug!("doorbell still ringing, not playing new chime"); } - debug!("sending ring sse"); Ok::<_, Infallible>((sse::event("ring"), sse::data("")).into_b()) })