-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Expand file tree
/
Copy pathgesture.rs
More file actions
335 lines (293 loc) · 10.9 KB
/
gesture.rs
File metadata and controls
335 lines (293 loc) · 10.9 KB
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
//! DTW (Dynamic Time Warping) gesture recognition — no_std port.
//!
//! Ported from `ruvsense/gesture.rs` for WASM execution on ESP32-S3.
//! Recognizes predefined gesture templates from CSI phase sequences
//! using constrained DTW with Sakoe-Chiba band.
use libm::fabsf;
/// Maximum gesture template length (samples).
const MAX_TEMPLATE_LEN: usize = 40;
/// Maximum observation window (samples).
const MAX_WINDOW_LEN: usize = 60;
/// Number of predefined gesture templates.
const NUM_TEMPLATES: usize = 4;
/// DTW distance threshold for a match.
const DTW_THRESHOLD: f32 = 2.5;
/// Sakoe-Chiba band width (constrains warping path).
const BAND_WIDTH: usize = 5;
/// Gesture template: a named sequence of phase-delta values.
struct GestureTemplate {
/// Template values (normalized phase deltas).
values: [f32; MAX_TEMPLATE_LEN],
/// Actual length of the template.
len: usize,
/// Gesture ID (emitted as event value).
id: u8,
}
/// DTW gesture detector state.
pub struct GestureDetector {
/// Sliding window of phase deltas.
window: [f32; MAX_WINDOW_LEN],
window_len: usize,
window_idx: usize,
/// Previous primary phase (for delta computation).
prev_phase: f32,
initialized: bool,
/// Cooldown counter (frames) to avoid duplicate detections.
cooldown: u16,
/// Predefined gesture templates.
templates: [GestureTemplate; NUM_TEMPLATES],
}
impl GestureDetector {
pub const fn new() -> Self {
Self {
window: [0.0; MAX_WINDOW_LEN],
window_len: 0,
window_idx: 0,
prev_phase: 0.0,
initialized: false,
cooldown: 0,
templates: [
// Template 1: Wave (oscillating phase)
GestureTemplate {
values: {
let mut v = [0.0f32; MAX_TEMPLATE_LEN];
// Manually define a wave pattern
v[0] = 0.5; v[1] = 0.8; v[2] = 0.3; v[3] = -0.3;
v[4] = -0.8; v[5] = -0.5; v[6] = 0.3; v[7] = 0.8;
v[8] = 0.5; v[9] = -0.3; v[10] = -0.8; v[11] = -0.5;
v
},
len: 12,
id: 1,
},
// Template 2: Push (steady positive phase shift)
GestureTemplate {
values: {
let mut v = [0.0f32; MAX_TEMPLATE_LEN];
v[0] = 0.1; v[1] = 0.3; v[2] = 0.5; v[3] = 0.7;
v[4] = 0.6; v[5] = 0.4; v[6] = 0.2; v[7] = 0.0;
v
},
len: 8,
id: 2,
},
// Template 3: Pull (steady negative phase shift)
GestureTemplate {
values: {
let mut v = [0.0f32; MAX_TEMPLATE_LEN];
v[0] = -0.1; v[1] = -0.3; v[2] = -0.5; v[3] = -0.7;
v[4] = -0.6; v[5] = -0.4; v[6] = -0.2; v[7] = 0.0;
v
},
len: 8,
id: 3,
},
// Template 4: Swipe (sharp directional change)
GestureTemplate {
values: {
let mut v = [0.0f32; MAX_TEMPLATE_LEN];
v[0] = 0.0; v[1] = 0.2; v[2] = 0.6; v[3] = 1.0;
v[4] = 0.8; v[5] = 0.2; v[6] = -0.2; v[7] = -0.4;
v[8] = -0.3; v[9] = -0.1;
v
},
len: 10,
id: 4,
},
],
}
}
/// Process one frame's phase data, returning a gesture ID if detected.
pub fn process_frame(&mut self, phases: &[f32]) -> Option<u8> {
if phases.is_empty() {
return None;
}
// Decrement cooldown.
if self.cooldown > 0 {
self.cooldown -= 1;
// Still need to update state even during cooldown.
}
// Use primary (first) subcarrier phase for gesture detection.
let primary_phase = phases[0];
if !self.initialized {
self.prev_phase = primary_phase;
self.initialized = true;
return None;
}
// Compute phase delta.
let delta = primary_phase - self.prev_phase;
self.prev_phase = primary_phase;
// Add to sliding window (ring buffer).
self.window[self.window_idx] = delta;
self.window_idx = (self.window_idx + 1) % MAX_WINDOW_LEN;
if self.window_len < MAX_WINDOW_LEN {
self.window_len += 1;
}
// Need minimum window before attempting matching.
if self.window_len < 8 || self.cooldown > 0 {
return None;
}
// Build contiguous observation from ring buffer.
let mut obs = [0.0f32; MAX_WINDOW_LEN];
for i in 0..self.window_len {
let ri = (self.window_idx + MAX_WINDOW_LEN - self.window_len + i) % MAX_WINDOW_LEN;
obs[i] = self.window[ri];
}
// Match against each template.
let mut best_id: Option<u8> = None;
let mut best_dist = DTW_THRESHOLD;
for tmpl in &self.templates {
if tmpl.len == 0 || self.window_len < tmpl.len {
continue;
}
// Use only the tail of the observation (matching template length + margin).
let obs_start = if self.window_len > tmpl.len + 10 {
self.window_len - tmpl.len - 10
} else {
0
};
let obs_slice = &obs[obs_start..self.window_len];
let dist = dtw_distance(obs_slice, &tmpl.values[..tmpl.len]);
if dist < best_dist {
best_dist = dist;
best_id = Some(tmpl.id);
}
}
if best_id.is_some() {
self.cooldown = 40; // ~2 seconds at 20 Hz.
}
best_id
}
}
/// Compute constrained DTW distance between two sequences.
/// Uses Sakoe-Chiba band to limit warping and reduce computation.
fn dtw_distance(a: &[f32], b: &[f32]) -> f32 {
let n = a.len();
let m = b.len();
if n == 0 || m == 0 {
return f32::MAX;
}
// Use a flat array on stack (max 60 × 40 = 2400 entries).
// For WASM, this uses linear memory which is fine.
const MAX_N: usize = MAX_WINDOW_LEN;
const MAX_M: usize = MAX_TEMPLATE_LEN;
let mut cost = [[f32::MAX; MAX_M]; MAX_N];
cost[0][0] = fabsf(a[0] - b[0]);
for i in 0..n {
for j in 0..m {
// Sakoe-Chiba band constraint.
let diff = if i > j { i - j } else { j - i };
if diff > BAND_WIDTH {
continue;
}
let c = fabsf(a[i] - b[j]);
if i == 0 && j == 0 {
cost[i][j] = c;
} else {
let mut min_prev = f32::MAX;
if i > 0 && cost[i - 1][j] < min_prev {
min_prev = cost[i - 1][j];
}
if j > 0 && cost[i][j - 1] < min_prev {
min_prev = cost[i][j - 1];
}
if i > 0 && j > 0 && cost[i - 1][j - 1] < min_prev {
min_prev = cost[i - 1][j - 1];
}
cost[i][j] = c + min_prev;
}
}
}
// Normalize by path length.
let path_len = (n + m) as f32;
cost[n - 1][m - 1] / path_len
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gesture_detector_init() {
let det = GestureDetector::new();
assert!(!det.initialized);
assert_eq!(det.window_len, 0);
assert_eq!(det.cooldown, 0);
}
#[test]
fn test_empty_phases_returns_none() {
let mut det = GestureDetector::new();
assert!(det.process_frame(&[]).is_none());
}
#[test]
fn test_first_frame_initializes() {
let mut det = GestureDetector::new();
assert!(det.process_frame(&[0.5]).is_none());
assert!(det.initialized);
assert_eq!(det.window_len, 0); // first frame only initializes prev_phase
}
#[test]
fn test_constant_phase_no_gesture_after_cooldown() {
let mut det = GestureDetector::new();
// Feed constant phase (no gesture) for many frames.
// With constant phase, delta=0 every frame. This may match some
// template at low distance. After any initial match, cooldown
// prevents further detections.
let mut detection_count = 0u32;
for _ in 0..200 {
if det.process_frame(&[1.0]).is_some() {
detection_count += 1;
}
}
// Even if a false match occurs, cooldown limits total detections.
assert!(detection_count <= 5, "constant phase should not trigger many gestures, got {}", detection_count);
}
#[test]
fn test_dtw_identical_sequences() {
let a = [0.1, 0.2, 0.3, 0.4, 0.5];
let b = [0.1, 0.2, 0.3, 0.4, 0.5];
let dist = dtw_distance(&a, &b);
assert!(dist < 0.01, "identical sequences should have near-zero DTW distance, got {}", dist);
}
#[test]
fn test_dtw_different_sequences() {
let a = [0.0, 0.0, 0.0, 0.0, 0.0];
let b = [1.0, 1.0, 1.0, 1.0, 1.0];
let dist = dtw_distance(&a, &b);
// DTW normalized by path length (5+5=10). Cost = 5*1.0 = 5.0, normalized = 0.5.
assert!(dist >= 0.5, "very different sequences should have large DTW distance, got {}", dist);
}
#[test]
fn test_dtw_empty_input() {
assert_eq!(dtw_distance(&[], &[1.0, 2.0]), f32::MAX);
assert_eq!(dtw_distance(&[1.0, 2.0], &[]), f32::MAX);
assert_eq!(dtw_distance(&[], &[]), f32::MAX);
}
#[test]
fn test_cooldown_prevents_duplicate_detection() {
let mut det = GestureDetector::new();
// Initialize
det.process_frame(&[0.0]);
// Feed wave-like pattern to try to trigger gesture
let mut phase = 0.0f32;
let mut detected_count = 0;
for i in 0..200 {
// Oscillating phase to simulate wave gesture
phase += if i % 6 < 3 { 0.8 } else { -0.8 };
if det.process_frame(&[phase]).is_some() {
detected_count += 1;
}
}
// If any gestures detected, cooldown should prevent immediate re-detection.
// With 200 frames and 40-frame cooldown, at most ~4-5 detections.
assert!(detected_count <= 5, "cooldown should limit detections, got {}", detected_count);
}
#[test]
fn test_window_ring_buffer_wraps() {
let mut det = GestureDetector::new();
det.process_frame(&[0.0]); // init
// Fill more than MAX_WINDOW_LEN frames to verify wrapping works.
for i in 0..100 {
det.process_frame(&[i as f32 * 0.01]);
}
assert_eq!(det.window_len, MAX_WINDOW_LEN);
}
}