Skip to main content

cli/
cli.rs

1//! Interactive REPL for manual testing of the protocol crate.
2//! Transport-agnostic: the same [`Command`]/[`DeviceEvent`] vocabulary drives
3//! the device over either USB HID (`/dev/hidraw*` + the crate's [`usb`] frame)
4//! or TCP (the crate's [`frame`] format). Only the I/O loop and the
5//! outer framing differ; everything from `parse_valuetree` and [`Layout`] on
6//! up is reused.
7//!
8//! ## Run
9//!
10//! ```text
11//! # USB (auto-detect a Pro II / Duo by VID:PID on any /dev/hidrawN):
12//! nix develop --command cargo run --example cli
13//! nix develop --command cargo run --example cli -- usb
14//! nix develop --command cargo run --example cli -- usb /dev/hidraw3
15//!
16//! # TCP (direct device port or network proxy):
17//! nix develop --command cargo run --example cli -- tcp 192.168.1.5:2345
18//! nix develop --command cargo run --example cli -- tcp 127.0.0.1:2346
19//! ```
20//!
21//! USB needs read+write on `/dev/hidraw*` (sudo, or a udev rule for VID
22//! `19f7`). TCP needs network reach to the target address.
23//!
24//! ## Commands
25//!
26//! Type `help` at the prompt for the full list. Quick start:
27//!
28//! ```text
29//! > layout
30//! > watch on            # live event print on (default)
31//! > mute p1 on          # mute physical fader 1
32//! > level v1 64         # set virtual fader 1 to mid scale
33//! > link usb1 hp1       # native link USB-1 source -> Headphone-1 mix
34//! > set master CompellorOn true   # generic typed-family setter
35//! > quit
36//! ```
37//!
38//! Linux-only for USB (uses `/dev/hidraw*` and sysfs); TCP works anywhere.
39
40use std::fs::{self, File, OpenOptions};
41use std::io::{self, BufRead, Read, Write};
42use std::net::TcpStream;
43use std::path::{Path, PathBuf};
44use std::sync::atomic::{AtomicBool, Ordering};
45use std::sync::{Arc, Mutex};
46use std::thread;
47use std::time::Duration;
48
49use rodecaster_protocol::{
50    change_frame, decode_event, frame, parse_valuetree, usb, AppParam, AudioParam, BuildParam,
51    ChannelParam, Command, CurrentShowParam, DeviceEvent, DeviceModel, DuckerParam, EffectsParam,
52    Fader, FrameScan, GuiParam, HeadphoneParam, InputSourceParam, Layout, MasterParam,
53    MixMinusesParam, MixOutput, NetworkParam, Node, OutputParam, PadParam, PlayerParam, RadioParam,
54    RadioRxParam, RadioTxParam, RcSyncMixParam, RecorderParam, RecordingParam, RecordingsParam,
55    ShowControlParam, ShowParam, Source, StorageVolumeParam, StreamerXMixPresetParam,
56    StreamerXStreamMixParam, SystemParam, ThemeParam, Value, WifiScanResultParam,
57};
58
59const RODE_VID: u16 = 0x19F7;
60const PID_PRO2: u16 = 0x0094;
61const PID_DUO: u16 = 0x0095;
62const PID_DUO_ALT: u16 = 0x0050;
63
64type Shared<T> = Arc<Mutex<T>>;
65type DynErr = Box<dyn std::error::Error + Send + Sync>;
66
67/// Write side of a connected transport: hands one JUCE body over to the
68/// transport's framing module and onto the wire. Cloneable so the REPL can
69/// hold one writer while other threads keep their own [`Arc`] to the
70/// underlying file / socket.
71type Writer = Arc<dyn Fn(Vec<u8>) -> Result<(), DynErr> + Send + Sync>;
72
73enum TransportArg {
74    Usb(Option<PathBuf>),
75    Tcp(String),
76}
77
78fn main() {
79    if let Err(e) = run() {
80        eprintln!("error: {e}");
81        std::process::exit(1);
82    }
83}
84
85fn parse_args() -> Result<TransportArg, DynErr> {
86    let mut args = std::env::args().skip(1);
87    match (args.next(), args.next(), args.next()) {
88        (None, _, _) => Ok(TransportArg::Usb(None)),
89        (Some(t), None, _) if t == "usb" => Ok(TransportArg::Usb(None)),
90        (Some(t), Some(p), None) if t == "usb" => Ok(TransportArg::Usb(Some(PathBuf::from(p)))),
91        (Some(t), Some(addr), None) if t == "tcp" => Ok(TransportArg::Tcp(addr)),
92        _ => Err("usage: cli [usb [/dev/hidrawN] | tcp <host:port>]".into()),
93    }
94}
95
96fn run() -> Result<(), DynErr> {
97    let arg = parse_args()?;
98    let layout: Shared<Option<Layout>> = Arc::new(Mutex::new(None));
99    let root: Shared<Option<Node>> = Arc::new(Mutex::new(None));
100    let watch = Arc::new(AtomicBool::new(true));
101
102    let writer = match arg {
103        TransportArg::Usb(path) => start_usb(path, &layout, &root, &watch)?,
104        TransportArg::Tcp(addr) => start_tcp(&addr, &layout, &root, &watch)?,
105    };
106
107    // Give the reader a beat to ingest the first fullSync so `layout` is
108    // probably populated before the user's first command.
109    thread::sleep(Duration::from_millis(250));
110
111    repl(&writer, &layout, &root, &watch)
112}
113
114// ──────────────────────────────────────────────────────────────────────────
115// Transport setup
116// ──────────────────────────────────────────────────────────────────────────
117
118fn start_usb(
119    explicit: Option<PathBuf>,
120    layout: &Shared<Option<Layout>>,
121    root: &Shared<Option<Node>>,
122    watch: &Arc<AtomicBool>,
123) -> Result<Writer, DynErr> {
124    let path = match explicit {
125        Some(p) => p,
126        None => {
127            let (p, model) = find_device()?.ok_or(
128                "no RODECaster Pro II / Duo on any /dev/hidraw* (VID 19f7 PID 0094/0095). \
129                 Is the device plugged in and powered?",
130            )?;
131            eprintln!("usb: {} ({})", p.display(), model_label(model));
132            p
133        }
134    };
135    let file = Arc::new(open_hidraw(&path)?);
136    // USB needs an explicit handshake; the device stays silent until it sees
137    // [`usb::HANDSHAKE_BODY`].
138    write_usb(&file, usb::HANDSHAKE_BODY.to_vec())?;
139
140    let reader_file = Arc::clone(&file);
141    let reader_layout = Arc::clone(layout);
142    let reader_root = Arc::clone(root);
143    let reader_watch = Arc::clone(watch);
144    thread::spawn(move || usb_reader_loop(reader_file, reader_layout, reader_root, reader_watch));
145
146    let writer_file = Arc::clone(&file);
147    Ok(Arc::new(move |body| write_usb(&writer_file, body)))
148}
149
150fn start_tcp(
151    addr: &str,
152    layout: &Shared<Option<Layout>>,
153    root: &Shared<Option<Node>>,
154    watch: &Arc<AtomicBool>,
155) -> Result<Writer, DynErr> {
156    eprintln!("tcp: connecting to {addr}");
157    let stream = Arc::new(TcpStream::connect(addr)?);
158    eprintln!("tcp: connected");
159    // No handshake on TCP: the device starts streaming the
160    // fullSync as soon as a client connects.
161
162    let reader_stream = Arc::clone(&stream);
163    let reader_layout = Arc::clone(layout);
164    let reader_root = Arc::clone(root);
165    let reader_watch = Arc::clone(watch);
166    thread::spawn(move || tcp_reader_loop(reader_stream, reader_layout, reader_root, reader_watch));
167
168    let writer_stream = Arc::clone(&stream);
169    Ok(Arc::new(move |body| write_tcp(&writer_stream, body)))
170}
171
172// ──────────────────────────────────────────────────────────────────────────
173// Device discovery
174// ──────────────────────────────────────────────────────────────────────────
175
176fn find_device() -> Result<Option<(PathBuf, DeviceModel)>, DynErr> {
177    let class = Path::new("/sys/class/hidraw");
178    if !class.exists() {
179        return Err("no /sys/class/hidraw on this system; this example is Linux-only".into());
180    }
181    for entry in fs::read_dir(class)? {
182        let entry = entry?;
183        let uevent = entry.path().join("device/uevent");
184        let Ok(text) = fs::read_to_string(&uevent) else {
185            continue;
186        };
187        // Format: HID_ID=0003:000019F7:00000094
188        let Some(line) = text.lines().find(|l| l.starts_with("HID_ID=")) else {
189            continue;
190        };
191        let parts: Vec<&str> = line.trim_start_matches("HID_ID=").split(':').collect();
192        if parts.len() != 3 {
193            continue;
194        }
195        let vid = u32::from_str_radix(parts[1], 16).unwrap_or(0) as u16;
196        let pid = u32::from_str_radix(parts[2], 16).unwrap_or(0) as u16;
197        if vid != RODE_VID {
198            continue;
199        }
200        let model = match pid {
201            PID_PRO2 => DeviceModel::Pro2,
202            PID_DUO | PID_DUO_ALT => DeviceModel::Duo,
203            _ => continue,
204        };
205        let dev = PathBuf::from("/dev").join(entry.file_name());
206        return Ok(Some((dev, model)));
207    }
208    Ok(None)
209}
210
211fn open_hidraw(path: &Path) -> Result<File, DynErr> {
212    OpenOptions::new()
213        .read(true)
214        .write(true)
215        .open(path)
216        .map_err(|e| format!("open {}: {e}", path.display()).into())
217}
218
219fn model_label(m: DeviceModel) -> &'static str {
220    match m {
221        DeviceModel::Pro2 => "RODECaster Pro II",
222        DeviceModel::Duo => "RODECaster Duo",
223    }
224}
225
226// ──────────────────────────────────────────────────────────────────────────
227// Transport I/O: two pairs (write + reader_loop), one per framing
228// ──────────────────────────────────────────────────────────────────────────
229
230/// Wrap one JUCE body into [`usb::Packet`], chunk into HID reports, write each
231/// report as one syscall (the kernel wants one report per write).
232fn write_usb(file: &File, body: Vec<u8>) -> Result<(), DynErr> {
233    let bytes = usb::Packet::new(body).to_bytes();
234    let mut f: &File = file;
235    for chunk in bytes.chunks(usb::REPORT_SIZE) {
236        f.write_all(chunk)?;
237    }
238    Ok(())
239}
240
241/// Wrap one JUCE body into [`frame::Packet`] (magic + length + body) and write
242/// the whole frame in one stream write.
243fn write_tcp(stream: &TcpStream, body: Vec<u8>) -> Result<(), DynErr> {
244    let bytes = frame::Packet::new(body).to_bytes();
245    let mut s: &TcpStream = stream;
246    s.write_all(&bytes)?;
247    Ok(())
248}
249
250fn usb_reader_loop(
251    file: Arc<File>,
252    layout: Shared<Option<Layout>>,
253    root: Shared<Option<Node>>,
254    watch: Arc<AtomicBool>,
255) {
256    let mut buf = Vec::<u8>::with_capacity(usb::REPORT_SIZE * 4);
257    let mut report = [0u8; usb::REPORT_SIZE];
258    loop {
259        let mut f: &File = &file;
260        let n = match f.read(&mut report) {
261            Ok(0) => return, // EOF: device went away or main dropped its handle
262            Ok(n) => n,
263            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
264            Err(_) => return,
265        };
266        buf.extend_from_slice(&report[..n]);
267        loop {
268            match usb::scan_frame(&buf) {
269                FrameScan::Incomplete => break,
270                FrameScan::Desync => {
271                    // One report's worth is junk; drop and rescan.
272                    let drop = usb::REPORT_SIZE.min(buf.len());
273                    buf.drain(..drop);
274                }
275                FrameScan::Complete { len } => {
276                    let Some((packet, consumed)) = usb::Packet::from_bytes(&buf[..len]) else {
277                        buf.drain(..len);
278                        continue;
279                    };
280                    buf.drain(..consumed);
281                    handle_body(packet.payload, &layout, &root, &watch);
282                }
283            }
284        }
285    }
286}
287
288fn tcp_reader_loop(
289    stream: Arc<TcpStream>,
290    layout: Shared<Option<Layout>>,
291    root: Shared<Option<Node>>,
292    watch: Arc<AtomicBool>,
293) {
294    let mut buf = Vec::<u8>::with_capacity(8192);
295    let mut chunk = [0u8; 4096];
296    loop {
297        let mut s: &TcpStream = &stream;
298        let n = match s.read(&mut chunk) {
299            Ok(0) => return,
300            Ok(n) => n,
301            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
302            Err(_) => return,
303        };
304        buf.extend_from_slice(&chunk[..n]);
305        loop {
306            match frame::scan_frame(&buf) {
307                FrameScan::Incomplete => break,
308                FrameScan::Desync => {
309                    // TCP frames are byte-aligned (no report stride);
310                    // slide one byte and rescan to resync on a fresh magic.
311                    buf.drain(..1);
312                }
313                FrameScan::Complete { len } => {
314                    let Some((packet, consumed)) = frame::Packet::from_bytes(&buf[..len]) else {
315                        buf.drain(..len);
316                        continue;
317                    };
318                    buf.drain(..consumed);
319                    handle_body(packet.payload, &layout, &root, &watch);
320                }
321            }
322        }
323    }
324}
325
326fn handle_body(
327    body: Vec<u8>,
328    layout: &Shared<Option<Layout>>,
329    root: &Shared<Option<Node>>,
330    watch: &AtomicBool,
331) {
332    // 0x02 = JUCE fullSync. Build a fresh Layout from the parsed tree so
333    // subsequent change-frames decode against an up-to-date address map.
334    if body.first() == Some(&0x02) {
335        if let Some(parsed_root) = parse_valuetree(&body) {
336            match Layout::from_full_sync(&parsed_root) {
337                Ok(new_layout) => {
338                    println!(
339                        "\n[layout] fullSync received: {} model, {} faders, {} sources, {} mixes",
340                        model_label(new_layout.model()),
341                        new_layout.fader_count(),
342                        new_layout.source_count(),
343                        new_layout.mix_count_per_source(),
344                    );
345                    *layout.lock().unwrap() = Some(new_layout);
346                    *root.lock().unwrap() = Some(parsed_root);
347                    if watch.load(Ordering::Relaxed) {
348                        // InitialState bursts can flood the terminal; print only
349                        // the count, not every property.
350                        if let Some(l) = layout.lock().unwrap().as_ref() {
351                            if let Some(DeviceEvent::InitialState(events)) = decode_event(&body, l)
352                            {
353                                println!("[initial-state] {} properties", events.len());
354                            }
355                        }
356                    }
357                    reprompt();
358                }
359                Err(e) => {
360                    println!("\n[layout] fullSync decode failed: {e:?}");
361                    reprompt();
362                }
363            }
364        }
365        return;
366    }
367
368    let guard = layout.lock().unwrap();
369    let Some(l) = guard.as_ref() else {
370        if watch.load(Ordering::Relaxed) {
371            println!("\n[event] (no layout yet, {} bytes)", body.len());
372            reprompt();
373        }
374        return;
375    };
376    if let Some(event) = decode_event(&body, l) {
377        if watch.load(Ordering::Relaxed) {
378            print_event(&event);
379        }
380    }
381}
382
383fn print_event(event: &DeviceEvent) {
384    match event {
385        DeviceEvent::InitialState(v) => {
386            println!("\n[event] InitialState ({} properties)", v.len());
387        }
388        other => {
389            println!("\n[event] {other:?}");
390        }
391    }
392    reprompt();
393}
394
395fn reprompt() {
396    print!("> ");
397    let _ = io::stdout().flush();
398}
399
400// ──────────────────────────────────────────────────────────────────────────
401// REPL
402// ──────────────────────────────────────────────────────────────────────────
403
404fn repl(
405    writer: &Writer,
406    layout: &Shared<Option<Layout>>,
407    root: &Shared<Option<Node>>,
408    watch: &AtomicBool,
409) -> Result<(), DynErr> {
410    let stdin = io::stdin();
411    reprompt();
412    for line in stdin.lock().lines() {
413        let line = line?;
414        let trimmed = line.trim();
415        if trimmed.is_empty() {
416            reprompt();
417            continue;
418        }
419        match dispatch(trimmed, writer, layout, root, watch) {
420            Ok(Outcome::Continue) => {}
421            Ok(Outcome::Quit) => return Ok(()),
422            Err(e) => println!("err: {e}"),
423        }
424        reprompt();
425    }
426    Ok(())
427}
428
429enum Outcome {
430    Continue,
431    Quit,
432}
433
434fn dispatch(
435    line: &str,
436    writer: &Writer,
437    layout: &Shared<Option<Layout>>,
438    root: &Shared<Option<Node>>,
439    watch: &AtomicBool,
440) -> Result<Outcome, String> {
441    let mut tok = line.split_whitespace();
442    let head = tok.next().unwrap();
443    let rest: Vec<&str> = tok.collect();
444    match head {
445        "help" | "?" => {
446            print_help();
447            Ok(Outcome::Continue)
448        }
449        "quit" | "exit" => Ok(Outcome::Quit),
450        "layout" => {
451            print_layout(layout);
452            Ok(Outcome::Continue)
453        }
454        "dump-cell" => {
455            dump_cell(layout, root, &rest)?;
456            Ok(Outcome::Continue)
457        }
458        "raw-press" => raw_request(writer, layout, &rest, RawValue::Press),
459        "raw-release" => raw_request(writer, layout, &rest, RawValue::Release),
460        "raw-bool" => {
461            let on = parse_bool(rest.get(3).copied().unwrap_or(""))?;
462            raw_request(writer, layout, &rest[..3], RawValue::Bool(on))
463        }
464        "raw-write" => raw_write(writer, &rest),
465        "refresh" => {
466            writer(usb::HANDSHAKE_BODY.to_vec()).map_err(|e| format!("write: {e}"))?;
467            println!("sent handshake; fresh fullSync incoming");
468            Ok(Outcome::Continue)
469        }
470        "dump-schema" => {
471            dump_schema(root)?;
472            Ok(Outcome::Continue)
473        }
474        "dump-node" => {
475            let name = rest
476                .first()
477                .copied()
478                .ok_or_else(|| "usage: dump-node <NODE_NAME>".to_string())?;
479            dump_node(root, name)?;
480            Ok(Outcome::Continue)
481        }
482        "watch" => {
483            let on = parse_bool(rest.first().copied().unwrap_or("on"))?;
484            watch.store(on, Ordering::Relaxed);
485            println!("watch {}", if on { "on" } else { "off" });
486            Ok(Outcome::Continue)
487        }
488        "mute" => one_shot(writer, layout, parse_set_fader_mute(&rest)?),
489        "cue" => one_shot(writer, layout, parse_set_fader_cue(&rest)?),
490        "level" => one_shot(writer, layout, parse_set_fader_level(&rest)?),
491        "assign" => one_shot(writer, layout, parse_assign_fader(&rest)?),
492        "mix-disable" => one_shot(writer, layout, parse_mix_disable(&rest)?),
493        "mix-mute" => one_shot(writer, layout, parse_mix_mute(&rest)?),
494        "link" => one_shot(writer, layout, parse_link(&rest)?),
495        "unlink" => one_shot(writer, layout, parse_unlink(&rest)?),
496        "link-callme" => one_shot(writer, layout, parse_link_callme(&rest)?),
497        "unlink-callme" => one_shot(writer, layout, parse_unlink_callme(&rest)?),
498        "screen" => one_shot(writer, layout, Command::ScreenTouched),
499        "skip-setup" | "setup-skip" => one_shot(writer, layout, parse_setup_skip(&rest)?),
500        "power" => {
501            print!("really power off? type 'yes' to confirm: ");
502            io::stdout().flush().ok();
503            let mut s = String::new();
504            io::stdin().read_line(&mut s).ok();
505            if s.trim() == "yes" {
506                one_shot(writer, layout, Command::PowerOff)
507            } else {
508                println!("cancelled");
509                Ok(Outcome::Continue)
510            }
511        }
512        "set" => one_shot(writer, layout, parse_set(&rest)?),
513        other => Err(format!("unknown command: {other}. try `help`")),
514    }
515}
516
517fn one_shot(
518    writer: &Writer,
519    layout: &Shared<Option<Layout>>,
520    cmd: Command,
521) -> Result<Outcome, String> {
522    let guard = layout.lock().unwrap();
523    let layout_ref = guard
524        .as_ref()
525        .ok_or_else(|| "no Layout yet; wait for the fullSync print".to_string())?;
526    let frames = cmd
527        .encode(layout_ref)
528        .map_err(|e| format!("encode: {e:?}"))?;
529    drop(guard);
530    let n = frames.len();
531    for body in frames {
532        writer(body).map_err(|e| format!("write: {e}"))?;
533    }
534    println!("sent {n} frame{}", if n == 1 { "" } else { "s" });
535    Ok(Outcome::Continue)
536}
537
538// ──────────────────────────────────────────────────────────────────────────
539// Parsers
540// ──────────────────────────────────────────────────────────────────────────
541
542fn parse_bool(s: &str) -> Result<bool, String> {
543    match s.to_ascii_lowercase().as_str() {
544        "on" | "true" | "1" | "yes" => Ok(true),
545        "off" | "false" | "0" | "no" => Ok(false),
546        other => Err(format!("expected on/off, got {other}")),
547    }
548}
549
550fn parse_fader(s: &str) -> Result<Fader, String> {
551    match s.to_ascii_lowercase().as_str() {
552        "p1" => Ok(Fader::Physical1),
553        "p2" => Ok(Fader::Physical2),
554        "p3" => Ok(Fader::Physical3),
555        "p4" => Ok(Fader::Physical4),
556        "p5" => Ok(Fader::Physical5),
557        "p6" => Ok(Fader::Physical6),
558        "v1" => Ok(Fader::Virtual1),
559        "v2" => Ok(Fader::Virtual2),
560        "v3" => Ok(Fader::Virtual3),
561        "v4" => Ok(Fader::Virtual4),
562        "v5" => Ok(Fader::Virtual5),
563        other => Err(format!("expected fader p1..p6 / v1..v5, got {other}")),
564    }
565}
566
567fn parse_source(s: &str) -> Result<Source, String> {
568    match s.to_ascii_lowercase().as_str() {
569        "combo1" => Ok(Source::Combo1),
570        "combo2" => Ok(Source::Combo2),
571        "combo3" => Ok(Source::Combo3),
572        "combo4" => Ok(Source::Combo4),
573        "combo1_2" | "combo12" => Ok(Source::Combo1_2),
574        "combo2_3" | "combo23" => Ok(Source::Combo2_3),
575        "combo3_4" | "combo34" => Ok(Source::Combo3_4),
576        "usb1" => Ok(Source::Usb1),
577        "chat" => Ok(Source::Chat),
578        "usb2" => Ok(Source::Usb2),
579        "bt" | "bluetooth" => Ok(Source::Bluetooth),
580        "pad" | "soundpad" => Ok(Source::SoundPad),
581        "vgame" | "virtualgame" => Ok(Source::VirtualGame),
582        "vmusic" | "virtualmusic" => Ok(Source::VirtualMusic),
583        "va" | "virtuala" => Ok(Source::VirtualA),
584        "vb" | "virtualb" => Ok(Source::VirtualB),
585        "callme1" => Ok(Source::CallMe1),
586        "callme2" => Ok(Source::CallMe2),
587        "callme3" => Ok(Source::CallMe3),
588        other => Err(format!("unknown source: {other}")),
589    }
590}
591
592fn parse_mix(s: &str) -> Result<MixOutput, String> {
593    match s.to_ascii_lowercase().as_str() {
594        "hp1" | "headphone1" => Ok(MixOutput::Headphone1),
595        "hp2" | "headphone2" => Ok(MixOutput::Headphone2),
596        "hp3" | "headphone3" => Ok(MixOutput::Headphone3),
597        "hp4" | "headphone4" => Ok(MixOutput::Headphone4),
598        "spk" | "speaker" => Ok(MixOutput::Speaker),
599        "rec" | "recording" => Ok(MixOutput::Recording),
600        "bt" | "bluetooth" => Ok(MixOutput::Bluetooth),
601        "usb1" => Ok(MixOutput::Usb1),
602        "chat" => Ok(MixOutput::Chat),
603        "usb2" => Ok(MixOutput::Usb2),
604        "callme1" => Ok(MixOutput::CallMe1),
605        "callme2" => Ok(MixOutput::CallMe2),
606        "callme3" => Ok(MixOutput::CallMe3),
607        other => Err(format!("unknown mix output: {other}")),
608    }
609}
610
611fn need_args<'a>(args: &'a [&'a str], n: usize, usage: &str) -> Result<(), String> {
612    if args.len() < n {
613        Err(format!("usage: {usage}"))
614    } else {
615        Ok(())
616    }
617}
618
619fn parse_set_fader_mute(args: &[&str]) -> Result<Command, String> {
620    need_args(args, 2, "mute <fader> <on|off>")?;
621    Ok(Command::SetFaderMute {
622        fader: parse_fader(args[0])?,
623        mute: parse_bool(args[1])?,
624    })
625}
626
627fn parse_set_fader_cue(args: &[&str]) -> Result<Command, String> {
628    need_args(args, 2, "cue <fader> <on|off>")?;
629    Ok(Command::SetFaderCue {
630        fader: parse_fader(args[0])?,
631        enable: parse_bool(args[1])?,
632    })
633}
634
635fn parse_set_fader_level(args: &[&str]) -> Result<Command, String> {
636    need_args(args, 2, "level <fader> <0..127>")?;
637    let level: u8 = args[1]
638        .parse()
639        .map_err(|_| format!("level not 0..127: {}", args[1]))?;
640    Ok(Command::SetFaderLevel {
641        fader: parse_fader(args[0])?,
642        level,
643    })
644}
645
646fn parse_assign_fader(args: &[&str]) -> Result<Command, String> {
647    need_args(args, 2, "assign <fader> <source|clear>")?;
648    let fader = parse_fader(args[0])?;
649    let source = if args[1].eq_ignore_ascii_case("clear") || args[1].eq_ignore_ascii_case("none") {
650        None
651    } else {
652        Some(parse_source(args[1])?)
653    };
654    Ok(Command::AssignFaderSource { fader, source })
655}
656
657fn parse_mix_disable(args: &[&str]) -> Result<Command, String> {
658    need_args(args, 3, "mix-disable <source> <mix> <on|off>")?;
659    Ok(Command::SetMixDisabled {
660        source: parse_source(args[0])?,
661        mix: parse_mix(args[1])?,
662        disabled: parse_bool(args[2])?,
663    })
664}
665
666fn parse_mix_mute(args: &[&str]) -> Result<Command, String> {
667    need_args(args, 3, "mix-mute <source> <mix> <on|off>")?;
668    Ok(Command::SetMixMute {
669        source: parse_source(args[0])?,
670        mix: parse_mix(args[1])?,
671        mute: parse_bool(args[2])?,
672    })
673}
674
675fn parse_link(args: &[&str]) -> Result<Command, String> {
676    need_args(args, 2, "link <source> <mix>")?;
677    Ok(Command::LinkMix {
678        source: parse_source(args[0])?,
679        mix: parse_mix(args[1])?,
680    })
681}
682
683fn parse_unlink(args: &[&str]) -> Result<Command, String> {
684    need_args(args, 2, "unlink <source> <mix>")?;
685    Ok(Command::UnlinkMix {
686        source: parse_source(args[0])?,
687        mix: parse_mix(args[1])?,
688    })
689}
690
691fn parse_link_callme(args: &[&str]) -> Result<Command, String> {
692    need_args(args, 2, "link-callme <callme1..3> <mix>")?;
693    let source = parse_source(args[0])?;
694    if !matches!(source, Source::CallMe1 | Source::CallMe2 | Source::CallMe3) {
695        return Err("link-callme needs a CallMe source (callme1..callme3)".into());
696    }
697    Ok(Command::LinkCallMe {
698        source,
699        mix: parse_mix(args[1])?,
700    })
701}
702
703fn parse_unlink_callme(args: &[&str]) -> Result<Command, String> {
704    need_args(args, 2, "unlink-callme <callme1..3> <mix>")?;
705    let source = parse_source(args[0])?;
706    if !matches!(source, Source::CallMe1 | Source::CallMe2 | Source::CallMe3) {
707        return Err("unlink-callme needs a CallMe source (callme1..callme3)".into());
708    }
709    Ok(Command::UnlinkCallMe {
710        source,
711        mix: parse_mix(args[1])?,
712    })
713}
714
715fn parse_setup_skip(args: &[&str]) -> Result<Command, String> {
716    let lang = args
717        .first()
718        .copied()
719        .filter(|s| *s != "none")
720        .map(|s| s.to_string());
721    let tz = args
722        .get(1..)
723        .map(|a| a.join(" "))
724        .filter(|s| !s.is_empty() && s != "none");
725    Ok(Command::SetupSkip {
726        language: lang,
727        timezone: tz,
728    })
729}
730
731/// `set <family> [key...] <wire-name> <value-kind> <value...>`
732///
733/// Families with no addressing key: master / output / ducker / recorder /
734/// player / gui / system. Per-instance families need a key:
735///   - channel        <fader>
736///   - inputsource    <source>
737///   - headphone      <0..N>     (N = `layout.headphone_count()`)
738///   - effects        <0..N>     (N = `layout.effects_count()`)
739///   - pad            <0..N>     (N = `layout.pad_count()`)
740fn parse_set(args: &[&str]) -> Result<Command, String> {
741    if args.is_empty() {
742        return Err("usage: set <family> [key] <wire-name> <kind> <value...>".into());
743    }
744    let family = args[0].to_ascii_lowercase();
745    let rest = &args[1..];
746    match family.as_str() {
747        "master" => {
748            need_args(rest, 3, "set master <wire-name> <kind> <value>")?;
749            let value = parse_value(&rest[1..])?;
750            Ok(Command::SetMasterParam {
751                param: MasterParam::from_name(rest[0]),
752                value,
753            })
754        }
755        "output" => {
756            need_args(rest, 3, "set output <wire-name> <kind> <value>")?;
757            let value = parse_value(&rest[1..])?;
758            Ok(Command::SetOutputParam {
759                param: OutputParam::from_name(rest[0]),
760                value,
761            })
762        }
763        "ducker" => {
764            need_args(rest, 3, "set ducker <wire-name> <kind> <value>")?;
765            let value = parse_value(&rest[1..])?;
766            Ok(Command::SetDuckerParam {
767                param: DuckerParam::from_name(rest[0]),
768                value,
769            })
770        }
771        "recorder" => {
772            need_args(rest, 3, "set recorder <wire-name> <kind> <value>")?;
773            let value = parse_value(&rest[1..])?;
774            Ok(Command::SetRecorderParam {
775                param: RecorderParam::from_name(rest[0]),
776                value,
777            })
778        }
779        "player" => {
780            need_args(rest, 3, "set player <wire-name> <kind> <value>")?;
781            let value = parse_value(&rest[1..])?;
782            Ok(Command::SetPlayerParam {
783                param: PlayerParam::from_name(rest[0]),
784                value,
785            })
786        }
787        "gui" => {
788            need_args(rest, 3, "set gui <wire-name> <kind> <value>")?;
789            let value = parse_value(&rest[1..])?;
790            Ok(Command::SetGuiParam {
791                param: GuiParam::from_name(rest[0]),
792                value,
793            })
794        }
795        "system" => {
796            need_args(rest, 3, "set system <wire-name> <kind> <value>")?;
797            let value = parse_value(&rest[1..])?;
798            Ok(Command::SetSystemParam {
799                param: SystemParam::from_name(rest[0]),
800                value,
801            })
802        }
803        "channel" => {
804            need_args(rest, 4, "set channel <fader> <wire-name> <kind> <value>")?;
805            let fader = parse_fader(rest[0])?;
806            let value = parse_value(&rest[2..])?;
807            Ok(Command::SetChannelParam {
808                fader,
809                param: ChannelParam::from_name(rest[1]),
810                value,
811            })
812        }
813        "inputsource" | "input-source" | "input_source" => {
814            need_args(
815                rest,
816                4,
817                "set inputsource <source> <wire-name> <kind> <value>",
818            )?;
819            let source = parse_source(rest[0])?;
820            let value = parse_value(&rest[2..])?;
821            Ok(Command::SetInputSourceParam {
822                source,
823                param: InputSourceParam::from_name(rest[1]),
824                value,
825            })
826        }
827        "headphone" => {
828            need_args(rest, 4, "set headphone <0..N> <wire-name> <kind> <value>")?;
829            let headphone: u8 = rest[0]
830                .parse()
831                .map_err(|_| format!("headphone index not numeric: {}", rest[0]))?;
832            let value = parse_value(&rest[2..])?;
833            Ok(Command::SetHeadphoneParam {
834                headphone,
835                param: HeadphoneParam::from_name(rest[1]),
836                value,
837            })
838        }
839        "effects" => {
840            need_args(rest, 4, "set effects <0..N> <wire-name> <kind> <value>")?;
841            let effects: u8 = rest[0]
842                .parse()
843                .map_err(|_| format!("effects index not numeric: {}", rest[0]))?;
844            let value = parse_value(&rest[2..])?;
845            Ok(Command::SetEffectsParam {
846                effects,
847                param: EffectsParam::from_name(rest[1]),
848                value,
849            })
850        }
851        "pad" => {
852            need_args(rest, 4, "set pad <0..N> <wire-name> <kind> <value>")?;
853            let pad: u8 = rest[0]
854                .parse()
855                .map_err(|_| format!("pad index not numeric: {}", rest[0]))?;
856            let value = parse_value(&rest[2..])?;
857            Ok(Command::SetPadParam {
858                pad,
859                param: PadParam::from_name(rest[1]),
860                value,
861            })
862        }
863        "network" => {
864            need_args(rest, 3, "set network <wire-name> <kind> <value>")?;
865            let value = parse_value(&rest[1..])?;
866            Ok(Command::SetNetworkParam {
867                param: NetworkParam::from_name(rest[0]),
868                value,
869            })
870        }
871        "audio" => {
872            need_args(rest, 3, "set audio <wire-name> <kind> <value>")?;
873            let value = parse_value(&rest[1..])?;
874            Ok(Command::SetAudioParam {
875                param: AudioParam::from_name(rest[0]),
876                value,
877            })
878        }
879        "build" => {
880            need_args(rest, 3, "set build <wire-name> <kind> <value>")?;
881            let value = parse_value(&rest[1..])?;
882            Ok(Command::SetBuildParam {
883                param: BuildParam::from_name(rest[0]),
884                value,
885            })
886        }
887        "app" => {
888            need_args(rest, 3, "set app <wire-name> <kind> <value>")?;
889            let value = parse_value(&rest[1..])?;
890            Ok(Command::SetAppParam {
891                param: AppParam::from_name(rest[0]),
892                value,
893            })
894        }
895        "theme" => {
896            need_args(rest, 3, "set theme <wire-name> <kind> <value>")?;
897            let value = parse_value(&rest[1..])?;
898            Ok(Command::SetThemeParam {
899                param: ThemeParam::from_name(rest[0]),
900                value,
901            })
902        }
903        "currentshow" | "current-show" => {
904            need_args(rest, 3, "set currentshow <wire-name> <kind> <value>")?;
905            let value = parse_value(&rest[1..])?;
906            Ok(Command::SetCurrentShowParam {
907                param: CurrentShowParam::from_name(rest[0]),
908                value,
909            })
910        }
911        "showcontrol" | "show-control" => {
912            need_args(rest, 3, "set showcontrol <wire-name> <kind> <value>")?;
913            let value = parse_value(&rest[1..])?;
914            Ok(Command::SetShowControlParam {
915                param: ShowControlParam::from_name(rest[0]),
916                value,
917            })
918        }
919        "recordings" => {
920            need_args(rest, 3, "set recordings <wire-name> <kind> <value>")?;
921            let value = parse_value(&rest[1..])?;
922            Ok(Command::SetRecordingsParam {
923                param: RecordingsParam::from_name(rest[0]),
924                value,
925            })
926        }
927        "radio" => {
928            need_args(rest, 3, "set radio <wire-name> <kind> <value>")?;
929            let value = parse_value(&rest[1..])?;
930            Ok(Command::SetRadioParam {
931                param: RadioParam::from_name(rest[0]),
932                value,
933            })
934        }
935        "show" => {
936            need_args(rest, 4, "set show <0..N> <wire-name> <kind> <value>")?;
937            let show: u8 = rest[0]
938                .parse()
939                .map_err(|_| format!("show index not numeric: {}", rest[0]))?;
940            let value = parse_value(&rest[2..])?;
941            Ok(Command::SetShowParam {
942                show,
943                param: ShowParam::from_name(rest[1]),
944                value,
945            })
946        }
947        "recording" => {
948            need_args(rest, 4, "set recording <0..N> <wire-name> <kind> <value>")?;
949            let recording: u8 = rest[0]
950                .parse()
951                .map_err(|_| format!("recording index not numeric: {}", rest[0]))?;
952            let value = parse_value(&rest[2..])?;
953            Ok(Command::SetRecordingParam {
954                recording,
955                param: RecordingParam::from_name(rest[1]),
956                value,
957            })
958        }
959        "storagevolume" | "storage-volume" => {
960            need_args(
961                rest,
962                4,
963                "set storagevolume <0..N> <wire-name> <kind> <value>",
964            )?;
965            let volume: u8 = rest[0]
966                .parse()
967                .map_err(|_| format!("storage volume index not numeric: {}", rest[0]))?;
968            let value = parse_value(&rest[2..])?;
969            Ok(Command::SetStorageVolumeParam {
970                volume,
971                param: StorageVolumeParam::from_name(rest[1]),
972                value,
973            })
974        }
975        "radiotx" | "radio-tx" => {
976            need_args(rest, 4, "set radiotx <0..N> <wire-name> <kind> <value>")?;
977            let tx: u8 = rest[0]
978                .parse()
979                .map_err(|_| format!("radio tx index not numeric: {}", rest[0]))?;
980            let value = parse_value(&rest[2..])?;
981            Ok(Command::SetRadioTxParam {
982                tx,
983                param: RadioTxParam::from_name(rest[1]),
984                value,
985            })
986        }
987        "radiorx" | "radio-rx" => {
988            need_args(rest, 4, "set radiorx <0..N> <wire-name> <kind> <value>")?;
989            let rx: u8 = rest[0]
990                .parse()
991                .map_err(|_| format!("radio rx index not numeric: {}", rest[0]))?;
992            let value = parse_value(&rest[2..])?;
993            Ok(Command::SetRadioRxParam {
994                rx,
995                param: RadioRxParam::from_name(rest[1]),
996                value,
997            })
998        }
999        "wifiscanresult" | "wifi-scan-result" => {
1000            need_args(
1001                rest,
1002                4,
1003                "set wifiscanresult <0..N> <wire-name> <kind> <value>",
1004            )?;
1005            let slot: u8 = rest[0]
1006                .parse()
1007                .map_err(|_| format!("wifi scan result slot index not numeric: {}", rest[0]))?;
1008            let value = parse_value(&rest[2..])?;
1009            Ok(Command::SetWifiScanResultParam {
1010                slot,
1011                param: WifiScanResultParam::from_name(rest[1]),
1012                value,
1013            })
1014        }
1015        "streamerxmixpreset" | "streamerx-mix-preset" => {
1016            need_args(
1017                rest,
1018                4,
1019                "set streamerxmixpreset <0..N> <wire-name> <kind> <value>",
1020            )?;
1021            let preset: u8 = rest[0]
1022                .parse()
1023                .map_err(|_| format!("streamerx mix preset index not numeric: {}", rest[0]))?;
1024            let value = parse_value(&rest[2..])?;
1025            Ok(Command::SetStreamerXMixPresetParam {
1026                preset,
1027                param: StreamerXMixPresetParam::from_name(rest[1]),
1028                value,
1029            })
1030        }
1031        "streamerxstreammix" | "streamerx-stream-mix" => {
1032            need_args(
1033                rest,
1034                4,
1035                "set streamerxstreammix <0..N> <wire-name> <kind> <value>",
1036            )?;
1037            let stream: u8 = rest[0]
1038                .parse()
1039                .map_err(|_| format!("streamerx stream mix index not numeric: {}", rest[0]))?;
1040            let value = parse_value(&rest[2..])?;
1041            Ok(Command::SetStreamerXStreamMixParam {
1042                stream,
1043                param: StreamerXStreamMixParam::from_name(rest[1]),
1044                value,
1045            })
1046        }
1047        "rcsyncmix" | "rcsync-mix" => {
1048            need_args(rest, 4, "set rcsyncmix <0..N> <wire-name> <kind> <value>")?;
1049            let mix: u8 = rest[0]
1050                .parse()
1051                .map_err(|_| format!("rcsync mix index not numeric: {}", rest[0]))?;
1052            let value = parse_value(&rest[2..])?;
1053            Ok(Command::SetRcSyncMixParam {
1054                mix,
1055                param: RcSyncMixParam::from_name(rest[1]),
1056                value,
1057            })
1058        }
1059        "mixminuses" | "mix-minuses" => {
1060            need_args(rest, 4, "set mixminuses <0..N> <wire-name> <kind> <value>")?;
1061            let minuses: u8 = rest[0]
1062                .parse()
1063                .map_err(|_| format!("mix minuses index not numeric: {}", rest[0]))?;
1064            let value = parse_value(&rest[2..])?;
1065            Ok(Command::SetMixMinusesParam {
1066                minuses,
1067                param: MixMinusesParam::from_name(rest[1]),
1068                value,
1069            })
1070        }
1071        other => Err(format!("unknown family: {other}")),
1072    }
1073}
1074
1075/// Parse `<kind> <value...>` into a [`Value`]. Kinds: int / i64 / bool / dbl / str.
1076fn parse_value(args: &[&str]) -> Result<Value, String> {
1077    if args.len() < 2 {
1078        return Err("value needs <kind> <value>; kinds: int i64 bool dbl str".into());
1079    }
1080    let kind = args[0].to_ascii_lowercase();
1081    let payload = args[1..].join(" ");
1082    match kind.as_str() {
1083        "int" => payload
1084            .parse::<i64>()
1085            .map(Value::Int)
1086            .map_err(|e| format!("int: {e}")),
1087        "i64" => payload
1088            .parse::<i64>()
1089            .map(Value::Int64)
1090            .map_err(|e| format!("i64: {e}")),
1091        "bool" => parse_bool(&payload).map(Value::Bool),
1092        "dbl" | "double" | "f64" => payload
1093            .parse::<f64>()
1094            .map(Value::Double)
1095            .map_err(|e| format!("dbl: {e}")),
1096        "str" | "string" => Ok(Value::String(payload)),
1097        other => Err(format!("unknown value kind: {other}")),
1098    }
1099}
1100
1101// ──────────────────────────────────────────────────────────────────────────
1102// Printers
1103// ──────────────────────────────────────────────────────────────────────────
1104
1105/// What to write into the `mixLinkRequest` / `mixUnlinkRequest` property for a
1106/// probe: used to deconstruct whether the press blob, the release blob, a
1107/// plain `Bool`, or any other shape is sufficient to flip a cell.
1108enum RawValue {
1109    /// Single Binary frame: `[01,01,02,01,01,02]`. The touchscreen's first frame.
1110    Press,
1111    /// Single Binary frame: `[01,01,03,01,01,03]`. The touchscreen's second frame.
1112    Release,
1113    /// Single Bool frame: the property's natural at-rest type per fullSync dumps.
1114    Bool(bool),
1115}
1116
1117/// `raw-press|raw-release|raw-bool <source> <mix> <link|unlink>`: send ONE
1118/// frame to `mixLinkRequest` (link) or `mixUnlinkRequest` (unlink) carrying
1119/// the chosen payload. No press/release pair, no enable/unmute, just the raw
1120/// property write. Probes whether the device gates a state change on the
1121/// payload type or the property name alone.
1122fn raw_request(
1123    writer: &Writer,
1124    layout: &Shared<Option<Layout>>,
1125    args: &[&str],
1126    raw: RawValue,
1127) -> Result<Outcome, String> {
1128    if args.len() < 3 {
1129        return Err("usage: raw-press|raw-release <source> <mix> <link|unlink> \
1130                    OR raw-bool <source> <mix> <link|unlink> <on|off>"
1131            .into());
1132    }
1133    let source = parse_source(args[0])?;
1134    let mix = parse_mix(args[1])?;
1135    let property = match args[2] {
1136        "link" => "mixLinkRequest",
1137        "unlink" => "mixUnlinkRequest",
1138        other => return Err(format!("expected link|unlink, got {other}")),
1139    };
1140    let value = match raw {
1141        RawValue::Press => Value::Binary(vec![0x01, 0x01, 0x02, 0x01, 0x01, 0x02]),
1142        RawValue::Release => Value::Binary(vec![0x01, 0x01, 0x03, 0x01, 0x01, 0x03]),
1143        RawValue::Bool(b) => Value::Bool(b),
1144    };
1145    let layout_guard = layout.lock().unwrap();
1146    let layout_ref = layout_guard
1147        .as_ref()
1148        .ok_or_else(|| "no Layout yet".to_string())?;
1149    let path = layout_ref
1150        .mix_cell_path(source.to_protocol(), mix.to_protocol())
1151        .ok_or_else(|| "bad cell".to_string())?;
1152    drop(layout_guard);
1153    let body = change_frame::encode_property_changed(&path, property, &value);
1154    writer(body).map_err(|e| format!("write: {e}"))?;
1155    println!("sent 1 frame: {property} = {value:?}");
1156    Ok(Outcome::Continue)
1157}
1158
1159/// `raw-write <PATH> <PROP_NAME> <KIND> <VALUE...>`: send a raw
1160/// propertyChanged frame with arbitrary path, property name, and value.
1161/// PATH is comma-separated `u32`s (e.g. `359,0`). KIND is one of `int`,
1162/// `i64`, `bool`, `dbl`, `str`. For `str`, the remainder of the line is the
1163/// string (allowing spaces). This is the fuzzing / probing primitive:
1164/// bypasses every typed `Command` and lets you write anything to anywhere.
1165fn raw_write(writer: &Writer, args: &[&str]) -> Result<Outcome, String> {
1166    if args.len() < 3 {
1167        return Err(
1168            "usage: raw-write <path,commas,between,u32s> <prop_name> <kind> [<value...>] \
1169             (value defaults to empty for str)"
1170                .into(),
1171        );
1172    }
1173    let path: Vec<u32> = args[0]
1174        .split(',')
1175        .map(|s| s.trim().parse::<u32>())
1176        .collect::<Result<_, _>>()
1177        .map_err(|e| format!("bad path (need comma-separated u32s): {e}"))?;
1178    let prop_name = args[1];
1179    let kind = args[2].to_ascii_lowercase();
1180    let payload = args.get(3..).map(|s| s.join(" ")).unwrap_or_default();
1181    let value = match kind.as_str() {
1182        "int" => Value::Int(payload.parse::<i64>().map_err(|e| format!("int: {e}"))?),
1183        "i64" => Value::Int64(payload.parse::<i64>().map_err(|e| format!("i64: {e}"))?),
1184        "bool" => Value::Bool(parse_bool(&payload)?),
1185        "dbl" | "f64" | "double" => {
1186            Value::Double(payload.parse::<f64>().map_err(|e| format!("dbl: {e}"))?)
1187        }
1188        "str" | "string" => Value::String(payload),
1189        other => return Err(format!("unknown kind: {other}")),
1190    };
1191    let body = change_frame::encode_property_changed(&path, prop_name, &value);
1192    writer(body).map_err(|e| format!("write: {e}"))?;
1193    println!("sent raw {prop_name} = {value:?} at path {path:?}");
1194    Ok(Outcome::Continue)
1195}
1196
1197/// `dump-node <NAME>`: find the first node in the cached fullSync tree whose
1198/// name matches, and print all its properties + values (with the current
1199/// wire types visible). Useful for reading singleton node state
1200/// (`NETWORK`, `SYSTEM`, `OUTPUT`, etc.) without waiting for a change event.
1201fn dump_node(root: &Shared<Option<Node>>, name: &str) -> Result<(), String> {
1202    let guard = root.lock().unwrap();
1203    let r = guard
1204        .as_ref()
1205        .ok_or_else(|| "no fullSync parsed yet".to_string())?;
1206    fn find<'a>(n: &'a Node, target: &str, path: &mut Vec<u32>) -> Option<(&'a Node, Vec<u32>)> {
1207        if n.name == target {
1208            return Some((n, path.clone()));
1209        }
1210        for (i, c) in n.children.iter().enumerate() {
1211            path.push(i as u32);
1212            if let Some(found) = find(c, target, path) {
1213                return Some(found);
1214            }
1215            path.pop();
1216        }
1217        None
1218    }
1219    let mut path = Vec::new();
1220    let (node, node_path) =
1221        find(r, name, &mut path).ok_or_else(|| format!("no node named {name}"))?;
1222    println!(
1223        "[node] <{}> at path {:?} ({} properties, {} children)",
1224        node.name,
1225        node_path,
1226        node.properties.len(),
1227        node.children.len()
1228    );
1229    for p in &node.properties {
1230        println!("  {} = {:?}", p.name, p.value);
1231    }
1232    Ok(())
1233}
1234
1235/// `dump-schema`: walk the cached fullSync tree and print every unique
1236/// `(node_name, property_name)` pair found. Used to enumerate the wire's
1237/// total property surface for completeness auditing.
1238fn dump_schema(root: &Shared<Option<Node>>) -> Result<(), String> {
1239    let guard = root.lock().unwrap();
1240    let r = guard
1241        .as_ref()
1242        .ok_or_else(|| "no fullSync parsed yet".to_string())?;
1243    let mut seen: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
1244        std::collections::BTreeMap::new();
1245    fn walk(
1246        n: &Node,
1247        seen: &mut std::collections::BTreeMap<String, std::collections::BTreeSet<String>>,
1248    ) {
1249        let entry = seen.entry(n.name.clone()).or_default();
1250        for p in &n.properties {
1251            entry.insert(p.name.clone());
1252        }
1253        for c in &n.children {
1254            walk(c, seen);
1255        }
1256    }
1257    walk(r, &mut seen);
1258    println!("[schema] {} unique node types", seen.len());
1259    for (node, props) in &seen {
1260        println!("  <{node}> ({} props)", props.len());
1261        for p in props {
1262            println!("    - {p}");
1263        }
1264    }
1265    Ok(())
1266}
1267
1268/// `dump-cell <source> <mix>`: find the MIX node for that (source, mix) cell
1269/// in the cached parsed root and print all of its properties + values, raw.
1270/// No interpretation, no decode. Lets you see what `mixLinkRequest` and friends
1271/// actually look like at rest, and how they differ across cells.
1272fn dump_cell(
1273    layout: &Shared<Option<Layout>>,
1274    root: &Shared<Option<Node>>,
1275    args: &[&str],
1276) -> Result<(), String> {
1277    if args.len() < 2 {
1278        return Err("usage: dump-cell <source> <mix>".into());
1279    }
1280    let source = parse_source(args[0])?;
1281    let mix = parse_mix(args[1])?;
1282
1283    let layout_guard = layout.lock().unwrap();
1284    let l = layout_guard
1285        .as_ref()
1286        .ok_or_else(|| "no Layout yet; wait for the fullSync".to_string())?;
1287    let root_guard = root.lock().unwrap();
1288    let r = root_guard
1289        .as_ref()
1290        .ok_or_else(|| "no fullSync parsed yet".to_string())?;
1291
1292    let s_idx = source.to_protocol();
1293    let m_idx = mix.to_protocol();
1294    let per_source = l.mix_count_per_source() as u32;
1295    let target = s_idx as u32 * per_source + m_idx as u32;
1296
1297    let mut counter: u32 = 0;
1298    for child in &r.children {
1299        if child.name != "MIX" {
1300            continue;
1301        }
1302        if counter == target {
1303            println!("[cell] source={source:?} mix={mix:?} root_idx_offset={counter}");
1304            for p in &child.properties {
1305                println!("  {} = {:?}", p.name, p.value);
1306            }
1307            return Ok(());
1308        }
1309        counter += 1;
1310    }
1311    Err(format!(
1312        "cell not found (offset {target}, found {counter} MIX nodes)"
1313    ))
1314}
1315
1316fn print_layout(layout: &Shared<Option<Layout>>) {
1317    match layout.lock().unwrap().as_ref() {
1318        None => println!("no layout yet"),
1319        Some(l) => {
1320            println!("model:               {}", model_label(l.model()));
1321            println!("fader count:         {}", l.fader_count());
1322            println!("channel first:       {}", l.first_channel());
1323            println!("channel count:       {}", l.channel_count());
1324            println!("source count:        {}", l.source_count());
1325            println!("mix per source:      {}", l.mix_count_per_source());
1326            println!("master channel:      {:?}", l.master_channel());
1327            println!("output:              {:?}", l.output());
1328            println!("ducker:              {:?}", l.ducker());
1329            println!("recorder:            {:?}", l.recorder());
1330            println!("player:              {:?}", l.player());
1331            println!(
1332                "headphones:          first={:?} count={}",
1333                l.first_headphone(),
1334                l.headphone_count()
1335            );
1336            println!(
1337                "effects:             first={:?} count={}",
1338                l.first_effects(),
1339                l.effects_count()
1340            );
1341            println!("gui:                 {:?}", l.gui());
1342            println!("soundpads:           {:?}", l.soundpads());
1343            println!(
1344                "pads:                first={} count={}",
1345                l.first_pad(),
1346                l.pad_count()
1347            );
1348        }
1349    }
1350}
1351
1352fn print_help() {
1353    println!(
1354        "\
1355commands:
1356  help                                       show this
1357  quit | exit                                disconnect
1358
1359  layout                                     print discovered Layout
1360  watch <on|off>                             toggle live event printing
1361
1362  mute     <fader>            <on|off>       SetFaderMute
1363  cue      <fader>            <on|off>       SetFaderCue
1364  level    <fader>            <0..127>       SetFaderLevel (virtual faders)
1365  assign   <fader>            <source|clear> AssignFaderSource
1366
1367  mix-disable <source> <mix>  <on|off>       SetMixDisabled
1368  mix-mute    <source> <mix>  <on|off>       SetMixMute
1369  link        <source> <mix>                 LinkMix    (enable+unmute+pulse)
1370  unlink      <source> <mix>                 UnlinkMix
1371  link-callme   <callme1..3> <mix>           LinkCallMe (single legacy blob)
1372  unlink-callme <callme1..3> <mix>           UnlinkCallMe
1373
1374  screen                                     ScreenTouched (wake display)
1375  power                                      PowerOff (asks for 'yes')
1376
1377  set master      <name> <kind> <value>      SetMasterParam
1378  set output      <name> <kind> <value>      SetOutputParam
1379  set ducker      <name> <kind> <value>      SetDuckerParam
1380  set recorder    <name> <kind> <value>      SetRecorderParam
1381  set player      <name> <kind> <value>      SetPlayerParam
1382  set gui         <name> <kind> <value>      SetGuiParam
1383  set system      <name> <kind> <value>      SetSystemParam
1384  set channel     <fader>  <name> <kind> <v> SetChannelParam
1385  set inputsource <source> <name> <kind> <v> SetInputSourceParam
1386  set headphone   <0..N>   <name> <kind> <v> SetHeadphoneParam
1387  set effects     <0..N>   <name> <kind> <v> SetEffectsParam
1388  set pad         <0..N>   <name> <kind> <v> SetPadParam
1389
1390specs:
1391  fader  : p1..p6 / v1..v5
1392  source : combo1..4, combo1_2, combo2_3, combo3_4, usb1, chat, usb2,
1393           bt, pad, vgame, vmusic, va, vb, callme1..callme3
1394  mix    : hp1..hp4, spk, rec, bt, usb1, chat, usb2, callme1..callme3
1395  kind   : int <i32> | i64 <i64> | bool <on|off> | dbl <f64> | str <rest of line>"
1396    );
1397}