Skip to main content

wayle_audio/core/device/input/
monitoring.rs

1use std::sync::Arc;
2
3use tracing::debug;
4use wayle_traits::ModelMonitoring;
5
6use crate::{
7    core::device::input::InputDevice,
8    error::{Error, MissingMonitoringComponent},
9    events::AudioEvent,
10    types::device::{Device, DeviceState},
11};
12
13impl ModelMonitoring for InputDevice {
14    type Error = Error;
15
16    async fn start_monitoring(self: Arc<Self>) -> Result<(), Self::Error> {
17        let Some(ref cancellation_token) = self.cancellation_token else {
18            return Err(Error::MonitoringNotInitialized(
19                MissingMonitoringComponent::CancellationToken,
20            ));
21        };
22
23        let Some(ref event_tx) = self.event_tx else {
24            return Err(Error::MonitoringNotInitialized(
25                MissingMonitoringComponent::EventSender,
26            ));
27        };
28
29        let weak_device = Arc::downgrade(&self);
30        let device_key = self.key;
31        let cancellation_token = cancellation_token.clone();
32        let mut event_rx = event_tx.subscribe();
33
34        tokio::spawn(async move {
35            loop {
36                tokio::select! {
37                    _ = cancellation_token.cancelled() => {
38                        debug!("InputDevice monitor cancelled for {:?}", device_key);
39                        return;
40                    }
41                    Ok(event) = event_rx.recv() => {
42                        let Some(device) = weak_device.upgrade() else {
43                            return;
44                        };
45
46                        match event {
47                            AudioEvent::DeviceChanged(Device::Source(source)) if source.key() == device_key => {
48                                device.update_from_source(&source);
49                            }
50                            AudioEvent::DeviceRemoved(key) if key == device_key => {
51                                device.state.set(DeviceState::Offline);
52                                break;
53                            }
54                            _ => {}
55                        }
56                    }
57                }
58            }
59        });
60
61        Ok(())
62    }
63}