Skip to main content

scdsu_core/
reader.rs

1//! Provides a background reader for reading [`DSUFrame`](crate::dsu::DSUFrame) data from devices.
2
3use std::sync::{Arc, atomic, mpsc};
4use std::thread;
5use std::time::{Duration, Instant};
6
7use crate::READ_ATOMIC_BOOL_ORDERING;
8use crate::devices::Device;
9use crate::dsu::DSUFrame;
10use crate::errors::DeviceError;
11
12/// Number of identical IMU frames before we consider the IMU frozen.
13/// At 100 Hz this is 1 second
14const FROZEN_DETECT_THRESHOLD: usize = 100;
15/// Retry interval for re-initializing the device when the IMU is frozen
16const REINIT_RETRY_INTERVAL: Duration = Duration::from_secs(1);
17/// Number of consecutive failed reads before assuming disconnect.
18/// At 100Hz this is ~1 second of no data.
19const DISCONNECT_THRESHOLD: usize = 100;
20
21/// Spawn a thread that reads from `device` and sends parsed frames over the returned channel.
22///
23/// The reader thread will exit when `running` is set to false.
24/// Returns a [`JoinHandle`](std::thread::JoinHandle) and a mpsc Receiver for receiving frame data.
25pub fn spawn_reader(
26    running: Arc<atomic::AtomicBool>,
27    device: impl Device + std::marker::Send + 'static,
28) -> (std::thread::JoinHandle<()>, mpsc::Receiver<DSUFrame>) {
29    let (tx, rx) = mpsc::channel::<DSUFrame>();
30
31    let handle = thread::spawn(move || {
32        let mut frame_state = FrameState::new();
33
34        log::debug!("Reader thread started");
35
36        while running.load(READ_ATOMIC_BOOL_ORDERING) {
37            if !read_frame(&device, &mut frame_state, &tx) {
38                break;
39            }
40        }
41
42        log::debug!(
43            "Reader thread finished after {} frames",
44            frame_state.total_frames
45        );
46    });
47
48    (handle, rx)
49}
50
51struct FrameState {
52    pub frozen_count: usize,
53    pub total_frames: usize,
54    pub prev_frame: Option<DSUFrame>,
55    pub fail_count: usize,
56    pub last_init_attempt: Option<Instant>,
57}
58
59impl FrameState {
60    pub fn new() -> Self {
61        Self {
62            frozen_count: 0,
63            total_frames: 0,
64            prev_frame: None,
65            fail_count: 0,
66            last_init_attempt: None,
67        }
68    }
69}
70
71/// Read a frame, returning true if another should be read.
72fn read_frame<D>(device: &D, frame_state: &mut FrameState, tx: &mpsc::Sender<DSUFrame>) -> bool
73where
74    D: Device + std::marker::Send + 'static,
75{
76    match device.read_frame() {
77        Ok(mut frame) => {
78            frame_state.fail_count = 0;
79            frame_state.total_frames += 1;
80
81            // Check for frozen IMU data
82            // Use the raw data incase values are frozen due to the gyro intentionally
83            // being disabled.
84            let is_imu_frozen = frame_state
85                .prev_frame
86                .map(|prev| {
87                    frame.raw_accel_x == prev.raw_accel_x
88                        && frame.raw_accel_y == prev.raw_accel_y
89                        && frame.raw_accel_z == prev.raw_accel_z
90                        && frame.raw_gyro_x == prev.raw_gyro_x
91                        && frame.raw_gyro_y == prev.raw_gyro_y
92                        && frame.raw_gyro_z == prev.raw_gyro_z
93                })
94                .unwrap_or(false);
95
96            if is_imu_frozen {
97                frame_state.frozen_count += 1;
98
99                if frame_state.frozen_count == FROZEN_DETECT_THRESHOLD {
100                    log::warn!(
101                        "IMU data frozen ({} identical frames). Steam likely disabled the IMU.",
102                        frame_state.frozen_count
103                    );
104                }
105
106                // Periodically attempt to re-enable the IMU
107                if frame_state.frozen_count >= FROZEN_DETECT_THRESHOLD {
108                    let should_try = frame_state
109                        .last_init_attempt
110                        .map(|t| t.elapsed() >= REINIT_RETRY_INTERVAL)
111                        .unwrap_or(true);
112                    if should_try {
113                        frame_state.last_init_attempt = Some(Instant::now());
114                        if let Err(e) = device.initialize() {
115                            log::warn!("Failed to reinitialize device while IMU frozen: {e}");
116                        } else {
117                            log::info!("Reinitialized device while IMU was frozen.");
118                        }
119                    }
120                }
121
122                // Zero out motion data so clients don't drift on stale values
123                frame.accel_x = 0.0;
124                frame.accel_y = 0.0;
125                frame.accel_z = 0.0;
126                frame.gyro_x = 0.0;
127                frame.gyro_y = 0.0;
128                frame.gyro_z = 0.0;
129            } else {
130                frame_state.frozen_count = 0;
131                frame_state.last_init_attempt = None;
132            }
133
134            frame_state.prev_frame = Some(frame);
135
136            if tx.send(frame).is_err() {
137                log::debug!("Receiver has hung up, reader thread exiting");
138                return false;
139            }
140        }
141        Err(DeviceError::ShortRead(n, expected)) => {
142            log::trace!("Short read: {} bytes (expected {})", n, expected);
143            frame_state.fail_count += 1;
144        }
145        Err(DeviceError::InvalidReport(id)) => {
146            log::trace!("Ignoring invalid report (first byte: 0x{:02x})", id);
147            frame_state.fail_count = 0;
148        }
149        Err(e) => {
150            log::trace!("HID read error: {}", e);
151            frame_state.fail_count += 1;
152        }
153    }
154
155    if frame_state.fail_count >= DISCONNECT_THRESHOLD {
156        log::warn!(
157            "Controller appears disconnected ({} consecutive read failures). Exiting reader.",
158            frame_state.fail_count,
159        );
160        return false;
161    }
162
163    true
164}