aboutsummaryrefslogtreecommitdiff
path: root/src/bin/probe.rs
blob: e77e6cd5d758b4aed17be7fda9a125116e6a0a94 (plain) (blame)
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
//! mmx150-probe — reverse-engineering tool for the MMX 150 dongle protocol.
//!
//! Phase 1 workflow: send candidate output reports to the dongle and observe
//! what input reports come back, correlating fields with headset on/off,
//! battery charge level and button presses.

use std::process::ExitCode;
use std::time::Duration;

use mmx150::hid::{find_devices_by_vendor, Hidraw, BEYERDYNAMIC_VID};

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match args.first().map(String::as_str) {
        Some("list") => cmd_list(&args[1..]),
        Some("scan") => cmd_scan(),
        Some("send") => cmd_send(&args[1..]),
        Some("sweep") => cmd_sweep(&args[1..]),
        Some("status") => cmd_status_dump(),
        Some("selenum") => cmd_sel_enum(&args[1..]),
        _ => {
            eprintln!("usage: mmx150-probe <list|scan|send|sweep|status|selenum>");
            ExitCode::FAILURE
        }
    }
}

fn cmd_list(_rest: &[String]) -> ExitCode {
    match find_devices_by_vendor(BEYERDYNAMIC_VID) {
        Ok(devices) => {
            for d in &devices {
                println!(
                    "{:04x}:{:04x} {} {}",
                    d.vid,
                    d.pid,
                    d.devnode.display(),
                    d.name
                );
            }
            if devices.is_empty() {
                eprintln!("no beyerdynamic hidraw devices found");
                return ExitCode::FAILURE;
            }
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::FAILURE
        }
    }
}

fn cmd_scan() -> ExitCode {
    let Some(dev) = mmx150::hid::find_mmx150().unwrap_or(None) else {
        eprintln!("MMX 150 dongle not found");
        return ExitCode::FAILURE;
    };
    println!("device: {} at {}", dev.name, dev.devnode.display());
    let hid = match Hidraw::open(&dev.devnode) {
        Ok(h) => h,
        Err(e) => {
            eprintln!("open failed: {e}");
            return ExitCode::FAILURE;
        }
    };

    // Known report sizes from the report descriptor:
    // 62-byte reports: 0x24/0x27, 0x80/0x81, 0x34/0x37
    // 60-byte reports: 0x2a/0x2b, 0x3a/0x3b
    // 16-byte reports: 0x2c/0x2d, 0x3c/0x3d
    for (report_id, len) in [
        (0x24, 63usize),
        (0x34, 63),
        (0x80, 63),
        (0x3a, 61),
        (0x3b, 61),
        (0x2a, 61),
        (0x2b, 61),
        (0x3d, 17),
        (0x2d, 17),
    ] {
        match hid.get_feature(report_id, len) {
            Ok(buf) => println!("FEATURE 0x{report_id:02x}: {}", hex(&buf)),
            Err(e) => println!("FEATURE 0x{report_id:02x}: {e}"),
        }
    }
    for (report_id, len) in [
        (0x27, 63usize),
        (0x37, 63),
        (0x81, 63),
        (0x3c, 17),
        (0x3d, 17),
        (0x2c, 17),
        (0x2d, 17),
    ] {
        match hid.get_input(report_id, len) {
            Ok(buf) => println!("GINPUT 0x{report_id:02x}: {}", hex(&buf)),
            Err(e) => println!("GINPUT 0x{report_id:02x}: {e}"),
        }
    }
    ExitCode::SUCCESS
}

fn cmd_send(rest: &[String]) -> ExitCode {
    if rest.len() < 2 {
        eprintln!("usage: mmx150-probe send <report_id> <hex bytes...>");
        return ExitCode::FAILURE;
    }
    let Ok(report_id) = u8::from_str_radix(rest[0].trim_start_matches("0x"), 16) else {
        eprintln!("bad report id");
        return ExitCode::FAILURE;
    };
    let mut data = vec![report_id];
    for part in &rest[1..] {
        let bytes = parse_hex(part);
        if bytes.is_empty() {
            eprintln!("bad hex: {part}");
            return ExitCode::FAILURE;
        }
        data.extend(bytes);
    }

    let Some(dev) = mmx150::hid::find_mmx150().unwrap_or(None) else {
        eprintln!("MMX 150 dongle not found");
        return ExitCode::FAILURE;
    };
    let hid = match Hidraw::open(&dev.devnode) {
        Ok(h) => h,
        Err(e) => {
            eprintln!("open failed: {e}");
            return ExitCode::FAILURE;
        }
    };
    let mut hid = hid;

    println!(
        ">> 0x{report_id:02x} [{}B] {}",
        data.len() - 1,
        hex(&data[1..])
    );
    match send_and_read(&mut hid, &data) {
        Some(resp) => println!("<< [{}B] {}", resp.len(), hex(&resp)),
        None => println!("<< no response"),
    }
    ExitCode::SUCCESS
}

/// Send one full output report (including report-id byte as data[0]) via the
/// interrupt OUT endpoint and return the first input report received, if any.
fn send_and_read(hid: &mut Hidraw, data: &[u8]) -> Option<Vec<u8>> {
    match hid.write(data) {
        Ok(_) => {}
        Err(e) => {
            eprintln!("write() failed: {e}");
            return None;
        }
    }
    hid.read_with_timeout(Duration::from_millis(400))
        .ok()
        .flatten()
}

/// Sweep a set of candidate commands against the dongle, printing responses
/// that differ from the all-zero baseline. Reports only non-trivial responses.
///
/// usage: mmx150-probe sweep <report_id> <B> ...
///   <report_id> is the output report id to use,
///   <B> is the report payload length (bytes, excluding the id byte).
fn cmd_status_dump() -> ExitCode {
    let Some(dev) = mmx150::hid::find_mmx150().unwrap_or(None) else {
        eprintln!("MMX 150 dongle not found");
        return ExitCode::FAILURE;
    };
    let hid = match Hidraw::open(&dev.devnode) {
        Ok(h) => h,
        Err(e) => {
            eprintln!("open failed: {e}");
            return ExitCode::FAILURE;
        }
    };
    let mut hid = hid;

    // Each row: label, report id, command payload.
    let cmds: Vec<(&str, u8, Vec<u8>)> = vec![
        ("0x2a echo/sel=0x0b", 0x2a, {
            let mut c = vec![0u8; 60];
            c[0] = 0x09;
            c[1] = 0x22;
            c[2] = 0x0b;
            c
        }),
        ("0x2a printf family 09 22", 0x2a, {
            let mut c = vec![0u8; 60];
            c[0] = 0x09;
            c[1] = 0x22;
            c[2] = 0x01;
            c
        }),
        ("0x2a eq family 09 00", 0x2a, {
            let mut c = vec![0u8; 60];
            c[0] = 0x09;
            c[1] = 0x00;
            c[2] = 0x0b;
            c
        }),
        ("0x3a sel=0x0b", 0x3a, {
            let mut c = vec![0u8; 60];
            c[0] = 0x09;
            c[1] = 0x22;
            c[2] = 0x0b;
            c
        }),
        ("0x3a sel=0x05", 0x3a, {
            let mut c = vec![0u8; 60];
            c[0] = 0x09;
            c[1] = 0x22;
            c[2] = 0x05;
            c
        }),
        ("0x3a sel=0x01", 0x3a, {
            let mut c = vec![0u8; 60];
            c[0] = 0x09;
            c[1] = 0x22;
            c[2] = 0x01;
            c
        }),
        ("0x2d signature", 0x2d, vec![0u8; 16]),
        ("0x3d signature", 0x3d, vec![0u8; 16]),
    ];

    for (label, rid, payload) in cmds {
        let mut frame = vec![rid];
        frame.extend(payload);
        let resp = send_and_read(&mut hid, &frame);
        println!(
            "{label:<26} >>0x{rid:02x} << {}",
            resp.map(|b| hex(&b)).unwrap_or_else(|| "<none>".into())
        );
        std::thread::sleep(Duration::from_millis(120));
    }
    ExitCode::SUCCESS
}

/// Enumerate many sub-command selectors across a report family, dumping any
/// response whose payload carries a real data byte (not just an echo of the
/// selector / a constant). This surfaces battery and state registers.
///
/// usage: mmx150-probe selenum [report_id]  (default: 0x3a)
fn cmd_sel_enum(rest: &[String]) -> ExitCode {
    let report_id = rest
        .first()
        .and_then(|s| u8::from_str_radix(s.trim_start_matches("0x"), 16).ok())
        .unwrap_or(0x3a);

    let Some(dev) = mmx150::hid::find_mmx150().unwrap_or(None) else {
        eprintln!("MMX 150 dongle not found");
        return ExitCode::FAILURE;
    };
    let hid = match Hidraw::open(&dev.devnode) {
        Ok(h) => h,
        Err(e) => {
            eprintln!("open failed: {e}");
            return ExitCode::FAILURE;
        }
    };
    let mut hid = hid;

    println!("sweeping report 0x{report_id:02x}, selector range 0x00..0xff");
    for sel in 0x00u8..=0xffu8 {
        let mut payload = vec![0u8; 60];
        payload[0] = 0x09;
        payload[1] = 0x22;
        payload[2] = sel;
        let mut frame = vec![report_id];
        frame.extend(payload);
        let resp = send_and_read(&mut hid, &frame);

        // Only report responses containing a "real" data byte beyond the
        // id/echo/constant region that could be battery/state.
        if let Some(b) = resp {
            if b.len() < 6 {
                continue;
            }
            // b[1] is the echo of sel, b[5] the constant ack. Look for any
            // non-zero byte among the remaining payload that isn't the ack.
            let interesting = b[6..].iter().any(|&x| x != 0x00);
            if interesting {
                println!("sel={sel:02x} resp={}", hex(&b));
            }
            std::thread::sleep(Duration::from_millis(8));
        }
    }
    ExitCode::SUCCESS
}

fn cmd_sweep(rest: &[String]) -> ExitCode {
    if rest.is_empty() {
        eprintln!("usage: mmx150-probe sweep <report_id> <payload_len>");
        return ExitCode::FAILURE;
    }
    let Ok(report_id) = u8::from_str_radix(rest[0].trim_start_matches("0x"), 16) else {
        eprintln!("bad report id");
        return ExitCode::FAILURE;
    };
    let plen: usize = rest.get(1).and_then(|s| s.parse().ok()).unwrap_or(60);

    let Some(dev) = mmx150::hid::find_mmx150().unwrap_or(None) else {
        eprintln!("MMX 150 dongle not found");
        return ExitCode::FAILURE;
    };
    let hid = match Hidraw::open(&dev.devnode) {
        Ok(h) => h,
        Err(e) => {
            eprintln!("open failed: {e}");
            return ExitCode::FAILURE;
        }
    };
    let mut hid = hid;

    // Baseline: all-zero command.
    let base = {
        let mut cmd = vec![report_id];
        cmd.extend(vec![0u8; plen]);
        send_and_read(&mut hid, &cmd)
    };
    println!(
        "baseline (all zero): {}",
        base.as_ref()
            .map(|b| hex(b.as_slice()))
            .unwrap_or_else(|| "<none>".into())
    );

    // Try setting individual low nibbles / bytes across the header to probe
    // which command byte selects a status register.
    for idx in 1..plen.clamp(1, 12) {
        for val in [0x01u8, 0x22, 0x2c, 0x2f, 0x80, 0x5a, 0xff] {
            let mut cmd = vec![report_id];
            cmd.extend(vec![0u8; plen]);
            cmd[idx] = val;
            match send_and_read(&mut hid, &cmd) {
                Some(resp) if Some(&resp) != base.as_ref() => {
                    println!("cmd[{idx:02}]=0x{val:02x} -> {}", hex(&resp));
                }
                _ => {}
            }
        }
    }
    ExitCode::SUCCESS
}

fn hex(bytes: &[u8]) -> String {
    bytes
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect::<Vec<_>>()
        .join(" ")
}

fn parse_hex(s: &str) -> Vec<u8> {
    let s = s.trim_start_matches("0x");
    if !s.len().is_multiple_of(2) {
        return Vec::new();
    }
    s.as_bytes()
        .chunks(2)
        .map(|c| {
            let hi = (c[0] as char).to_digit(16)?;
            let lo = (c[1] as char).to_digit(16)?;
            Some((hi * 16 + lo) as u8)
        })
        .collect::<Option<Vec<u8>>>()
        .unwrap_or_default()
}