Skip to main content

rodecaster_protocol/
commands.rs

1//! Typed command builders for controlling RØDECaster functions.
2//!
3//! [`Command`] represents actions sent from your application to the device:
4//!
5//! - **Faders & Channels**: Mute, solo/cue, volume level, strip assignment, and color.
6//! - **Routing Matrix**: Connecting or disconnecting sources to mix outputs, custom sub-mixes.
7//! - **Pads & Sounds**: Triggering SMART pads and sound playback.
8//! - **Audio Processing**: EQ, compressor, high-pass filter, de-esser, and noise gate.
9//! - **Monitoring**: Headphone volume levels and master output settings.
10//!
11//! # Encoding Commands
12//!
13//! You typically encode commands through [`crate::ProtocolSession::encode`], which
14//! automatically formats the command using the active layout:
15//!
16//! ```rust
17//! use rodecaster_protocol::{Command, Fader, ProtocolSession};
18//!
19//! # fn example(session: &ProtocolSession) -> Result<(), Box<dyn std::error::Error>> {
20//! let cmd = Command::SetFaderMute {
21//!     fader: Fader::Physical1,
22//!     mute: true,
23//! };
24//! let payloads = session.encode(&cmd)?;
25//! # Ok(())
26//! # }
27//! ```
28
29use crate::change_frame;
30use crate::juce_var::Value;
31use crate::layout::Layout;
32use crate::names::{
33    AppParam, AudioParam, BuildParam, ChannelParam, CurrentShowParam, DeviceModel, DuckerParam,
34    EffectsParam, Fader, FxPresetParam, GuiParam, HeadphoneParam, InputSourceParam, MasterParam,
35    MixMinusesParam, MixOutput, NetworkParam, OutputParam, PadParam, PadRecorderParam, PlayerParam,
36    RadioParam, RadioRxParam, RadioTxParam, RcSyncMixParam, RecorderParam, RecordingParam,
37    RecordingsParam, ShowControlParam, ShowParam, SipAdvancedParam, SipCallSlotsParam,
38    SipCallingParam, SipRegistrationParam, Source, StorageVolumeParam, StreamerXMixPresetParam,
39    StreamerXStreamMixParam, SystemParam, TestParam, ThemeParam, WifiScanResultParam,
40};
41
42/// Canonical trigger payload alias for backward compatibility in tests.
43#[cfg(test)]
44const MIX_LINK_TRIGGER: [u8; 6] = crate::trigger::PRESS_BYTES;
45
46/// JUCE `Int` value representing unassigned for `channelInputSource`.
47const CHANNEL_INPUT_SOURCE_UNASSIGNED: i64 = -1;
48
49/// Verbatim wire bytes for the screen-wake message ([`Command::ScreenTouched`]).
50///
51/// Anatomy: PropertyChanged changeType (0x01), path depth 1 (0x01, 0x01),
52/// child node 1 prefix (0x01), followed by null-terminated "screenTouched\0".
53/// Emitted verbatim by RØDE Central to wake the touchscreen display on node index 1.
54const SCREEN_TOUCHED_FRAME: [u8; 18] = [
55    0x01, 0x01, 0x01, 0x01, b's', b'c', b'r', b'e', b'e', b'n', b'T', b'o', b'u', b'c', b'h', b'e',
56    b'd', 0x00,
57];
58
59/// Mix offset index for CallMe return channel routing requests.
60///
61/// Used in `(source << 8) | (CALLME_MIX_PATH_OFFSET + mix)` to address
62/// external SIP/CallMe return channels outside the primary mix matrix.
63const CALLME_MIX_PATH_OFFSET: u32 = 4;
64
65#[inline]
66fn single_prop_frame(path: &[u32], name: &str, value: &Value) -> Vec<Vec<u8>> {
67    vec![change_frame::encode_property_changed(path, name, value)]
68}
69
70#[inline]
71fn trigger_frame(path: &[u32], name: &str) -> Vec<Vec<u8>> {
72    single_prop_frame(path, name, &crate::trigger::press_value())
73}
74
75macro_rules! encode_singleton {
76    ($layout:expr, $getter:ident, $what:literal, $param:expr, $val:expr) => {{
77        let path = $layout
78            .$getter()
79            .ok_or(EncodeError::MissingNode { what: $what })?;
80        Ok(single_prop_frame(&path, $param.as_str(), $val))
81    }};
82}
83
84macro_rules! encode_indexed {
85    ($layout:expr, $getter:ident, $idx:expr, $what:literal, $param:expr, $val:expr) => {{
86        let path = $layout
87            .$getter($idx)
88            .ok_or(EncodeError::MissingNode { what: $what })?;
89        Ok(single_prop_frame(&path, $param.as_str(), $val))
90    }};
91}
92
93/// An outgoing command sent to a RØDECaster console.
94///
95/// Variants use high-level domain types ([`Fader`], [`Source`], [`MixOutput`])
96/// which are dynamically translated into the device's internal wire addresses
97/// when encoded.
98#[derive(Debug, Clone, PartialEq)]
99#[non_exhaustive]
100pub enum Command {
101    /// Set the output mute on a fader strip.
102    SetFaderMute { fader: Fader, mute: bool },
103    /// Set the cue (pre-fader-listen) enable on a fader strip.
104    SetFaderCue { fader: Fader, enable: bool },
105    /// Set a virtual fader's level (0..127 MIDI scale).
106    /// Physical fader levels come from hardware over MIDI/UART, not this path.
107    SetFaderLevel { fader: Fader, level: u8 },
108    /// Assign (or clear, with `None`) the input source for a fader strip.
109    AssignFaderSource {
110        fader: Fader,
111        source: Option<Source>,
112    },
113    /// Enable or disable a routing matrix cell.
114    SetMixDisabled {
115        source: Source,
116        mix: MixOutput,
117        disabled: bool,
118    },
119    /// Mute or unmute a routing matrix cell. This is the per-cell `mixMute`,
120    /// distinct from the per-strip [`Command::SetFaderMute`]. The device clears
121    /// it as part of a native link; exposed on its own so callers can compose.
122    SetMixMute {
123        source: Source,
124        mix: MixOutput,
125        mute: bool,
126    },
127    /// Link a routing matrix cell with the device-validated minimal sequence:
128    /// enable (`mixDisabled=false`), unmute (`mixMute=false`), then a single
129    /// `Binary` trigger write to `mixLinkRequest`. `encode` returns three
130    /// frames in order. The atomic halves are also callable on their own as
131    /// [`Command::SetMixDisabled`] and [`Command::SetMixMute`]; a press on
132    /// `mixLinkRequest` alone does NOT auto-clear `mixDisabled` or `mixMute`.
133    LinkMix { source: Source, mix: MixOutput },
134    /// Unlink a routing matrix cell with a single `Binary` trigger write to
135    /// `mixUnlinkRequest`. `mixDisabled` and `mixMute` retain their prior
136    /// values (the unlink does not re-disable or re-mute the cell).
137    UnlinkMix { source: Source, mix: MixOutput },
138    /// Set a routing matrix cell's sub-mix send level and tracking value.
139    ///
140    /// Encodes `mixLevelWithAnchor` on the matrix cell's path as `"anchor|value"`.
141    /// In broadcast mixing terminology, `anchor` represents the custom sub-mix
142    /// send level (active when the cell is unlinked), and `value` represents
143    /// the post-fader program level.
144    SetMixLevel {
145        source: Source,
146        mix: MixOutput,
147        anchor: f32,
148        value: f32,
149    },
150    /// Wake the device display. A fixed, layout-independent message; see
151    /// `SCREEN_TOUCHED_FRAME`.
152    ScreenTouched,
153    /// Request the device power off.
154    PowerOff,
155    /// Link a CallMe return channel into a mix. `source` must be a CallMe
156    /// source ([`Source::CallMe1`]..=[`Source::CallMe3`]); on firmware where
157    /// CallMe sits outside the mix matrix it is addressed by a dedicated
158    /// request path, so this sends a single legacy `mixLinkRequest` blob (no
159    /// enable/unmute or press/release pulse, unlike [`Command::LinkMix`]).
160    LinkCallMe { source: Source, mix: MixOutput },
161    /// Unlink a CallMe return channel from a mix. See [`Command::LinkCallMe`].
162    UnlinkCallMe { source: Source, mix: MixOutput },
163    /// Set a channel-strip DSP parameter on a fader's CHANNEL node.
164    SetChannelParam {
165        fader: Fader,
166        param: ChannelParam,
167        value: Value,
168    },
169    /// Set an input-source parameter on a source's INPUTSOURCE node.
170    SetInputSourceParam {
171        source: Source,
172        param: InputSourceParam,
173        value: Value,
174    },
175    /// Set a master-bus parameter on the MASTERCHANNEL node.
176    SetMasterParam { param: MasterParam, value: Value },
177    /// Set an output-bus parameter on the OUTPUT node.
178    SetOutputParam { param: OutputParam, value: Value },
179    /// Set the auto-duck depth on the DUCKER node.
180    SetDuckerParam { param: DuckerParam, value: Value },
181    /// Set a recorder transport property on the RECORDER node.
182    SetRecorderParam { param: RecorderParam, value: Value },
183    /// Set a player property on the PLAYER node.
184    SetPlayerParam { param: PlayerParam, value: Value },
185    /// Set a headphone property on a HEADPHONE node.
186    SetHeadphoneParam {
187        headphone: u8,
188        param: HeadphoneParam,
189        value: Value,
190    },
191    /// Set an effects parameter on an EFFECTS_PARAMETERS node.
192    SetEffectsParam {
193        effects: u8,
194        param: EffectsParam,
195        value: Value,
196    },
197    /// Set a front-panel UI parameter on the GUI node.
198    SetGuiParam { param: GuiParam, value: Value },
199    /// Set a sound-pad parameter on a PAD node.
200    SetPadParam {
201        pad: u8,
202        param: PadParam,
203        value: Value,
204    },
205    /// Set a device-wide system parameter on the SYSTEM node.
206    SetSystemParam { param: SystemParam, value: Value },
207    /// Set a SIP calling parameter on the SIPCALLING node.
208    SetSipCallingParam {
209        param: SipCallingParam,
210        value: Value,
211    },
212    /// Set a per-registration SIP parameter on a SIPREGISTRATION node.
213    SetSipRegistrationParam {
214        registration: u8,
215        param: SipRegistrationParam,
216        value: Value,
217    },
218    /// Set a per-call-slot SIP parameter on a SIPCALLSLOTS node.
219    SetSipCallSlotsParam {
220        slot: u8,
221        param: SipCallSlotsParam,
222        value: Value,
223    },
224    /// Set a SIP advanced parameter on the SIPADVANCED node.
225    SetSipAdvancedParam {
226        param: SipAdvancedParam,
227        value: Value,
228    },
229    /// Set a diagnostic parameter on the TEST node.
230    SetTestParam { param: TestParam, value: Value },
231    /// Set a pad recorder parameter on a PADRECORDER node.
232    SetPadRecorderParam {
233        pad_recorder: u8,
234        param: PadRecorderParam,
235        value: Value,
236    },
237    /// Set an effects preset parameter on an FXPRESET node.
238    SetFxPresetParam {
239        preset: u8,
240        param: FxPresetParam,
241        value: Value,
242    },
243    /// Set a networking parameter on the singleton `NETWORK` node.
244    SetNetworkParam { param: NetworkParam, value: Value },
245    /// Set an audio engine parameter on the singleton `AUDIO` node.
246    SetAudioParam { param: AudioParam, value: Value },
247    /// Set a build parameter on the singleton `BUILD` node.
248    SetBuildParam { param: BuildParam, value: Value },
249    /// Set a companion-app parameter on the singleton `APP` node.
250    SetAppParam { param: AppParam, value: Value },
251    /// Set a theme parameter on the singleton `THEME` node.
252    SetThemeParam { param: ThemeParam, value: Value },
253    /// Set a current-show parameter on the singleton `CURRENTSHOW` node.
254    SetCurrentShowParam {
255        param: CurrentShowParam,
256        value: Value,
257    },
258    /// Set a show-control parameter on the singleton `SHOWCONTROL` node.
259    SetShowControlParam {
260        param: ShowControlParam,
261        value: Value,
262    },
263    /// Set a recordings-container parameter on the singleton `RECORDINGS` node.
264    SetRecordingsParam {
265        param: RecordingsParam,
266        value: Value,
267    },
268    /// Set a wireless-radio parameter on the singleton `RADIO` node.
269    SetRadioParam { param: RadioParam, value: Value },
270    /// Set a per-show parameter on one of the `SHOW` child nodes under `SHOWS`.
271    SetShowParam {
272        show: u8,
273        param: ShowParam,
274        value: Value,
275    },
276    /// Set a per-recording parameter on one of the `RECORDING` child nodes under `RECORDINGS`.
277    SetRecordingParam {
278        recording: u8,
279        param: RecordingParam,
280        value: Value,
281    },
282    /// Set a storage volume parameter on one of the `STORAGEVOLUME` nodes.
283    SetStorageVolumeParam {
284        volume: u8,
285        param: StorageVolumeParam,
286        value: Value,
287    },
288    /// Set a wireless-radio transmitter parameter on one of the `RADIOTX` nodes.
289    SetRadioTxParam {
290        tx: u8,
291        param: RadioTxParam,
292        value: Value,
293    },
294    /// Set a wireless-radio receiver parameter on one of the `RADIORX` nodes.
295    SetRadioRxParam {
296        rx: u8,
297        param: RadioRxParam,
298        value: Value,
299    },
300    /// Set a WiFi scan result entry parameter on one of the `WIFISCANRESULT` nodes.
301    SetWifiScanResultParam {
302        slot: u8,
303        param: WifiScanResultParam,
304        value: Value,
305    },
306    /// Set a StreamerX mix preset parameter on one of the `STREAMERXMIXPRESET` nodes.
307    SetStreamerXMixPresetParam {
308        preset: u8,
309        param: StreamerXMixPresetParam,
310        value: Value,
311    },
312    /// Set a StreamerX stream mix parameter on one of the `STREAMERXSTREAMMIX` nodes.
313    SetStreamerXStreamMixParam {
314        stream: u8,
315        param: StreamerXStreamMixParam,
316        value: Value,
317    },
318    /// Set an rcSync mix parameter on one of the `RCSYNCMIX` nodes.
319    SetRcSyncMixParam {
320        mix: u8,
321        param: RcSyncMixParam,
322        value: Value,
323    },
324    /// Set a mix-minus parameter on one of the `MIXMINUSES` nodes.
325    SetMixMinusesParam {
326        minuses: u8,
327        param: MixMinusesParam,
328        value: Value,
329    },
330    /// Skip initial setup mode and configure language and timezone.
331    SetupSkip {
332        language: Option<String>,
333        timezone: Option<String>,
334    },
335}
336
337impl Command {
338    /// Encode this command into one or more change-frame payloads to send in
339    /// order. `Err(EncodeError::OutOfRange)` if the addressed entity does not
340    /// exist in the layout (e.g., fader index past `Layout::fader_count`).
341    ///
342    /// Wrap each payload in a [`crate::frame::Packet`] for the transport.
343    pub fn encode(&self, layout: &Layout) -> Result<Vec<Vec<u8>>, EncodeError> {
344        match self {
345            Command::SetFaderMute { fader, mute } => {
346                let path = channel_path(layout, fader_index(layout, *fader)?)?;
347                Ok(vec![change_frame::encode_property_changed(
348                    &path,
349                    "channelOutputMute",
350                    &Value::Bool(*mute),
351                )])
352            }
353            Command::SetFaderCue { fader, enable } => {
354                let path = channel_path(layout, fader_index(layout, *fader)?)?;
355                Ok(vec![change_frame::encode_property_changed(
356                    &path,
357                    "channelCueEnable",
358                    &Value::Bool(*enable),
359                )])
360            }
361            Command::SetFaderLevel { fader, level } => {
362                let path = fader_path(layout, fader_index(layout, *fader)?)?;
363                Ok(vec![change_frame::encode_property_changed(
364                    &path,
365                    "faderLevel",
366                    &Value::Int(*level as i64),
367                )])
368            }
369            Command::AssignFaderSource { fader, source } => {
370                let path = channel_path(layout, fader_index(layout, *fader)?)?;
371                let source_value = source
372                    .map(|s| s.to_protocol() as i64)
373                    .unwrap_or(CHANNEL_INPUT_SOURCE_UNASSIGNED);
374                Ok(vec![change_frame::encode_property_changed(
375                    &path,
376                    "channelInputSource",
377                    &Value::Int(source_value),
378                )])
379            }
380            Command::SetMixDisabled {
381                source,
382                mix,
383                disabled,
384            } => {
385                let path = mix_path(layout, *source, *mix)?;
386                Ok(vec![change_frame::encode_property_changed(
387                    &path,
388                    "mixDisabled",
389                    &Value::Bool(*disabled),
390                )])
391            }
392            Command::SetMixMute { source, mix, mute } => {
393                let path = mix_path(layout, *source, *mix)?;
394                Ok(vec![change_frame::encode_property_changed(
395                    &path,
396                    "mixMute",
397                    &Value::Bool(*mute),
398                )])
399            }
400            Command::LinkMix { source, mix } => {
401                let path = mix_path(layout, *source, *mix)?;
402                // Link sequence: enable (mixDisabled = false), unmute (mixMute = false),
403                // then emit the mixLinkRequest trigger pulse.
404                Ok(vec![
405                    change_frame::encode_property_changed(
406                        &path,
407                        "mixDisabled",
408                        &Value::Bool(false),
409                    ),
410                    change_frame::encode_property_changed(&path, "mixMute", &Value::Bool(false)),
411                    change_frame::encode_property_changed(
412                        &path,
413                        "mixLinkRequest",
414                        &crate::trigger::press_value(),
415                    ),
416                ])
417            }
418            Command::UnlinkMix { source, mix } => {
419                let path = mix_path(layout, *source, *mix)?;
420                Ok(trigger_frame(&path, "mixUnlinkRequest"))
421            }
422            Command::SetMixLevel {
423                source,
424                mix,
425                anchor,
426                value,
427            } => {
428                let path = mix_path(layout, *source, *mix)?;
429                let formatted = format!("{:.1}|{:.1}", anchor, value);
430                Ok(single_prop_frame(
431                    &path,
432                    "mixLevelWithAnchor",
433                    &Value::String(formatted),
434                ))
435            }
436            Command::ScreenTouched => Ok(vec![SCREEN_TOUCHED_FRAME.to_vec()]),
437            Command::PowerOff => {
438                let path = layout
439                    .system_path()
440                    .ok_or(EncodeError::MissingNode { what: "SYSTEM" })?;
441                Ok(single_prop_frame(
442                    &path,
443                    "powerOffRequest",
444                    &Value::Bool(true),
445                ))
446            }
447            Command::LinkCallMe { source, mix } => Ok(trigger_frame(
448                &callme_request_path(*source, *mix),
449                "mixLinkRequest",
450            )),
451            Command::UnlinkCallMe { source, mix } => Ok(trigger_frame(
452                &callme_request_path(*source, *mix),
453                "mixUnlinkRequest",
454            )),
455            Command::SetChannelParam {
456                fader,
457                param,
458                value,
459            } => {
460                let path = channel_path(layout, fader_index(layout, *fader)?)?;
461                Ok(single_prop_frame(&path, param.as_str(), value))
462            }
463            Command::SetInputSourceParam {
464                source,
465                param,
466                value,
467            } => {
468                let path = input_source_path(layout, *source)?;
469                Ok(single_prop_frame(&path, param.as_str(), value))
470            }
471            Command::SetMasterParam { param, value } => {
472                encode_singleton!(layout, master_channel_path, "MASTERCHANNEL", param, value)
473            }
474            Command::SetOutputParam { param, value } => {
475                encode_singleton!(layout, output_path, "OUTPUT", param, value)
476            }
477            Command::SetDuckerParam { param, value } => {
478                encode_singleton!(layout, ducker_path, "DUCKER", param, value)
479            }
480            Command::SetRecorderParam { param, value } => {
481                encode_singleton!(layout, recorder_path, "RECORDER", param, value)
482            }
483            Command::SetPlayerParam { param, value } => {
484                encode_singleton!(layout, player_path, "PLAYER", param, value)
485            }
486            Command::SetHeadphoneParam {
487                headphone,
488                param,
489                value,
490            } => {
491                let path = headphone_path(layout, *headphone)?;
492                Ok(single_prop_frame(&path, param.as_str(), value))
493            }
494            Command::SetEffectsParam {
495                effects,
496                param,
497                value,
498            } => {
499                let path = effects_path(layout, *effects)?;
500                Ok(single_prop_frame(&path, param.as_str(), value))
501            }
502            Command::SetGuiParam { param, value } => {
503                encode_singleton!(layout, gui_path, "GUI", param, value)
504            }
505            Command::SetPadParam { pad, param, value } => {
506                let path = pad_path(layout, *pad)?;
507                Ok(single_prop_frame(&path, param.as_str(), value))
508            }
509            Command::SetSystemParam { param, value } => {
510                encode_singleton!(layout, system_path, "SYSTEM", param, value)
511            }
512            Command::SetSipCallingParam { param, value } => {
513                encode_singleton!(layout, sip_calling_path, "SIPCALLING", param, value)
514            }
515            Command::SetSipAdvancedParam { param, value } => {
516                encode_singleton!(layout, sip_advanced_path, "SIPADVANCED", param, value)
517            }
518            Command::SetSipRegistrationParam {
519                registration,
520                param,
521                value,
522            } => {
523                encode_indexed!(
524                    layout,
525                    sip_registration_path,
526                    *registration,
527                    "SIPREGISTRATION",
528                    param,
529                    value
530                )
531            }
532            Command::SetSipCallSlotsParam { slot, param, value } => {
533                encode_indexed!(
534                    layout,
535                    sip_call_slots_path,
536                    *slot,
537                    "SIPCALLSLOTS",
538                    param,
539                    value
540                )
541            }
542            Command::SetTestParam { param, value } => {
543                encode_singleton!(layout, test_path, "TEST", param, value)
544            }
545            Command::SetPadRecorderParam {
546                pad_recorder,
547                param,
548                value,
549            } => {
550                encode_indexed!(
551                    layout,
552                    pad_recorder_path,
553                    *pad_recorder,
554                    "PADRECORDER",
555                    param,
556                    value
557                )
558            }
559            Command::SetFxPresetParam {
560                preset,
561                param,
562                value,
563            } => {
564                encode_indexed!(layout, fx_preset_path, *preset, "FXPRESET", param, value)
565            }
566            Command::SetNetworkParam { param, value } => {
567                encode_singleton!(layout, network_path, "NETWORK", param, value)
568            }
569            Command::SetAudioParam { param, value } => {
570                encode_singleton!(layout, audio_path, "AUDIO", param, value)
571            }
572            Command::SetBuildParam { param, value } => {
573                encode_singleton!(layout, build_path, "BUILD", param, value)
574            }
575            Command::SetAppParam { param, value } => {
576                encode_singleton!(layout, app_path, "APP", param, value)
577            }
578            Command::SetThemeParam { param, value } => {
579                encode_singleton!(layout, theme_path, "THEME", param, value)
580            }
581            Command::SetCurrentShowParam { param, value } => {
582                encode_singleton!(layout, current_show_path, "CURRENTSHOW", param, value)
583            }
584            Command::SetShowControlParam { param, value } => {
585                encode_singleton!(layout, show_control_path, "SHOWCONTROL", param, value)
586            }
587            Command::SetRecordingsParam { param, value } => {
588                encode_singleton!(layout, recordings_path, "RECORDINGS", param, value)
589            }
590            Command::SetRadioParam { param, value } => {
591                encode_singleton!(layout, radio_path, "RADIO", param, value)
592            }
593            Command::SetShowParam { show, param, value } => {
594                encode_indexed!(layout, show_path, *show, "SHOW", param, value)
595            }
596            Command::SetRecordingParam {
597                recording,
598                param,
599                value,
600            } => {
601                encode_indexed!(
602                    layout,
603                    recording_path,
604                    *recording,
605                    "RECORDING",
606                    param,
607                    value
608                )
609            }
610            Command::SetStorageVolumeParam {
611                volume,
612                param,
613                value,
614            } => {
615                encode_indexed!(
616                    layout,
617                    storage_volume_path,
618                    *volume,
619                    "STORAGEVOLUME",
620                    param,
621                    value
622                )
623            }
624            Command::SetRadioTxParam { tx, param, value } => {
625                encode_indexed!(layout, radio_tx_path, *tx, "RADIOTX", param, value)
626            }
627            Command::SetRadioRxParam { rx, param, value } => {
628                encode_indexed!(layout, radio_rx_path, *rx, "RADIORX", param, value)
629            }
630            Command::SetWifiScanResultParam { slot, param, value } => {
631                encode_indexed!(
632                    layout,
633                    wifi_scan_result_path,
634                    *slot,
635                    "WIFISCANRESULT",
636                    param,
637                    value
638                )
639            }
640            Command::SetStreamerXMixPresetParam {
641                preset,
642                param,
643                value,
644            } => {
645                encode_indexed!(
646                    layout,
647                    streamerx_mix_preset_path,
648                    *preset,
649                    "STREAMERXMIXPRESET",
650                    param,
651                    value
652                )
653            }
654            Command::SetStreamerXStreamMixParam {
655                stream,
656                param,
657                value,
658            } => {
659                encode_indexed!(
660                    layout,
661                    streamerx_stream_mix_path,
662                    *stream,
663                    "STREAMERXSTREAMMIX",
664                    param,
665                    value
666                )
667            }
668            Command::SetRcSyncMixParam { mix, param, value } => {
669                encode_indexed!(layout, rcsync_mix_path, *mix, "RCSYNCMIX", param, value)
670            }
671            Command::SetMixMinusesParam {
672                minuses,
673                param,
674                value,
675            } => {
676                encode_indexed!(
677                    layout,
678                    mix_minuses_path,
679                    *minuses,
680                    "MIXMINUSES",
681                    param,
682                    value
683                )
684            }
685            Command::SetupSkip { language, timezone } => {
686                let mut frames = Vec::new();
687                if let Some(lang) = language {
688                    if let Some(path) = layout.gui_path() {
689                        frames.push(change_frame::encode_property_changed(
690                            &path,
691                            "lang",
692                            &Value::String(lang.clone()),
693                        ));
694                    }
695                }
696                if let Some(tz) = timezone {
697                    if let Some(path) = layout.system_path() {
698                        frames.push(change_frame::encode_property_changed(
699                            &path,
700                            "systemDateTimezone",
701                            &Value::String(tz.clone()),
702                        ));
703                        frames.push(change_frame::encode_property_changed(
704                            &path,
705                            "systemDateTime24h",
706                            &Value::Bool(true),
707                        ));
708                        frames.push(change_frame::encode_property_changed(
709                            &path,
710                            "systemDateTimeOnHome",
711                            &Value::Bool(true),
712                        ));
713                    }
714                }
715                if let Some(path) = layout.show_control_path() {
716                    frames.push(change_frame::encode_property_changed(
717                        &path,
718                        "showControlNewFromDefaultMuted",
719                        &Value::Bool(true),
720                    ));
721                }
722                if let Some(path) = layout.system_path() {
723                    frames.push(change_frame::encode_property_changed(
724                        &path,
725                        "disableAllPhysicalButtons",
726                        &Value::Bool(false),
727                    ));
728                    frames.push(change_frame::encode_property_changed(
729                        &path,
730                        "disableAllLineoutOutputs",
731                        &Value::Bool(false),
732                    ));
733                    frames.push(change_frame::encode_property_changed(
734                        &path,
735                        "disableAllHeadphoneOutputs",
736                        &Value::Bool(false),
737                    ));
738                    frames.push(change_frame::encode_property_changed(
739                        &path,
740                        "systemChannelSelected",
741                        &Value::Int(-1),
742                    ));
743                }
744                Ok(frames)
745            }
746        }
747    }
748}
749
750/// Resolve a named fader strip to its wire fader/channel index on the layout's
751/// device model. `Err(FaderNotOnModel)` if the strip does not exist there
752/// (e.g. `Physical6` on a Duo).
753fn fader_index(layout: &Layout, fader: Fader) -> Result<u8, EncodeError> {
754    fader
755        .to_index(layout.model())
756        .ok_or(EncodeError::FaderNotOnModel {
757            fader,
758            model: layout.model(),
759        })
760}
761
762/// Single-level request path for a CallMe routing cell. See
763/// [`CALLME_MIX_PATH_OFFSET`].
764fn callme_request_path(source: Source, mix: MixOutput) -> Vec<u32> {
765    vec![((source.to_protocol() as u32) << 8) | (CALLME_MIX_PATH_OFFSET + mix.to_protocol() as u32)]
766}
767
768fn channel_path(layout: &Layout, idx: u8) -> Result<Vec<u32>, EncodeError> {
769    layout.channel_path(idx).ok_or(EncodeError::OutOfRange {
770        what: "fader",
771        index: idx as u32,
772        bound: layout.channel_count() as u32,
773    })
774}
775
776fn input_source_path(layout: &Layout, source: Source) -> Result<Vec<u32>, EncodeError> {
777    let idx = source.to_protocol();
778    layout
779        .input_source_path(idx)
780        .ok_or(EncodeError::OutOfRange {
781            what: "input source",
782            index: idx as u32,
783            bound: layout.input_source_count() as u32,
784        })
785}
786
787fn fader_path(layout: &Layout, idx: u8) -> Result<Vec<u32>, EncodeError> {
788    layout.fader_path(idx).ok_or(EncodeError::OutOfRange {
789        what: "fader",
790        index: idx as u32,
791        bound: layout.fader_count() as u32,
792    })
793}
794
795fn headphone_path(layout: &Layout, idx: u8) -> Result<Vec<u32>, EncodeError> {
796    layout.headphone_path(idx).ok_or(EncodeError::OutOfRange {
797        what: "headphone",
798        index: idx as u32,
799        bound: layout.headphone_count() as u32,
800    })
801}
802
803fn effects_path(layout: &Layout, idx: u8) -> Result<Vec<u32>, EncodeError> {
804    layout.effects_path(idx).ok_or(EncodeError::OutOfRange {
805        what: "effects",
806        index: idx as u32,
807        bound: layout.effects_count() as u32,
808    })
809}
810
811fn pad_path(layout: &Layout, idx: u8) -> Result<Vec<u32>, EncodeError> {
812    layout.pad_path(idx).ok_or(EncodeError::OutOfRange {
813        what: "pad",
814        index: idx as u32,
815        bound: layout.pad_count() as u32,
816    })
817}
818
819fn mix_path(layout: &Layout, source: Source, mix: MixOutput) -> Result<Vec<u32>, EncodeError> {
820    layout
821        .mix_cell_path(source.to_protocol(), mix.to_protocol())
822        .ok_or(EncodeError::MixCellOutOfRange {
823            source: source.to_protocol(),
824            mix: mix.to_protocol(),
825            source_bound: layout.source_count(),
826            mix_bound: layout.mix_count_per_source(),
827        })
828}
829
830#[derive(Debug, Clone, PartialEq)]
831pub enum EncodeError {
832    OutOfRange {
833        what: &'static str,
834        index: u32,
835        bound: u32,
836    },
837    MixCellOutOfRange {
838        source: u8,
839        mix: u8,
840        source_bound: u8,
841        mix_bound: u8,
842    },
843    /// The named fader strip does not exist on this device model (e.g.
844    /// `Physical6` on a Duo, or `Virtual4` on a Pro II).
845    FaderNotOnModel { fader: Fader, model: DeviceModel },
846    /// A singleton node the command addresses (e.g. `MASTERCHANNEL`, `OUTPUT`)
847    /// was not present in the layout's fullSync. Unlike [`EncodeError::OutOfRange`]
848    /// there is no index: the whole family is absent.
849    MissingNode { what: &'static str },
850}
851
852impl std::fmt::Display for EncodeError {
853    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
854        match self {
855            EncodeError::OutOfRange { what, index, bound } => {
856                write!(f, "{what} index {index} out of range (bound {bound})")
857            }
858            EncodeError::FaderNotOnModel { fader, model } => {
859                write!(f, "fader {fader} does not exist on {model}")
860            }
861            EncodeError::MissingNode { what } => {
862                write!(f, "layout has no {what} node")
863            }
864            EncodeError::MixCellOutOfRange {
865                source,
866                mix,
867                source_bound,
868                mix_bound,
869            } => write!(
870                f,
871                "mix cell ({source}, {mix}) out of range (sources {source_bound}, mixes {mix_bound})"
872            ),
873        }
874    }
875}
876
877impl std::error::Error for EncodeError {}
878
879#[cfg(test)]
880#[path = "commands_tests.rs"]
881mod tests;