makcu 0.3.2

Rust library for controlling MAKCU USB HID interceptor devices
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
/// Events emitted by the stream parser.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseEvent {
    /// A button state change event (raw mask byte from `km.` prefix).
    ButtonEvent(u8),
    /// A complete command response (everything before the `>>> ` prompt).
    Response(Vec<u8>),
}

/// State machine that parses the interleaved device stream.
///
/// Handles:
/// - `km.` prefix detection for button events (mask byte follows)
/// - `>>> ` prompt detection for command response boundaries
/// - Interleaved button events and command responses
pub struct StreamParser {
    /// How many bytes of "km." we've matched (0-3).
    km_matched: usize,
    /// Accumulated response bytes (between prompts).
    response_buf: Vec<u8>,
    /// How many bytes of ">>> " we've matched (0-4).
    prompt_matched: usize,
}

impl StreamParser {
    pub fn new() -> Self {
        Self {
            km_matched: 0,
            response_buf: Vec::with_capacity(256),
            prompt_matched: 0,
        }
    }

    /// Feed a single byte into the parser. Returns an event if one is complete.
    pub fn feed(&mut self, byte: u8) -> Option<ParseEvent> {
        const KM: &[u8] = b"km.";

        // State: we've matched the full "km." prefix, this byte is the mask.
        if self.km_matched == 3 {
            self.km_matched = 0;
            // Distinguish button mask (< 0x20) from command echo (>= 0x20).
            // Command names after "km." always start with a letter (>= 0x61),
            // so any byte < 0x20 is a button event mask.
            if byte < 0x20 {
                return Some(ParseEvent::ButtonEvent(byte));
            }
            // False positive — flush "km." + this byte to response buffer.
            self.push_response_bytes(KM);
            return self.push_response_byte(byte);
        }

        // State: partially matching "km." prefix.
        if self.km_matched > 0 {
            if byte == KM[self.km_matched] {
                self.km_matched += 1;
                return None;
            }
            // Mismatch — flush partial "km" to response buffer.
            let partial = &KM[..self.km_matched];
            self.km_matched = 0;
            self.push_response_bytes(partial);
            // Check if current byte starts a new "km." match.
            if byte == KM[0] {
                self.km_matched = 1;
                return None;
            }
            return self.push_response_byte(byte);
        }

        // State: normal — check if this byte starts "km." prefix.
        if byte == KM[0] {
            self.km_matched = 1;
            return None;
        }

        // Normal byte — add to response buffer and check for prompt.
        self.push_response_byte(byte)
    }

    /// Push a single byte to the response buffer and check for prompt completion.
    fn push_response_byte(&mut self, byte: u8) -> Option<ParseEvent> {
        const PROMPT_BYTES: &[u8] = b">>> ";

        self.response_buf.push(byte);

        if byte == PROMPT_BYTES[self.prompt_matched] {
            self.prompt_matched += 1;
            if self.prompt_matched == PROMPT_BYTES.len() {
                // Complete prompt found — emit response.
                let len = self.response_buf.len() - PROMPT_BYTES.len();
                let response = self.response_buf[..len].to_vec();
                self.response_buf.clear();
                self.prompt_matched = 0;
                return Some(ParseEvent::Response(response));
            }
        } else if byte == PROMPT_BYTES[0] {
            self.prompt_matched = 1;
        } else {
            self.prompt_matched = 0;
        }

        None
    }

    /// Push multiple bytes to response buffer, checking prompt after each.
    fn push_response_bytes(&mut self, bytes: &[u8]) {
        for &b in bytes {
            // We ignore any events from flushing partial km. matches to response buf
            // because "km." chars can't complete a ">>> " prompt.
            self.response_buf.push(b);
            // No need to check prompt — 'k', 'm', '.' never match '>', '>', '>', ' '.
        }
    }

    /// Reset parser state (e.g. on reconnection).
    #[allow(dead_code)]
    pub fn reset(&mut self) {
        self.km_matched = 0;
        self.response_buf.clear();
        self.prompt_matched = 0;
    }
}

/// Parse a raw response buffer into a classified result.
///
/// Returns `(echo_stripped_value, is_query)` where `is_query` indicates
/// whether the response contained a return value.
pub fn classify_response(raw: &[u8]) -> ResponseKind {
    let body = trim_bytes(raw);
    if body.is_empty() {
        return ResponseKind::Executed;
    }
    let text = String::from_utf8_lossy(body);
    // If there's a newline: first line is the echo, rest is the return value.
    if let Some(nl) = body.iter().position(|&b| b == b'\n') {
        let value = String::from_utf8_lossy(&body[nl + 1..]).trim().to_string();
        return ResponseKind::Value(value);
    }
    // Single line — could be echo-only or a value without echo (km.version special case).
    // We return it as a value and let the caller decide.
    ResponseKind::ValueOrEcho(text.trim().to_string())
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResponseKind {
    /// No body — command executed, prompt returned immediately.
    Executed,
    /// Multi-line: echo + value. The value string is extracted.
    Value(String),
    /// Single line — might be just an echo or a value without echo.
    /// Caller must compare with sent command to disambiguate.
    ValueOrEcho(String),
}

/// Try to parse a response buffer as a catch event.
///
/// Catch events arrive as unsolicited responses like `km.catch_ml(1)\r\n`
/// where the value 1 = press and 2 = release. Each event is terminated by
/// its own `>>> ` prompt, so the response buffer always contains a single
/// catch line.
pub fn parse_catch_event(raw: &[u8]) -> Option<crate::types::CatchEvent> {
    use crate::types::Button;

    let text = std::str::from_utf8(trim_bytes(raw)).ok()?;
    let rest = text.strip_prefix("km.catch_m")?;

    // Parse button suffix and value.
    let (button, rest) = if let Some(r) = rest.strip_prefix("s1") {
        (Button::Side1, r)
    } else if let Some(r) = rest.strip_prefix("s2") {
        (Button::Side2, r)
    } else if let Some(r) = rest.strip_prefix('l') {
        (Button::Left, r)
    } else if let Some(r) = rest.strip_prefix('r') {
        (Button::Right, r)
    } else if let Some(r) = rest.strip_prefix('m') {
        (Button::Middle, r)
    } else {
        return None;
    };

    match rest {
        "(1)" => Some(crate::types::CatchEvent {
            button,
            pressed: true,
        }),
        "(2)" => Some(crate::types::CatchEvent {
            button,
            pressed: false,
        }),
        _ => None,
    }
}

fn trim_bytes(b: &[u8]) -> &[u8] {
    let is_ws = |&x: &u8| x == b'\r' || x == b'\n' || x == b' ';
    let start = b.iter().position(|x| !is_ws(x)).unwrap_or(b.len());
    let end = b
        .iter()
        .rposition(|x| !is_ws(x))
        .map(|i| i + 1)
        .unwrap_or(0);
    if start >= end { &[] } else { &b[start..end] }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn button_event_basic() {
        let mut parser = StreamParser::new();
        // Feed "km." + mask byte 0x05 (left + middle)
        assert_eq!(parser.feed(b'k'), None);
        assert_eq!(parser.feed(b'm'), None);
        assert_eq!(parser.feed(b'.'), None);
        assert_eq!(parser.feed(0x05), Some(ParseEvent::ButtonEvent(0x05)));
    }

    #[test]
    fn button_event_mask_0x0a() {
        let mut parser = StreamParser::new();
        assert_eq!(parser.feed(b'k'), None);
        assert_eq!(parser.feed(b'm'), None);
        assert_eq!(parser.feed(b'.'), None);
        // 0x0A = right + side1
        assert_eq!(parser.feed(0x0A), Some(ParseEvent::ButtonEvent(0x0A)));
    }

    #[test]
    fn button_event_mask_0x0d() {
        let mut parser = StreamParser::new();
        assert_eq!(parser.feed(b'k'), None);
        assert_eq!(parser.feed(b'm'), None);
        assert_eq!(parser.feed(b'.'), None);
        // 0x0D = left + middle + side1
        assert_eq!(parser.feed(0x0D), Some(ParseEvent::ButtonEvent(0x0D)));
    }

    #[test]
    fn button_event_mask_zero() {
        let mut parser = StreamParser::new();
        for &b in b"km." {
            assert_eq!(parser.feed(b), None);
        }
        assert_eq!(parser.feed(0x00), Some(ParseEvent::ButtonEvent(0x00)));
    }

    #[test]
    fn command_echo_not_confused_with_button() {
        let mut parser = StreamParser::new();
        // Feed "km.left(1)\r\n>>> "
        let input = b"km.left(1)\r\n>>> ";
        let mut events = Vec::new();
        for &b in input.iter() {
            if let Some(ev) = parser.feed(b) {
                events.push(ev);
            }
        }
        // Should get one Response, not a button event
        assert_eq!(events.len(), 1);
        match &events[0] {
            ParseEvent::Response(data) => {
                let text = String::from_utf8_lossy(data);
                assert!(text.contains("km.left(1)"), "got: {}", text);
            }
            other => panic!("expected Response, got {:?}", other),
        }
    }

    #[test]
    fn interleaved_button_and_response() {
        let mut parser = StreamParser::new();
        // Command echo, then button event, then prompt
        // "km.left(1)\r\n" + "km." + 0x05 + ">>> "
        let mut input: Vec<u8> = b"km.left(1)\r\n".to_vec();
        input.extend_from_slice(b"km.");
        input.push(0x05);
        input.extend_from_slice(b">>> ");

        let mut events = Vec::new();
        for &b in &input {
            if let Some(ev) = parser.feed(b) {
                events.push(ev);
            }
        }
        assert_eq!(events.len(), 2);
        assert_eq!(events[0], ParseEvent::ButtonEvent(0x05));
        assert!(matches!(&events[1], ParseEvent::Response(_)));
    }

    #[test]
    fn version_response_no_echo() {
        let mut parser = StreamParser::new();
        // km.version() is special: response is just "km.MAKCU\r\n>>> "
        // but "km." starts km prefix matching. 'M' >= 0x20 so it's flushed.
        let input = b"km.MAKCU\r\n>>> ";
        let mut events = Vec::new();
        for &b in input.iter() {
            if let Some(ev) = parser.feed(b) {
                events.push(ev);
            }
        }
        assert_eq!(events.len(), 1);
        match &events[0] {
            ParseEvent::Response(data) => {
                let text = String::from_utf8_lossy(data);
                assert!(text.contains("km.MAKCU"), "got: {}", text);
            }
            other => panic!("expected Response, got {:?}", other),
        }
    }

    #[test]
    fn classify_executed() {
        assert_eq!(classify_response(b""), ResponseKind::Executed);
        assert_eq!(classify_response(b"\r\n"), ResponseKind::Executed);
    }

    #[test]
    fn classify_value_multiline() {
        let resp = b"km.left()\r\n1";
        assert_eq!(
            classify_response(resp),
            ResponseKind::Value("1".to_string())
        );
    }

    #[test]
    fn catch_event_press() {
        let event = parse_catch_event(b"km.catch_ml(1)\r\n").unwrap();
        assert_eq!(event.button, crate::types::Button::Left);
        assert!(event.pressed);
    }

    #[test]
    fn catch_event_release() {
        let event = parse_catch_event(b"km.catch_ml(2)\r\n").unwrap();
        assert_eq!(event.button, crate::types::Button::Left);
        assert!(!event.pressed);
    }

    #[test]
    fn catch_event_right() {
        let event = parse_catch_event(b"km.catch_mr(1)").unwrap();
        assert_eq!(event.button, crate::types::Button::Right);
        assert!(event.pressed);
    }

    #[test]
    fn catch_event_middle() {
        let event = parse_catch_event(b"km.catch_mm(2)").unwrap();
        assert_eq!(event.button, crate::types::Button::Middle);
        assert!(!event.pressed);
    }

    #[test]
    fn catch_event_side1() {
        let event = parse_catch_event(b"km.catch_ms1(1)").unwrap();
        assert_eq!(event.button, crate::types::Button::Side1);
    }

    #[test]
    fn catch_event_side2() {
        let event = parse_catch_event(b"km.catch_ms2(2)").unwrap();
        assert_eq!(event.button, crate::types::Button::Side2);
    }

    #[test]
    fn catch_event_not_catch() {
        // Normal command response should not parse as catch
        assert!(parse_catch_event(b"km.left(1)\r\n").is_none());
        assert!(parse_catch_event(b"km.lock_ml(1)\r\n").is_none());
        assert!(parse_catch_event(b"").is_none());
    }

    #[test]
    fn catch_event_enable_response_not_catch() {
        // The enable command echo "km.catch_ml(0)" should NOT be a catch event
        assert!(parse_catch_event(b"km.catch_ml(0)\r\n").is_none());
    }

    #[test]
    fn catch_event_through_parser() {
        // Full catch event as it arrives on the wire: "km.catch_ml(1)\r\n>>> "
        let mut parser = StreamParser::new();
        let input = b"km.catch_ml(1)\r\n>>> ";
        let mut events = Vec::new();
        for &b in input.iter() {
            if let Some(ev) = parser.feed(b) {
                events.push(ev);
            }
        }
        // Parser sees "km." then 'c' >= 0x20, flushes to response buffer
        assert_eq!(events.len(), 1);
        match &events[0] {
            ParseEvent::Response(data) => {
                let catch = parse_catch_event(data).unwrap();
                assert_eq!(catch.button, crate::types::Button::Left);
                assert!(catch.pressed);
            }
            other => panic!("expected Response, got {:?}", other),
        }
    }

    #[test]
    fn classify_single_line() {
        let resp = b"km.MAKCU";
        assert_eq!(
            classify_response(resp),
            ResponseKind::ValueOrEcho("km.MAKCU".to_string())
        );
    }
}