simplify audio locking with local refcell rather than thread local

This commit is contained in:
2020-11-03 10:08:30 -08:00
parent 4a66223542
commit e17c88873a

View File

@@ -19,10 +19,6 @@ const HUE_KEY: &str = include_str!("../hue.key");
const BUTTON_PIN: u8 = 26;
const CHANNEL_VEC_SIZE: usize = 32;
thread_local! {
static AUDIO_CHILD: RefCell<Option<process::Child>> = RefCell::new(None);
}
#[tokio::main(basic_scheduler)]
async fn main() {
pretty_env_logger::init_timed();
@@ -36,13 +32,15 @@ async fn main() {
pin.set_async_interrupt(Trigger::FallingEdge, move |_| button_pressed(&clients))
.expect("set interrupt");
let reqwest = &reqwest::Client::new();
let (tx, rx) = mpsc::channel(1);
events_clients.lock().unwrap().push(tx);
let reqwest = &reqwest::Client::new();
let audio_child = &RefCell::new(None);
let hue_busy = &Cell::new(false);
let pushes = rx.for_each_concurrent(2, |()| async move {
if !audio_busy() {
play_chime()
if !audio_busy(&audio_child) {
play_chime(&audio_child)
} else { debug!("doorbell still ringing, not playing new chime"); }
if !hue_busy.replace(true) {
@@ -107,25 +105,23 @@ async fn warp(clients: Arc<Mutex<SmallVec<[mpsc::Sender<()>; CHANNEL_VEC_SIZE]>>
warp::serve(routes).run(([0, 0, 0, 0], 8060)).await;
}
fn audio_busy() -> bool {
AUDIO_CHILD.with(|cell| {
if let Some(ref mut audio_child) = *cell.borrow_mut() {
fn audio_busy(audio_child: &RefCell<Option<process::Child>>) -> bool {
if let Some(ref mut audio_child) = *audio_child.borrow_mut() {
if let Ok(None) = audio_child.try_wait() {
return true;
}
}
false
})
}
fn play_chime() {
fn play_chime(audio_child: &RefCell<Option<process::Child>>) {
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))); },
Ok(child) => { audio_child.replace(Some(child)); },
Err(err) => error!("Error playing outdoor chime: {}", err)
};
}