1use crate::{CameraError, CameraResult, CameraSystem, DeviceInfo};
3use std::{sync::Arc, time::Duration};
4use tokio::sync::watch;
5#[derive(Clone, Debug)]
6pub struct DeviceSnapshot {
8 pub generation: u64,
10 pub devices: Vec<DeviceInfo>,
12 pub error: Option<Arc<CameraError>>,
14}
15pub struct DeviceWatcher {
17 state: watch::Receiver<DeviceSnapshot>,
18 cancel: watch::Sender<bool>,
19 task: Option<tokio::task::JoinHandle<()>>,
20}
21impl CameraSystem {
22 pub async fn watch_devices(&self, interval: Duration) -> CameraResult<DeviceWatcher> {
24 if interval.is_zero() {
25 return Err(CameraError::invalid_config(
26 "Device scan interval must be positive".into(),
27 ));
28 }
29 let devices = self.devices().await?;
30 let system = self.clone();
31 let (tx, rx) = watch::channel(DeviceSnapshot {
32 generation: 0,
33 devices,
34 error: None,
35 });
36 let (cancel, mut cancelled) = watch::channel(false);
37 let task = tokio::spawn(async move {
38 loop {
39 tokio::select! {biased;_ = cancelled.changed()=>break,_=tokio::time::sleep(interval)=>{}}
40 let result = tokio::select! {biased;_ = cancelled.changed()=>break,result=system.devices()=>result};
41 if *cancelled.borrow() {
42 break;
43 }
44 let previous = tx.borrow().clone();
45 let next = match result {
46 Ok(devices) => DeviceSnapshot {
47 generation: previous.generation + 1,
48 devices,
49 error: None,
50 },
51 Err(e) => DeviceSnapshot {
52 generation: previous.generation + 1,
53 devices: previous.devices.clone(),
54 error: Some(Arc::new(e)),
55 },
56 };
57 let same = next.error == previous.error
58 && next.devices.len() == previous.devices.len()
59 && next.devices.iter().all(|d| {
60 previous
61 .devices
62 .iter()
63 .any(|p| p.id == d.id && p.name == d.name && p.index == d.index)
64 });
65 if !same {
66 tx.send_replace(next);
67 }
68 }
69 });
70 Ok(DeviceWatcher {
71 state: rx,
72 cancel,
73 task: Some(task),
74 })
75 }
76}
77impl DeviceWatcher {
78 pub fn snapshot(&self) -> DeviceSnapshot {
80 self.state.borrow().clone()
81 }
82 pub async fn changed(&mut self) -> CameraResult<DeviceSnapshot> {
84 self.state
85 .changed()
86 .await
87 .map_err(|_| CameraError::stream_stopped())?;
88 Ok(self.state.borrow_and_update().clone())
89 }
90 pub async fn stop(&mut self) -> CameraResult<()> {
92 self.cancel.send_replace(true);
93 if let Some(task) = self.task.take() {
94 task.await
95 .map_err(|e| CameraError::worker_failure(e.to_string()).with_source(e))?;
96 }
97 Ok(())
98 }
99}
100impl Drop for DeviceWatcher {
101 fn drop(&mut self) {
102 self.cancel.send_replace(true);
103 }
104}