mendi 0.0.2

Rust client for the Mendi neurofeedback headband over BLE using btleplug
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Simulated Mendi headband for testing without hardware.
//!
//! Enabled with `--features simulate`. Provides:
//!
//! - [`SimulatedDevice`] — a fake headband that generates realistic fNIRS
//!   data and emits [`MendiEvent`]s on an mpsc channel, matching the same
//!   API surface as the real [`MendiClient`].
//! - [`MockDevice`] — a scripted mock where you push events manually,
//!   useful for deterministic unit tests.
//!
//! # Example: simulated device
//!
//! ```no_run
//! use mendi::simulate::{SimulatedDevice, SimConfig};
//! use mendi::types::MendiEvent;
//!
//! #[tokio::main]
//! async fn main() {
//!     let (mut rx, handle) = SimulatedDevice::start(SimConfig::default());
//!     while let Some(event) = rx.recv().await {
//!         match event {
//!             MendiEvent::Frame(f) => println!("IR left={}", f.ir_left),
//!             MendiEvent::Disconnected => break,
//!             _ => {}
//!         }
//!     }
//! }
//! ```
//!
//! # Example: mock device
//!
//! ```
//! use mendi::simulate::MockDevice;
//! use mendi::types::{MendiEvent, DeviceInfo};
//!
//! #[tokio::main]
//! async fn main() {
//!     let (mut rx, mock) = MockDevice::new(16);
//!     mock.send(MendiEvent::Connected(DeviceInfo::default()));
//!     mock.send(MendiEvent::Disconnected);
//!
//!     let ev = rx.recv().await.unwrap();
//!     assert!(matches!(ev, MendiEvent::Connected(_)));
//!     let ev = rx.recv().await.unwrap();
//!     assert_eq!(ev, MendiEvent::Disconnected);
//! }
//! ```

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use tokio::sync::mpsc;

use crate::types::{
    BatteryReading, CalibrationReading, DeviceInfo, DiagnosticsReading, FrameReading, MendiEvent,
    MENDI_FCC_ID,
};

// ═══════════════════════════════════════════════════════════════════════════════
//  SimConfig
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for [`SimulatedDevice`].
#[derive(Debug, Clone)]
pub struct SimConfig {
    /// Frame rate in Hz. Default: `25.0` (matches typical Mendi sample rate).
    pub frame_rate_hz: f64,
    /// Battery voltage in mV. Default: `3900`.
    pub battery_voltage_mv: u32,
    /// Whether USB is connected in simulation. Default: `false`.
    pub usb_connected: bool,
    /// Whether charging in simulation. Default: `false`.
    pub charging: bool,
    /// Send a battery event every N frames. Default: `100`.
    pub battery_every_n_frames: u64,
    /// Send a calibration event every N frames. Default: `200`.
    pub calibration_every_n_frames: u64,
    /// Device name. Default: `"Mendi-SIM"`.
    pub device_name: String,
    /// Firmware version string. Default: `"SIM-1.0.0"`.
    pub firmware_version: String,
    /// If `Some(n)`, disconnect automatically after `n` frames.
    /// If `None`, run forever until [`SimHandle::disconnect`] is called.
    pub disconnect_after_frames: Option<u64>,
    /// Base infrared reading (optical signal oscillates around this).
    /// Default: `50000`.
    pub base_ir: i32,
    /// Base red LED reading. Default: `40000`.
    pub base_red: i32,
    /// Base ambient reading. Default: `1000`.
    pub base_ambient: i32,
    /// Temperature in °C. Default: `36.5`.
    pub temperature: f32,
}

impl Default for SimConfig {
    fn default() -> Self {
        Self {
            frame_rate_hz: 25.0,
            battery_voltage_mv: 3900,
            usb_connected: false,
            charging: false,
            battery_every_n_frames: 100,
            calibration_every_n_frames: 200,
            device_name: "Mendi-SIM".into(),
            firmware_version: "SIM-1.0.0".into(),
            disconnect_after_frames: None,
            base_ir: 50_000,
            base_red: 40_000,
            base_ambient: 1_000,
            temperature: 36.5,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
//  SimHandle
// ═══════════════════════════════════════════════════════════════════════════════

/// Handle to a running [`SimulatedDevice`].
///
/// Allows stopping the simulation or checking its state.
pub struct SimHandle {
    running: Arc<AtomicBool>,
    task: tokio::task::JoinHandle<()>,
}

impl SimHandle {
    /// Signal the simulation to stop. The next loop iteration will send
    /// [`MendiEvent::Disconnected`] and exit.
    pub fn disconnect(&self) {
        self.running.store(false, Ordering::SeqCst);
    }

    /// Get a clone of the running flag for external use (e.g. Ctrl-C handler).
    pub fn running_flag(&self) -> Arc<AtomicBool> {
        Arc::clone(&self.running)
    }

    /// Whether the simulation task is still running.
    pub fn is_running(&self) -> bool {
        !self.task.is_finished()
    }

    /// Wait for the simulation task to complete.
    pub async fn join(self) {
        let _ = self.task.await;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
//  SimulatedDevice
// ═══════════════════════════════════════════════════════════════════════════════

/// A simulated Mendi headband that generates realistic fNIRS data.
///
/// Produces a stream of [`MendiEvent`]s matching the real device's behavior:
/// - `Connected` with device info
/// - `Diagnostics` (once)
/// - `Frame` at the configured rate with sinusoidal optical signals + noise
/// - `Battery` periodically
/// - `Calibration` periodically
/// - `Disconnected` when stopped
pub struct SimulatedDevice;

impl SimulatedDevice {
    /// Start the simulation and return an event receiver and control handle.
    ///
    /// The returned `mpsc::Receiver<MendiEvent>` behaves identically to
    /// the one returned by [`MendiClient::connect`](crate::mendi_client::MendiClient::connect).
    pub fn start(config: SimConfig) -> (mpsc::Receiver<MendiEvent>, SimHandle) {
        let (tx, rx) = mpsc::channel::<MendiEvent>(256);
        let running = Arc::new(AtomicBool::new(true));
        let running_clone = Arc::clone(&running);

        let task = tokio::spawn(async move {
            Self::run(config, tx, running_clone).await;
        });

        let handle = SimHandle { running, task };
        (rx, handle)
    }

    async fn run(config: SimConfig, tx: mpsc::Sender<MendiEvent>, running: Arc<AtomicBool>) {
        // ── Connected ────────────────────────────────────────────────────────
        let device_info = DeviceInfo {
            name: config.device_name.clone(),
            id: "SIM-00:00:00:00:00:00".into(),
            firmware_version: Some(config.firmware_version.clone()),
            hardware_version: Some("SIM-HW-1.0".into()),
            fcc_id: MENDI_FCC_ID.into(),
        };
        if tx.send(MendiEvent::Connected(device_info)).await.is_err() {
            return;
        }

        // ── Diagnostics ──────────────────────────────────────────────────────
        let diag = DiagnosticsReading {
            timestamp: now_ms(),
            adc: Some(BatteryReading {
                timestamp: now_ms(),
                voltage_mv: config.battery_voltage_mv,
                charging: config.charging,
                usb_connected: config.usb_connected,
            }),
            imu_ok: true,
            sensor_ok: true,
        };
        if tx.send(MendiEvent::Diagnostics(diag)).await.is_err() {
            return;
        }

        // ── Frame loop ───────────────────────────────────────────────────────
        let interval = Duration::from_secs_f64(1.0 / config.frame_rate_hz);
        let mut frame_count: u64 = 0;
        let mut rng = StdRng::from_os_rng();

        while running.load(Ordering::SeqCst) {
            frame_count += 1;

            // Check frame limit
            if let Some(limit) = config.disconnect_after_frames {
                if frame_count > limit {
                    break;
                }
            }

            let ts = now_ms();
            let t = frame_count as f64 / config.frame_rate_hz;

            // Sinusoidal optical signals with noise — simulates brain activity
            // Left and right channels have slightly different phases
            let sin_l = (t * 0.5 * std::f64::consts::TAU).sin(); // ~0.5 Hz oscillation
            let sin_r = (t * 0.5 * std::f64::consts::TAU + 0.3).sin();
            let sin_p = (t * 1.2 * std::f64::consts::TAU).sin(); // pulse ~1.2 Hz (heartbeat)

            let n = |r: &mut StdRng| -> i32 { r.random_range(-200..=200) };

            let frame = FrameReading {
                timestamp: ts,
                // IMU: slight gravity on Z, small noise on X/Y
                acc_x: rng.random_range(-50..=50),
                acc_y: rng.random_range(-50..=50),
                acc_z: 16384 + rng.random_range(-100..=100), // ~1g
                ang_x: rng.random_range(-10..=10),
                ang_y: rng.random_range(-10..=10),
                ang_z: rng.random_range(-10..=10),
                temperature: config.temperature,
                // Optical: base + sinusoidal modulation + noise
                ir_left: config.base_ir + (sin_l * 2000.0) as i32 + n(&mut rng),
                red_left: config.base_red + (sin_l * 1500.0) as i32 + n(&mut rng),
                amb_left: config.base_ambient + n(&mut rng) / 4,
                ir_right: config.base_ir + (sin_r * 2000.0) as i32 + n(&mut rng),
                red_right: config.base_red + (sin_r * 1500.0) as i32 + n(&mut rng),
                amb_right: config.base_ambient + n(&mut rng) / 4,
                ir_pulse: config.base_ir + (sin_p * 3000.0) as i32 + n(&mut rng),
                red_pulse: config.base_red + (sin_p * 2000.0) as i32 + n(&mut rng),
                amb_pulse: config.base_ambient + n(&mut rng) / 4,
            };

            // Use try_send for frames (same as real client)
            if tx.try_send(MendiEvent::Frame(frame)).is_err() {
                // Channel full or closed
                if tx.is_closed() {
                    return;
                }
            }

            // ── Periodic battery ─────────────────────────────────────────────
            if frame_count.is_multiple_of(config.battery_every_n_frames) {
                let battery = BatteryReading {
                    timestamp: now_ms(),
                    voltage_mv: config.battery_voltage_mv,
                    charging: config.charging,
                    usb_connected: config.usb_connected,
                };
                let _ = tx.send(MendiEvent::Battery(battery)).await;
            }

            // ── Periodic calibration ─────────────────────────────────────────
            if frame_count.is_multiple_of(config.calibration_every_n_frames) {
                let cal = CalibrationReading {
                    timestamp: now_ms(),
                    offset_left: 0.0,
                    offset_right: 0.0,
                    offset_pulse: 0.0,
                    auto_calibration: true,
                    low_power_mode: false,
                };
                let _ = tx.send(MendiEvent::Calibration(cal)).await;
            }

            tokio::time::sleep(interval).await;
        }

        // ── Disconnected ─────────────────────────────────────────────────────
        let _ = tx.send(MendiEvent::Disconnected).await;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
//  MockDevice
// ═══════════════════════════════════════════════════════════════════════════════

/// A scripted mock device for deterministic unit tests.
///
/// You push events manually with [`MockDevice::send`]; the consumer receives
/// them in order on the `mpsc::Receiver`. No background tasks, no timing,
/// no randomness — pure determinism.
///
/// # Example
///
/// ```
/// use mendi::simulate::MockDevice;
/// use mendi::types::{MendiEvent, DeviceInfo};
///
/// #[tokio::main]
/// async fn main() {
///     let (mut rx, mock) = MockDevice::new(16);
///
///     mock.send(MendiEvent::Connected(DeviceInfo {
///         name: "Test".into(),
///         id: "00:00".into(),
///         fcc_id: "RYYEYSHJN".into(),
///         ..Default::default()
///     }));
///     mock.send(MendiEvent::Disconnected);
///     // Signal no more events
///     drop(mock);
///
///     let mut events = vec![];
///     while let Some(ev) = rx.recv().await {
///         events.push(ev);
///     }
///     assert_eq!(events.len(), 2);
///     assert!(matches!(events[0], MendiEvent::Connected(_)));
///     assert_eq!(events[1], MendiEvent::Disconnected);
/// }
/// ```
pub struct MockDevice {
    tx: mpsc::Sender<MendiEvent>,
}

impl MockDevice {
    /// Create a new mock device with the given channel buffer size.
    ///
    /// Returns the consumer receiver and the mock controller.
    pub fn new(buffer: usize) -> (mpsc::Receiver<MendiEvent>, Self) {
        let (tx, rx) = mpsc::channel(buffer);
        (rx, Self { tx })
    }

    /// Send an event to the consumer. Panics if the channel is full.
    ///
    /// Use [`try_send`](MockDevice::try_send) for non-panicking behavior.
    pub fn send(&self, event: MendiEvent) {
        self.tx.try_send(event).expect("MockDevice channel full or closed");
    }

    /// Try to send an event. Returns `false` if the channel is full or closed.
    pub fn try_send(&self, event: MendiEvent) -> bool {
        self.tx.try_send(event).is_ok()
    }

    /// Send an event asynchronously (waits if the channel is full).
    pub async fn send_async(&self, event: MendiEvent) {
        let _ = self.tx.send(event).await;
    }

    /// Create a mock that immediately emits `Connected` + `Diagnostics`
    /// with the given device info, mimicking real connection startup.
    pub fn connected(info: DeviceInfo, buffer: usize) -> (mpsc::Receiver<MendiEvent>, Self) {
        let (rx, mock) = Self::new(buffer);
        mock.send(MendiEvent::Connected(info));
        mock.send(MendiEvent::Diagnostics(DiagnosticsReading {
            timestamp: 0.0,
            adc: Some(BatteryReading {
                timestamp: 0.0,
                voltage_mv: 3900,
                charging: false,
                usb_connected: false,
            }),
            imu_ok: true,
            sensor_ok: true,
        }));
        (rx, mock)
    }

    /// Create a mock pre-loaded with `Connected` + `n` frames + `Disconnected`.
    ///
    /// Frames have sequential timestamps and constant optical values.
    /// Useful for testing frame processing pipelines.
    pub fn with_frames(n: usize, buffer: usize) -> (mpsc::Receiver<MendiEvent>, Self) {
        let (rx, mock) = Self::new(buffer.max(n + 3));
        mock.send(MendiEvent::Connected(DeviceInfo {
            name: "Mock".into(),
            id: "MOCK-00".into(),
            fcc_id: MENDI_FCC_ID.into(),
            ..Default::default()
        }));
        for i in 0..n {
            mock.send(MendiEvent::Frame(FrameReading {
                timestamp: i as f64 * 40.0, // 25 Hz
                acc_x: 0,
                acc_y: 0,
                acc_z: 16384,
                ang_x: 0,
                ang_y: 0,
                ang_z: 0,
                temperature: 36.5,
                ir_left: 50_000 + (i as i32 * 10),
                red_left: 40_000 + (i as i32 * 8),
                amb_left: 1_000,
                ir_right: 50_000 + (i as i32 * 10),
                red_right: 40_000 + (i as i32 * 8),
                amb_right: 1_000,
                ir_pulse: 50_000 + (i as i32 * 5),
                red_pulse: 40_000 + (i as i32 * 4),
                amb_pulse: 1_000,
            }));
        }
        mock.send(MendiEvent::Disconnected);
        (rx, mock)
    }
}

// ── Helpers ──────────────────────────────────────────────────────────────────

fn now_ms() -> f64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("system clock before epoch")
        .as_secs_f64()
        * 1000.0
}