use parking_lot::Mutex;
use super::{
sample::MotionConfig,
sensor::{latest, platform},
status::{DeviceMotionPermission, DeviceMotionStatus, announce, store_status},
};
struct Session {
next_id: u64,
leases: Vec<(u64, MotionConfig)>,
running: Option<MotionConfig>,
}
static SESSION: Mutex<Session> = Mutex::new(Session {
next_id: 1,
leases: Vec::new(),
running: None,
});
pub struct DeviceMotionLease {
id: u64,
}
fn locked<R>(change: impl FnOnce(&mut Session) -> R) -> R {
change(&mut SESSION.lock())
}
impl Drop for DeviceMotionLease {
fn drop(&mut self) {
let changed = locked(|session| {
session.leases.retain(|(id, _)| *id != self.id);
reconcile(session)
});
announce(changed);
}
}
pub fn start_device_motion(config: MotionConfig) -> DeviceMotionLease {
let (id, changed) = locked(|session| {
let id = session.next_id;
session.next_id += 1;
session.leases.push((id, config));
(id, reconcile(session))
});
announce(changed);
DeviceMotionLease { id }
}
fn wanted(leases: &[(u64, MotionConfig)]) -> Option<MotionConfig> {
let (_, first) = leases.first()?;
let rate = leases
.iter()
.fold(first.rate, |rate, (_, config)| rate.or_faster(config.rate));
Some(MotionConfig {
reference: first.reference,
rate,
})
}
fn resting_status() -> DeviceMotionStatus {
match platform() {
None => DeviceMotionStatus::Unavailable,
Some(sensor) => match sensor.permission() {
DeviceMotionPermission::Granted => DeviceMotionStatus::Idle,
DeviceMotionPermission::Denied => DeviceMotionStatus::Denied,
DeviceMotionPermission::NotAsked => DeviceMotionStatus::NeedsPermission,
},
}
}
pub(super) fn forget_running() {
SESSION.lock().running = None;
}
pub(super) fn refresh() {
let changed = locked(|session| {
let mut changed = reconcile(session);
if session.running.is_none() {
changed |= store_status(resting_status());
}
changed
});
announce(changed);
}
fn reconcile(session: &mut Session) -> bool {
let wanted = wanted(&session.leases);
if wanted == session.running {
return false;
}
let Some(sensor) = platform() else {
session.running = None;
return store_status(DeviceMotionStatus::Unavailable);
};
let Some(config) = wanted else {
sensor.stop();
latest().end();
session.running = None;
return store_status(resting_status());
};
if sensor.permission() != DeviceMotionPermission::Granted {
return store_status(resting_status());
}
let mut changed = false;
if session.running.is_none() {
latest().begin();
changed |= store_status(DeviceMotionStatus::Acquiring);
}
match sensor.start(config) {
Ok(()) => session.running = Some(config),
Err(error) => {
log::warn!("cranpose: the motion sensor did not start: {error:?}");
latest().end();
session.running = None;
changed |= store_status(DeviceMotionStatus::Unavailable);
}
}
changed
}