simplify hue locking with local cell rather than global atomic

This commit is contained in:
2020-11-03 09:04:24 -08:00
parent 641fd5ae38
commit fbb7dea664

View File

@@ -1,7 +1,6 @@
use std::cell::RefCell; use std::cell::{Cell, RefCell};
use std::convert::Infallible; use std::convert::Infallible;
use std::process; use std::process;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
@@ -23,7 +22,6 @@ const CHANNEL_VEC_SIZE: usize = 32;
thread_local! { thread_local! {
static AUDIO_CHILD: RefCell<Option<process::Child>> = RefCell::new(None); static AUDIO_CHILD: RefCell<Option<process::Child>> = RefCell::new(None);
} }
static HUE_LOCKED: AtomicBool = AtomicBool::new(false);
#[tokio::main(basic_scheduler)] #[tokio::main(basic_scheduler)]
async fn main() { async fn main() {
@@ -38,18 +36,18 @@ async fn main() {
pin.set_async_interrupt(Trigger::FallingEdge, move |level| button_pressed(level, &clients)) pin.set_async_interrupt(Trigger::FallingEdge, move |level| button_pressed(level, &clients))
.expect("set interrupt"); .expect("set interrupt");
let reqwest = reqwest::Client::new(); let reqwest = &reqwest::Client::new();
let (tx, rx) = mpsc::channel(1); let (tx, rx) = mpsc::channel(1);
events_clients.lock().unwrap().push(tx); events_clients.lock().unwrap().push(tx);
let pushes = rx.for_each_concurrent(2, |()| async { let hue_busy = &Cell::new(false);
let pushes = rx.for_each_concurrent(2, |()| async move {
if !audio_busy() { if !audio_busy() {
play_chime() play_chime()
} else { debug!("doorbell still ringing, not playing new chime"); } } else { debug!("doorbell still ringing, not playing new chime"); }
let locked = HUE_LOCKED.compare_and_swap(false, true, Ordering::Acquire); if !hue_busy.replace(true) {
if !locked { flash_porch(&reqwest).await;
flash_patio(&reqwest).await; hue_busy.set(false);
HUE_LOCKED.store(false, Ordering::Release);
} else { debug!("hue already in use, not scheduling new flashing"); } } else { debug!("hue already in use, not scheduling new flashing"); }
}); });
@@ -139,7 +137,7 @@ async fn hue_base(reqwest: &reqwest::Client, body: &'static str, delay_millis: u
delay_for(Duration::from_millis(delay_millis)).await; delay_for(Duration::from_millis(delay_millis)).await;
} }
async fn flash_patio(reqwest: &reqwest::Client) { async fn flash_porch(reqwest: &reqwest::Client) {
hue_base(reqwest, hue_base(reqwest,
r#"{"transitiontime":0,"on":true,"bri":254,"sat":254}"#, // activate/resaturate r#"{"transitiontime":0,"on":true,"bri":254,"sat":254}"#, // activate/resaturate
250).await; 250).await;