Skip to main content

rodecaster_protocol/
events.rs

1//! Inbound typed event notifications from a RØDECaster console.
2//!
3//! [`DeviceEvent`] represents notifications emitted by the device in response
4//! to hardware changes or user actions:
5//!
6//! - Physical or virtual fader movements.
7//! - Mute and cue/solo button toggles.
8//! - Rotary encoder adjustments and color updates.
9//! - Input source assignment changes.
10//! - Audio processing adjustments (EQ, dynamics, HPF, pan).
11//! - Sub-mix changes and routing matrix links.
12//!
13//! # Handling Events
14//!
15//! When using [`crate::ProtocolSession`], events are yielded by
16//! [`crate::ProtocolSession::ingest`]:
17//!
18//! ```rust
19//! use rodecaster_protocol::{DeviceEvent, Fader};
20//!
21//! fn handle_event(event: DeviceEvent) {
22//!     match event {
23//!         DeviceEvent::FaderLevelChanged { fader, level } => {
24//!             println!("{fader:?} level is now {level}");
25//!         }
26//!         DeviceEvent::FaderMuteChanged { fader, muted } => {
27//!             println!("{fader:?} muted: {muted}");
28//!         }
29//!         _ => {}
30//!     }
31//! }
32//! ```
33
34use crate::change_frame::{decode as decode_frame, ChangeFrame};
35use crate::juce_var::Value;
36use crate::layout::Layout;
37use crate::names::{
38    AppParam, AudioParam, BuildParam, ChannelParam, CurrentShowParam, DeviceModel, DuckerParam,
39    EffectsParam, Fader, FxPresetParam, GuiParam, HeadphoneParam, InputSourceParam, MasterParam,
40    MeterParam, MixMinusesParam, MixOutput, NetworkParam, OutputParam, PadParam, PadRecorderParam,
41    PlayerParam, RadioParam, RadioRxParam, RadioTxParam, RcSyncMixParam, RecorderParam,
42    RecordingParam, RecordingsParam, ShowControlParam, ShowParam, SipAdvancedParam,
43    SipCallSlotsParam, SipCallingParam, SipRegistrationParam, Source, StorageVolumeParam,
44    StreamerXMixPresetParam, StreamerXStreamMixParam, SystemParam, TestParam, ThemeParam,
45    WifiScanResultParam,
46};
47use crate::trigger::decode_phase;
48pub use crate::trigger::TriggerPhase;
49use crate::valuetree::Node;
50
51/// A typed event emitted by a connected RØDECaster console.
52#[derive(Debug, Clone, PartialEq)]
53#[non_exhaustive]
54pub enum DeviceEvent {
55    /// Full device state received during initialization or sync.
56    InitialState(Vec<DeviceEvent>),
57
58    /// Fader mute state changed.
59    FaderMuteChanged { fader: Fader, muted: bool },
60    /// Fader cue/solo state changed.
61    FaderCueChanged { fader: Fader, enabled: bool },
62    /// Fader level changed (0..127 MIDI scale).
63    FaderLevelChanged { fader: Fader, level: u8 },
64    /// A fader strip was touched.
65    FaderTouched { fader: Fader },
66    /// Rotary encoder LED-ring colour palette index changed (`None` when cleared).
67    FaderEncoderColourChanged { fader: Fader, colour: Option<i32> },
68    /// Mix link or unlink request or acknowledgment trace.
69    MixLinkRequested {
70        source: Source,
71        mix: MixOutput,
72        direction: MixLinkDirection,
73        origin: MixLinkRequestOrigin,
74    },
75    /// A fader's input-source assignment changed (`None` when unassigned).
76    FaderAssignmentChanged {
77        fader: Fader,
78        source: Option<Source>,
79    },
80
81    /// A channel-strip parameter changed (EQ, dynamics, HPF, pan, tone, preamp).
82    ChannelParamChanged {
83        fader: Fader,
84        param: ChannelParam,
85        value: Value,
86    },
87
88    /// An input-source parameter changed (preamp gain, phantom power, mic type).
89    InputSourceParamChanged {
90        source: Source,
91        param: InputSourceParam,
92        value: Value,
93    },
94
95    /// A master-bus parameter changed (Compellor compressor, master delay).
96    MasterParamChanged { param: MasterParam, value: Value },
97
98    /// An output-bus parameter changed (monitor/Bluetooth level, mute, multi-out).
99    OutputParamChanged { param: OutputParam, value: Value },
100
101    /// Auto-ducking parameters changed.
102    DuckerParamChanged { param: DuckerParam, value: Value },
103
104    /// Recorder transport state or property changed.
105    RecorderParamChanged { param: RecorderParam, value: Value },
106
107    /// Sound player property changed (playback state, file, fade envelope).
108    PlayerParamChanged { param: PlayerParam, value: Value },
109
110    /// Per-headphone parameter changed (colour, output type).
111    HeadphoneParamChanged {
112        headphone: u8,
113        param: HeadphoneParam,
114        value: Value,
115    },
116
117    /// Per-slot channel effects parameter changed (reverb, delay, pitch, distortion).
118    EffectsParamChanged {
119        effects: u8,
120        param: EffectsParam,
121        value: Value,
122    },
123
124    /// Front-panel UI parameter changed (display/button brightness, pad bank).
125    GuiParamChanged { param: GuiParam, value: Value },
126
127    /// Sound-pad parameter changed (colour, sample, playback mode, routing).
128    PadParamChanged {
129        pad: u8,
130        param: PadParam,
131        value: Value,
132    },
133
134    /// Device-wide system parameter changed (power, clock, USB/storage status).
135    SystemParamChanged { param: SystemParam, value: Value },
136
137    /// Routing matrix level changed (`anchor` is matrix level, `value` is live fader-tracked level).
138    MixLevelChanged {
139        source: Source,
140        mix: MixOutput,
141        anchor: f32,
142        value: f32,
143    },
144    /// Routing matrix mute state changed.
145    MixMuteChanged {
146        source: Source,
147        mix: MixOutput,
148        muted: bool,
149    },
150    /// Routing matrix link state changed.
151    MixLinkChanged {
152        source: Source,
153        mix: MixOutput,
154        linked: bool,
155    },
156    /// Routing matrix route disabled state changed.
157    MixDisabledChanged {
158        source: Source,
159        mix: MixOutput,
160        disabled: bool,
161    },
162
163    /// Device-wide networking parameter changed (WiFi, Bluetooth, IP, DNS).
164    NetworkParamChanged { param: NetworkParam, value: Value },
165
166    /// Recordings summary parameter changed (total count, total duration).
167    RecordingsParamChanged {
168        param: RecordingsParam,
169        value: Value,
170    },
171
172    /// Specific recording metadata changed.
173    RecordingParamChanged {
174        recording: u8,
175        param: RecordingParam,
176        value: Value,
177    },
178
179    /// Storage volume parameter changed (total bytes, used bytes).
180    StorageVolumeParamChanged {
181        volume: u8,
182        param: StorageVolumeParam,
183        value: Value,
184    },
185
186    /// Rotary encoder or potentiometer position changed (0..=127).
187    PotLevelChanged { pot: u8, level: u8 },
188
189    /// Front-panel pad button press or release.
190    PadButtonPressed { button: u8, pressed: bool },
191
192    /// Front-panel mute button press or release.
193    MutePressed { button: u8, pressed: bool },
194
195    /// Device-wide audio-engine parameter changed (sample rate, buffer size, latencies).
196    AudioParamChanged { param: AudioParam, value: Value },
197
198    /// Firmware build metadata changed.
199    BuildParamChanged { param: BuildParam, value: Value },
200
201    /// Companion-app state flag changed.
202    AppParamChanged { param: AppParam, value: Value },
203
204    /// UI theme setting changed.
205    ThemeParamChanged { param: ThemeParam, value: Value },
206
207    /// Currently-loaded show identifier changed.
208    CurrentShowParamChanged {
209        param: CurrentShowParam,
210        value: Value,
211    },
212
213    /// Show metadata changed.
214    ShowParamChanged {
215        show: u8,
216        param: ShowParam,
217        value: Value,
218    },
219
220    /// Show control or lifecycle action changed.
221    ShowControlParamChanged {
222        param: ShowControlParam,
223        value: Value,
224    },
225
226    /// Live level meter reading changed.
227    MeterParamChanged {
228        meter: u8,
229        param: MeterParam,
230        value: Value,
231    },
232
233    /// Rotary encoder push-button press or release.
234    EncoderPressed { encoder: u8, pressed: bool },
235
236    /// Front-panel solo/listen button press or release.
237    SoloPressed { button: u8, pressed: bool },
238
239    /// Front-panel record button press or release.
240    RecButtonPressed { pressed: bool },
241
242    /// Emergency mute state changed.
243    EmergencyMuteChanged { active: bool },
244
245    /// SIP calling state parameter changed.
246    SipCallingParamChanged {
247        param: SipCallingParam,
248        value: Value,
249    },
250
251    /// SIP account registration parameter changed.
252    SipRegistrationParamChanged {
253        registration: u8,
254        param: SipRegistrationParam,
255        value: Value,
256    },
257
258    /// SIP call slot parameter changed.
259    SipCallSlotsParamChanged {
260        slot: u8,
261        param: SipCallSlotsParam,
262        value: Value,
263    },
264
265    /// SIP advanced setting changed.
266    SipAdvancedParamChanged {
267        param: SipAdvancedParam,
268        value: Value,
269    },
270
271    /// Streamer X mix preset parameter changed.
272    StreamerXMixPresetParamChanged {
273        preset: u8,
274        param: StreamerXMixPresetParam,
275        value: Value,
276    },
277
278    /// Streamer X stream mix parameter changed.
279    StreamerXStreamMixParamChanged {
280        stream: u8,
281        param: StreamerXStreamMixParam,
282        value: Value,
283    },
284
285    /// Effects preset parameter changed.
286    FxPresetParamChanged {
287        preset: u8,
288        param: FxPresetParam,
289        value: Value,
290    },
291
292    /// Pad recorder parameter changed.
293    PadRecorderParamChanged {
294        pad_recorder: u8,
295        param: PadRecorderParam,
296        value: Value,
297    },
298
299    /// Diagnostic or factory-test parameter changed.
300    TestParamChanged { param: TestParam, value: Value },
301
302    /// WiFi scan result entry changed.
303    WifiScanResultChanged {
304        slot: u8,
305        param: WifiScanResultParam,
306        value: Value,
307    },
308
309    /// Wireless receiver lifecycle parameter changed.
310    RadioParamChanged { param: RadioParam, value: Value },
311
312    /// Wireless transmitter parameter changed.
313    RadioTxParamChanged {
314        tx: u8,
315        param: RadioTxParam,
316        value: Value,
317    },
318
319    /// Wireless receiver parameter changed.
320    RadioRxParamChanged {
321        rx: u8,
322        param: RadioRxParam,
323        value: Value,
324    },
325
326    /// Mix-minus routing parameter changed.
327    MixMinusesParamChanged {
328        minuses: u8,
329        param: MixMinusesParam,
330        value: Value,
331    },
332
333    /// rcSync mix routing parameter changed.
334    RcSyncMixParamChanged {
335        mix: u8,
336        param: RcSyncMixParam,
337        value: Value,
338    },
339
340    /// Tree topology changed (child added, removed, or moved); layout should be rebuilt.
341    LayoutInvalidated,
342
343    /// Unrecognized property name or path under the current layout.
344    Unknown {
345        prop_name: String,
346        path: Vec<u32>,
347        value: Option<Value>,
348    },
349}
350
351/// Direction of a mix-cell link request echo.
352#[derive(Debug, Clone, Copy, PartialEq, Eq)]
353pub enum MixLinkDirection {
354    /// Link action (`mixLinkRequest`).
355    Link,
356    /// Unlink action (`mixUnlinkRequest`).
357    Unlink,
358}
359
360/// Origin of a mix-cell link request observation (alias for [`TriggerPhase`]).
361pub type MixLinkRequestOrigin = TriggerPhase;
362
363/// Decode one wire payload (the change-frame, not including transport frame)
364/// into a typed event. Returns `None` if the payload isn't a recognized JUCE
365/// change-frame at all.
366pub fn decode_event(payload: &[u8], layout: &Layout) -> Option<DeviceEvent> {
367    let frame = decode_frame(payload)?;
368    Some(decode_change_frame(frame, layout))
369}
370
371/// Decode an already-parsed [`ChangeFrame`] through the discovered [`Layout`]
372/// into a typed [`DeviceEvent`].
373pub fn decode_event_from_frame(frame: ChangeFrame, layout: &Layout) -> DeviceEvent {
374    decode_change_frame(frame, layout)
375}
376
377fn decode_change_frame(frame: ChangeFrame, layout: &Layout) -> DeviceEvent {
378    match frame {
379        ChangeFrame::FullSync { root } => {
380            DeviceEvent::InitialState(extract_initial_state(&root, layout))
381        }
382        ChangeFrame::ChildAdded { .. }
383        | ChangeFrame::ChildRemoved { .. }
384        | ChangeFrame::ChildMoved { .. } => DeviceEvent::LayoutInvalidated,
385        ChangeFrame::PropertyChanged { path, name, value } => {
386            decode_property(&path, &name, Some(value), layout)
387        }
388        ChangeFrame::PropertyRemoved { path, name } => decode_property(&path, &name, None, layout),
389    }
390}
391
392fn decode_property(path: &[u32], name: &str, value: Option<Value>, layout: &Layout) -> DeviceEvent {
393    let model = layout.model();
394
395    // CHANNEL-addressed properties (single-level path). A path that resolves to
396    // a channel with no named fader (the master strip, index 9) falls through
397    // to Unknown rather than matching here.
398    if let Some(fader) = layout
399        .channel_index_from_path(path)
400        .and_then(|idx| Fader::from_index(model, idx))
401    {
402        match name {
403            "channelOutputMute" => {
404                if let Some(Value::Bool(muted)) = value {
405                    return DeviceEvent::FaderMuteChanged { fader, muted };
406                }
407            }
408            "channelCueEnable" => {
409                if let Some(Value::Bool(enabled)) = value {
410                    return DeviceEvent::FaderCueChanged { fader, enabled };
411                }
412            }
413            "channelInputSource" => {
414                let source = value
415                    .as_ref()
416                    .and_then(Value::as_int)
417                    .filter(|&s| s >= 0)
418                    .and_then(|s| u8::try_from(s).ok())
419                    .and_then(Source::from_protocol);
420                return DeviceEvent::FaderAssignmentChanged { fader, source };
421            }
422            _ => {}
423        }
424    }
425
426    // FADER-addressed properties (two-level path through PHYSICALINTERFACE).
427    if let Some(fader) = layout
428        .fader_index_from_path(path)
429        .and_then(|idx| Fader::from_index(model, idx))
430    {
431        if name == "faderLevel" {
432            if let Some(v) = &value {
433                if let Some(level_i64) = v.as_int() {
434                    let level = level_i64.clamp(0, 127) as u8;
435                    return DeviceEvent::FaderLevelChanged { fader, level };
436                }
437            }
438        }
439    }
440
441    // MIX-cell-addressed properties (single-level path).
442    if let Some((source, mix)) = layout
443        .mix_cell_from_path(path)
444        .and_then(|(s, m)| Some((Source::from_protocol(s)?, MixOutput::from_protocol(m)?)))
445    {
446        match name {
447            "mixMute" => {
448                if let Some(Value::Bool(muted)) = value {
449                    return DeviceEvent::MixMuteChanged { source, mix, muted };
450                }
451            }
452            "mixLink" => {
453                if let Some(Value::Bool(linked)) = value {
454                    return DeviceEvent::MixLinkChanged {
455                        source,
456                        mix,
457                        linked,
458                    };
459                }
460            }
461            "mixDisabled" => {
462                if let Some(Value::Bool(disabled)) = value {
463                    return DeviceEvent::MixDisabledChanged {
464                        source,
465                        mix,
466                        disabled,
467                    };
468                }
469            }
470            "mixLevelWithAnchor" => {
471                if let Some(Value::String(s)) = &value {
472                    if let Some((anchor, value)) = parse_mix_level(s) {
473                        return DeviceEvent::MixLevelChanged {
474                            source,
475                            mix,
476                            anchor,
477                            value,
478                        };
479                    }
480                }
481            }
482            // mixLinkRequest / mixUnlinkRequest at a cell's single-level path.
483            // Direction = property name; origin = momentary trigger state.
484            "mixLinkRequest" | "mixUnlinkRequest" => {
485                if let Some(origin) = value.as_ref().and_then(decode_phase) {
486                    let direction = if name == "mixLinkRequest" {
487                        MixLinkDirection::Link
488                    } else {
489                        MixLinkDirection::Unlink
490                    };
491                    return DeviceEvent::MixLinkRequested {
492                        source,
493                        mix,
494                        direction,
495                        origin,
496                    };
497                }
498            }
499            _ => {}
500        }
501    }
502
503    // encoderSignal (fader touch): single-level path whose value IS the fader
504    // index (stride 1, no base offset). See module docs.
505    if name == "encoderSignal" {
506        if let Some(&raw) = path.first() {
507            if raw < layout.fader_count() as u32 {
508                if let Some(fader) = Fader::from_index(model, raw as u8) {
509                    return DeviceEvent::FaderTouched { fader };
510                }
511            }
512        }
513    }
514
515    // encoderColour: LED-ring colour of a fader strip's rotary encoder. Same
516    // single-level addressing as encoderSignal; the value is an Int where -1
517    // means "cleared / no colour" and >= 0 is the palette index. A missing
518    // or non-Int value falls through to Unknown so we don't conflate the two.
519    if name == "encoderColour" {
520        if let Some(&raw) = path.first() {
521            if raw < layout.fader_count() as u32 {
522                if let Some(fader) = Fader::from_index(model, raw as u8) {
523                    if let Some(i) = value.as_ref().and_then(Value::as_int) {
524                        let colour = if i < 0 { None } else { Some(i as i32) };
525                        return DeviceEvent::FaderEncoderColourChanged { fader, colour };
526                    }
527                }
528            }
529        }
530    }
531
532    // channelInputSource echo: resolves via stride-1 channel_index_from_path first,
533    // falling back to stride-6 echo addressing when node is offset-addressed.
534    if name == "channelInputSource" {
535        let fader_opt = layout
536            .channel_index_from_path(path)
537            .and_then(|idx| Fader::from_index(model, idx))
538            .or_else(|| {
539                path.first()
540                    .and_then(|raw| raw.checked_sub(layout.first_channel()))
541                    .filter(|&offset| offset % 6 == 0)
542                    .map(|offset| offset / 6)
543                    .filter(|&idx| idx < layout.channel_count() as u32)
544                    .and_then(|idx| Fader::from_index(model, idx as u8))
545            });
546
547        if let Some(fader) = fader_opt {
548            let source = value
549                .as_ref()
550                .and_then(Value::as_int)
551                .filter(|&s| s >= 0)
552                .and_then(|s| u8::try_from(s).ok())
553                .and_then(Source::from_protocol);
554            return DeviceEvent::FaderAssignmentChanged { fader, source };
555        }
556    }
557
558    // PHYSICALINTERFACE hardware-child input events. Path shape is
559    // `[physical_interface_idx, child_index]`. Each property name here is
560    // unique to its child node type, so we key off the name and hand the
561    // caller the raw child index (per-model mapping is the caller's job).
562    if path.len() == 2 && path[0] == layout.physical_interface_idx() {
563        let child = path[1] as u8;
564        match name {
565            "potLevel" => {
566                if let Some(Value::Int(level)) = value.as_ref() {
567                    return DeviceEvent::PotLevelChanged {
568                        pot: child,
569                        level: (*level).clamp(0, 127) as u8,
570                    };
571                }
572            }
573            "padButtonPressed" => {
574                if let Some(Value::Bool(pressed)) = value.as_ref() {
575                    return DeviceEvent::PadButtonPressed {
576                        button: child,
577                        pressed: *pressed,
578                    };
579                }
580            }
581            "mutePressed" => {
582                if let Some(Value::Bool(pressed)) = value.as_ref() {
583                    return DeviceEvent::MutePressed {
584                        button: child,
585                        pressed: *pressed,
586                    };
587                }
588            }
589            "soloPressed" => {
590                if let Some(Value::Bool(pressed)) = value.as_ref() {
591                    return DeviceEvent::SoloPressed {
592                        button: child,
593                        pressed: *pressed,
594                    };
595                }
596            }
597            "encoderPressed" => {
598                if let Some(Value::Bool(pressed)) = value.as_ref() {
599                    return DeviceEvent::EncoderPressed {
600                        encoder: child,
601                        pressed: *pressed,
602                    };
603                }
604            }
605            "recButtonPressed" => {
606                if let Some(Value::Bool(pressed)) = value.as_ref() {
607                    return DeviceEvent::RecButtonPressed { pressed: *pressed };
608                }
609            }
610            _ => {}
611        }
612    }
613
614    // EMERGENCYMUTE singleton at root (path.len() == 1).
615    if path.len() == 1 && name == "emergencyMuteActive" {
616        if let Some(Value::Bool(active)) = value.as_ref() {
617            return DeviceEvent::EmergencyMuteChanged { active: *active };
618        }
619    }
620
621    // NETWORK singleton: property names are all `bt*`, `wifi*`, `cell*`, etc.
622    // The wire-name set is unique to the NETWORK node, so we match on name
623    // without checking path (any structurally-valid propertyChanged carrying
624    // one of these names lands here).
625    if let Some(param) = NetworkParam::from_known_name(name) {
626        if let Some(value) = value {
627            return DeviceEvent::NetworkParamChanged { param, value };
628        }
629    }
630
631    // RECORDINGS singleton (path.len() == 1).
632    if path.len() == 1 {
633        if let Some(param) = RecordingsParam::from_known_name(name) {
634            if let Some(value) = value {
635                return DeviceEvent::RecordingsParamChanged { param, value };
636            }
637        }
638    }
639
640    // RECORDING children (path.len() == 2). path[1] is the child index within
641    // the RECORDINGS container.
642    if path.len() == 2 {
643        if let Some(param) = RecordingParam::from_known_name(name) {
644            if let Some(value) = value {
645                return DeviceEvent::RecordingParamChanged {
646                    recording: path[1] as u8,
647                    param,
648                    value,
649                };
650            }
651        }
652
653        // STORAGEVOLUME children (path.len() == 2). path[1] is the volume index.
654        if let Some(param) = StorageVolumeParam::from_known_name(name) {
655            if let Some(value) = value {
656                return DeviceEvent::StorageVolumeParamChanged {
657                    volume: path[1] as u8,
658                    param,
659                    value,
660                };
661            }
662        }
663    }
664
665    // Path-length-1 singletons: property names are unique to each family.
666    if path.len() == 1 {
667        if let Some(param) = AudioParam::from_known_name(name) {
668            if let Some(value) = value {
669                return DeviceEvent::AudioParamChanged { param, value };
670            }
671        }
672        if let Some(param) = BuildParam::from_known_name(name) {
673            if let Some(value) = value {
674                return DeviceEvent::BuildParamChanged { param, value };
675            }
676        }
677        if let Some(param) = AppParam::from_known_name(name) {
678            if let Some(value) = value {
679                return DeviceEvent::AppParamChanged { param, value };
680            }
681        }
682        if let Some(param) = ThemeParam::from_known_name(name) {
683            if let Some(value) = value {
684                return DeviceEvent::ThemeParamChanged { param, value };
685            }
686        }
687        if let Some(param) = CurrentShowParam::from_known_name(name) {
688            if let Some(value) = value {
689                return DeviceEvent::CurrentShowParamChanged { param, value };
690            }
691        }
692        if let Some(param) = ShowControlParam::from_known_name(name) {
693            if let Some(value) = value {
694                return DeviceEvent::ShowControlParamChanged { param, value };
695            }
696        }
697    }
698
699    // Path-length-2 children under SHOWS and METER containers.
700    if path.len() == 2 {
701        if let Some(param) = ShowParam::from_known_name(name) {
702            if let Some(value) = value {
703                return DeviceEvent::ShowParamChanged {
704                    show: path[1] as u8,
705                    param,
706                    value,
707                };
708            }
709        }
710
711        if path[0] != layout.physical_interface_idx() {
712            if let Some(param) = MeterParam::from_known_name(name) {
713                if let Some(value) = value {
714                    return DeviceEvent::MeterParamChanged {
715                        meter: path[1] as u8,
716                        param,
717                        value,
718                    };
719                }
720            }
721        }
722    }
723
724    // SIPCALLING singleton (path.len() == 1, layout-resolved position).
725    if layout.is_sip_calling_path(path) {
726        if let Some(param) = SipCallingParam::from_known_name(name) {
727            if let Some(value) = value {
728                return DeviceEvent::SipCallingParamChanged { param, value };
729            }
730        }
731    }
732
733    // SIPADVANCED singleton.
734    if layout.is_sip_advanced_path(path) {
735        if let Some(param) = SipAdvancedParam::from_known_name(name) {
736            if let Some(value) = value {
737                return DeviceEvent::SipAdvancedParamChanged { param, value };
738            }
739        }
740    }
741
742    // SIPREGISTRATION per-instance under SIPCALLING.
743    if let Some(reg) = layout.sip_registration_index_from_path(path) {
744        if let Some(param) = SipRegistrationParam::from_known_name(name) {
745            if let Some(value) = value {
746                return DeviceEvent::SipRegistrationParamChanged {
747                    registration: reg,
748                    param,
749                    value,
750                };
751            }
752        }
753    }
754
755    // SIPCALLSLOTS per-slot at root.
756    if let Some(slot) = layout.sip_call_slots_index_from_path(path) {
757        if let Some(param) = SipCallSlotsParam::from_known_name(name) {
758            if let Some(value) = value {
759                return DeviceEvent::SipCallSlotsParamChanged { slot, param, value };
760            }
761        }
762    }
763
764    // Small-family decodes for property names that don't conflict with any
765    // typed family above. Each name is unique to its family, so we key by
766    // name; per-instance families take path.last() as the ordinal (no
767    // layout resolution: the path itself carries enough context).
768
769    if let Some(param) = StreamerXMixPresetParam::from_known_name(name) {
770        if let Some(value) = value {
771            let preset = path.last().copied().unwrap_or(0) as u8;
772            return DeviceEvent::StreamerXMixPresetParamChanged {
773                preset,
774                param,
775                value,
776            };
777        }
778    }
779    if let Some(param) = StreamerXStreamMixParam::from_known_name(name) {
780        if let Some(value) = value {
781            let stream = path.last().copied().unwrap_or(0) as u8;
782            return DeviceEvent::StreamerXStreamMixParamChanged {
783                stream,
784                param,
785                value,
786            };
787        }
788    }
789    if let Some(param) = FxPresetParam::from_known_name(name) {
790        if let Some(value) = value {
791            let preset = path.last().copied().unwrap_or(0) as u8;
792            return DeviceEvent::FxPresetParamChanged {
793                preset,
794                param,
795                value,
796            };
797        }
798    }
799    if let Some(param) = PadRecorderParam::from_known_name(name) {
800        if let Some(value) = value {
801            let pad_recorder = path.last().copied().unwrap_or(0) as u8;
802            return DeviceEvent::PadRecorderParamChanged {
803                pad_recorder,
804                param,
805                value,
806            };
807        }
808    }
809    if let Some(param) = TestParam::from_known_name(name) {
810        if let Some(value) = value {
811            return DeviceEvent::TestParamChanged { param, value };
812        }
813    }
814    if let Some(param) = WifiScanResultParam::from_known_name(name) {
815        if let Some(value) = value {
816            // Path shape is [network_root_idx, scan_slot]; slot is path.last().
817            let slot = path.last().copied().unwrap_or(0) as u8;
818            return DeviceEvent::WifiScanResultChanged { slot, param, value };
819        }
820    }
821    if let Some(param) = RadioParam::from_known_name(name) {
822        if let Some(value) = value {
823            return DeviceEvent::RadioParamChanged { param, value };
824        }
825    }
826    if let Some(param) = RadioTxParam::from_known_name(name) {
827        if let Some(value) = value {
828            let tx = path.last().copied().unwrap_or(0) as u8;
829            return DeviceEvent::RadioTxParamChanged { tx, param, value };
830        }
831    }
832    if let Some(param) = RadioRxParam::from_known_name(name) {
833        if let Some(value) = value {
834            let rx = path.last().copied().unwrap_or(0) as u8;
835            return DeviceEvent::RadioRxParamChanged { rx, param, value };
836        }
837    }
838    if let Some(minuses) = layout.mix_minuses_index_from_path(path) {
839        if let Some(param) = MixMinusesParam::from_known_name(name) {
840            if let Some(value) = value {
841                return DeviceEvent::MixMinusesParamChanged {
842                    minuses,
843                    param,
844                    value,
845                };
846            }
847        }
848    }
849    // RcSyncMixParam shares six wire names with the regular MIX cell family
850    // (mixDisabled / mixLevelWithAnchor / mixLink / mixLinkRequest / mixMute /
851    // mixUnlinkRequest). The MIX matrix decode above matches paths inside the
852    // discovered `first_mix + source*13 + mix` run; anything outside that run
853    // that still carries these names lands here. The seventh property
854    // (`mixRcSyncLevelRequest`) is unique to RCSYNCMIX.
855    if let Some(mix) = layout.rcsync_mix_index_from_path(path) {
856        if let Some(param) = RcSyncMixParam::from_known_name(name) {
857            if let Some(value) = value {
858                return DeviceEvent::RcSyncMixParamChanged { mix, param, value };
859            }
860        }
861    }
862
863    // Typed param-family promotion: any *other* property on an addressable node
864    // becomes the matching typed `*ParamChanged` event, carrying the
865    // self-describing wire value. `resolve_param_target` decides which family the
866    // path lands on (CHANNEL strip, INPUTSOURCE, the MASTERCHANNEL / OUTPUT /
867    // DUCKER / RECORDER / PLAYER singletons, or a HEADPHONE jack). Those node
868    // index ranges are disjoint, so the resolver order is for clarity, not
869    // precedence. `value` is moved exactly once: into the matched event, else
870    // into Unknown (which also catches `propertyRemoved`, where value is None).
871    match (resolve_param_target(path, name, layout, model), value) {
872        (Some(ParamTarget::Channel(fader)), Some(value)) => DeviceEvent::ChannelParamChanged {
873            fader,
874            param: ChannelParam::from_name(name),
875            value,
876        },
877        (Some(ParamTarget::InputSource(source)), Some(value)) => {
878            DeviceEvent::InputSourceParamChanged {
879                source,
880                param: InputSourceParam::from_name(name),
881                value,
882            }
883        }
884        (Some(ParamTarget::Master), Some(value)) => DeviceEvent::MasterParamChanged {
885            param: MasterParam::from_name(name),
886            value,
887        },
888        (Some(ParamTarget::Output), Some(value)) => DeviceEvent::OutputParamChanged {
889            param: OutputParam::from_name(name),
890            value,
891        },
892        (Some(ParamTarget::Ducker), Some(value)) => DeviceEvent::DuckerParamChanged {
893            param: DuckerParam::from_name(name),
894            value,
895        },
896        (Some(ParamTarget::Recorder), Some(value)) => DeviceEvent::RecorderParamChanged {
897            param: RecorderParam::from_name(name),
898            value,
899        },
900        (Some(ParamTarget::Player), Some(value)) => DeviceEvent::PlayerParamChanged {
901            param: PlayerParam::from_name(name),
902            value,
903        },
904        (Some(ParamTarget::Headphone(headphone)), Some(value)) => {
905            DeviceEvent::HeadphoneParamChanged {
906                headphone,
907                param: HeadphoneParam::from_name(name),
908                value,
909            }
910        }
911        (Some(ParamTarget::Effects(effects)), Some(value)) => DeviceEvent::EffectsParamChanged {
912            effects,
913            param: EffectsParam::from_name(name),
914            value,
915        },
916        (Some(ParamTarget::Gui), Some(value)) => DeviceEvent::GuiParamChanged {
917            param: GuiParam::from_name(name),
918            value,
919        },
920        (Some(ParamTarget::Pad(pad)), Some(value)) => DeviceEvent::PadParamChanged {
921            pad,
922            param: PadParam::from_name(name),
923            value,
924        },
925        (Some(ParamTarget::System), Some(value)) => DeviceEvent::SystemParamChanged {
926            param: SystemParam::from_name(name),
927            value,
928        },
929        (_, value) => DeviceEvent::Unknown {
930            prop_name: name.to_string(),
931            path: path.to_vec(),
932            value,
933        },
934    }
935}
936
937/// Which addressable node family a property path lands on. Resolved by
938/// [`resolve_param_target`] and consumed by [`decode_property`] to promote a
939/// property to the matching typed `*ParamChanged` event.
940enum ParamTarget {
941    Channel(Fader),
942    InputSource(Source),
943    Master,
944    Output,
945    Ducker,
946    Recorder,
947    Player,
948    Headphone(u8),
949    Effects(u8),
950    Gui,
951    Pad(u8),
952    System,
953}
954
955/// Resolve a property path to its addressable node family, if any. The node
956/// index ranges are disjoint, so the first match wins and the order is for
957/// readability only. Returns `None` for paths that don't land on a typed family
958/// (the caller then emits [`DeviceEvent::Unknown`]).
959fn resolve_param_target(
960    path: &[u32],
961    name: &str,
962    layout: &Layout,
963    model: DeviceModel,
964) -> Option<ParamTarget> {
965    // CHANNEL strip (the whole EQ / dynamics / HPF / aphex / pan / tone / preamp
966    // strip). The three specialized props that own dedicated variants are
967    // excluded so a malformed one of those falls to Unknown rather than
968    // masquerading as a generic strip param.
969    if !matches!(
970        name,
971        "channelOutputMute" | "channelCueEnable" | "channelInputSource"
972    ) {
973        if let Some(fader) = layout
974            .channel_index_from_path(path)
975            .and_then(|idx| Fader::from_index(model, idx))
976        {
977            return Some(ParamTarget::Channel(fader));
978        }
979    }
980    // INPUTSOURCE: the input* preamp/source params, on a node separate from
981    // CHANNEL. An ordinal past the named vocabulary (a rcSync / streamer-x
982    // placeholder source) doesn't map and falls through to Unknown.
983    if let Some(source) = layout
984        .input_source_index_from_path(path)
985        .and_then(Source::from_protocol)
986    {
987        return Some(ParamTarget::InputSource(source));
988    }
989    // Singletons: exactly one node each, key-less.
990    if layout.is_master_channel_path(path) {
991        return Some(ParamTarget::Master);
992    }
993    if layout.is_output_path(path) {
994        return Some(ParamTarget::Output);
995    }
996    if layout.is_ducker_path(path) {
997        return Some(ParamTarget::Ducker);
998    }
999    if layout.is_recorder_path(path) {
1000        return Some(ParamTarget::Recorder);
1001    }
1002    if layout.is_player_path(path) {
1003        return Some(ParamTarget::Player);
1004    }
1005    // HEADPHONE: multi-instance, one node per physical jack.
1006    if let Some(headphone) = layout.headphone_index_from_path(path) {
1007        return Some(ParamTarget::Headphone(headphone));
1008    }
1009    // EFFECTS_PARAMETERS: multi-instance, one node per channel-strip effects slot.
1010    if let Some(effects) = layout.effects_index_from_path(path) {
1011        return Some(ParamTarget::Effects(effects));
1012    }
1013    // GUI: the single front-panel UI-state node.
1014    if layout.is_gui_path(path) {
1015        return Some(ParamTarget::Gui);
1016    }
1017    // PAD: multi-instance, one node per sound pad inside SOUNDPADS (two-level).
1018    if let Some(pad) = layout.pad_index_from_path(path) {
1019        return Some(ParamTarget::Pad(pad));
1020    }
1021    // SYSTEM: the single device-wide state node.
1022    if layout.is_system_path(path) {
1023        return Some(ParamTarget::System);
1024    }
1025    None
1026}
1027
1028/// `mixLevelWithAnchor` wire form: `anchor|value` (or a single number for
1029/// both). Returns `(anchor, value)`: the left/configured matrix level and the
1030/// right/fader-tracked level.
1031fn parse_mix_level(s: &str) -> Option<(f32, f32)> {
1032    let anchor = s.split('|').next()?.parse().ok()?;
1033    let value = s.split('|').next_back()?.parse().ok()?;
1034    Some((anchor, value))
1035}
1036
1037/// Walk a parsed fullSync tree and extract the initial device state as a list of [`DeviceEvent`]s.
1038pub fn extract_initial_state(root: &Node, layout: &Layout) -> Vec<DeviceEvent> {
1039    let mut out = Vec::new();
1040    let model = layout.model();
1041
1042    // 1. PHYSICALINTERFACE -> FADER initial levels (physical strips only).
1043    if let Some(phys) = root.children.iter().find(|n| n.name == "PHYSICALINTERFACE") {
1044        let mut fader_idx: u8 = 0;
1045        for child in &phys.children {
1046            if child.name != "FADER" {
1047                continue;
1048            }
1049            if let (Some(fader), Some(level)) = (
1050                Fader::from_index(model, fader_idx),
1051                int_prop(child, "faderLevel"),
1052            ) {
1053                out.push(DeviceEvent::FaderLevelChanged {
1054                    fader,
1055                    level: level.clamp(0, 127) as u8,
1056                });
1057            }
1058            fader_idx = fader_idx.saturating_add(1);
1059        }
1060    }
1061
1062    // 2. CHANNEL initial mute/cue (one per strip, including virtuals). The
1063    // master strip (index 9) has no named fader, so its properties are skipped.
1064    let mut channel_idx: u8 = 0;
1065    for child in &root.children {
1066        if child.name != "CHANNEL" {
1067            continue;
1068        }
1069        if let Some(fader) = Fader::from_index(model, channel_idx) {
1070            if let Some(muted) = bool_prop(child, "channelOutputMute") {
1071                out.push(DeviceEvent::FaderMuteChanged { fader, muted });
1072            }
1073            if let Some(enabled) = bool_prop(child, "channelCueEnable") {
1074                out.push(DeviceEvent::FaderCueChanged { fader, enabled });
1075            }
1076            // In a fullSync the assignment sits on the Nth CHANNEL positionally
1077            // (stride 1), unlike the stride-6 incremental echo.
1078            if let Some(source_i) = int_prop(child, "channelInputSource") {
1079                out.push(DeviceEvent::FaderAssignmentChanged {
1080                    fader,
1081                    source: if source_i < 0 {
1082                        None
1083                    } else {
1084                        u8::try_from(source_i).ok().and_then(Source::from_protocol)
1085                    },
1086                });
1087            }
1088            // Everything else on the CHANNEL node is the channel strip (EQ,
1089            // dynamics, HPF, aphex, pan, tone, preamp). Emit each as a typed,
1090            // fader-resolved param so the initial state carries the full strip,
1091            // not just mute/cue/source. Skips the three handled above.
1092            for p in &child.properties {
1093                if matches!(
1094                    p.name.as_str(),
1095                    "channelOutputMute" | "channelCueEnable" | "channelInputSource"
1096                ) {
1097                    continue;
1098                }
1099                out.push(DeviceEvent::ChannelParamChanged {
1100                    fader,
1101                    param: ChannelParam::from_name(&p.name),
1102                    value: p.value.clone(),
1103                });
1104            }
1105        }
1106        channel_idx = channel_idx.saturating_add(1);
1107    }
1108
1109    // 3. MIX cells initial values. Source-major: cell N has source = N/13, mix
1110    // = N%13. Cells whose source ordinal falls past the named vocabulary (e.g.
1111    // a Duo's rcSync RCV placeholder block) don't map and are skipped; the
1112    // counter still advances so later cells keep their source-major position.
1113    let mut mix_counter: u32 = 0;
1114    let per_source = layout.mix_count_per_source() as u32;
1115    for child in &root.children {
1116        if child.name != "MIX" {
1117            continue;
1118        }
1119        let source_idx = (mix_counter / per_source) as u8;
1120        let mix_idx = (mix_counter % per_source) as u8;
1121        mix_counter += 1;
1122        let (source, mix) = match (
1123            Source::from_protocol(source_idx),
1124            MixOutput::from_protocol(mix_idx),
1125        ) {
1126            (Some(s), Some(m)) => (s, m),
1127            _ => continue,
1128        };
1129        if let Some(level_s) = string_prop(child, "mixLevelWithAnchor") {
1130            if let Some((anchor, value)) = parse_mix_level(level_s) {
1131                out.push(DeviceEvent::MixLevelChanged {
1132                    source,
1133                    mix,
1134                    anchor,
1135                    value,
1136                });
1137            }
1138        }
1139        if let Some(muted) = bool_prop(child, "mixMute") {
1140            out.push(DeviceEvent::MixMuteChanged { source, mix, muted });
1141        }
1142        if let Some(linked) = bool_prop(child, "mixLink") {
1143            out.push(DeviceEvent::MixLinkChanged {
1144                source,
1145                mix,
1146                linked,
1147            });
1148        }
1149        if let Some(disabled) = bool_prop(child, "mixDisabled") {
1150            out.push(DeviceEvent::MixDisabledChanged {
1151                source,
1152                mix,
1153                disabled,
1154            });
1155        }
1156    }
1157
1158    // 4. INPUTSOURCE initial preamp/source params (one set per addressable
1159    // source). The counter runs over every INPUTSOURCE node in tree order; the
1160    // ordinal == the device `inputId` == `Source::to_protocol`. Ordinals past
1161    // the named vocabulary (a Duo's rcSync / streamer-x placeholder block) don't
1162    // map and are skipped, the counter still advancing so later sources keep
1163    // their position.
1164    let mut input_source_idx: u32 = 0;
1165    for child in &root.children {
1166        if child.name != "INPUTSOURCE" {
1167            continue;
1168        }
1169        let ordinal = input_source_idx;
1170        input_source_idx += 1;
1171        let source = match u8::try_from(ordinal).ok().and_then(Source::from_protocol) {
1172            Some(s) => s,
1173            None => continue,
1174        };
1175        for p in &child.properties {
1176            out.push(DeviceEvent::InputSourceParamChanged {
1177                source,
1178                param: InputSourceParam::from_name(&p.name),
1179                value: p.value.clone(),
1180            });
1181        }
1182    }
1183
1184    // 5. MASTERCHANNEL and OUTPUT initial params (singletons). Emit every
1185    // property the device carries on each node as a typed, key-less event.
1186    if let Some(node) = root.children.iter().find(|c| c.name == "MASTERCHANNEL") {
1187        for p in &node.properties {
1188            out.push(DeviceEvent::MasterParamChanged {
1189                param: MasterParam::from_name(&p.name),
1190                value: p.value.clone(),
1191            });
1192        }
1193    }
1194    if let Some(node) = root.children.iter().find(|c| c.name == "OUTPUT") {
1195        for p in &node.properties {
1196            out.push(DeviceEvent::OutputParamChanged {
1197                param: OutputParam::from_name(&p.name),
1198                value: p.value.clone(),
1199            });
1200        }
1201    }
1202
1203    // 6. DUCKER / RECORDER / PLAYER initial params (singletons). Same key-less
1204    // shape: emit every property each node carries as its typed event.
1205    if let Some(node) = root.children.iter().find(|c| c.name == "DUCKER") {
1206        for p in &node.properties {
1207            out.push(DeviceEvent::DuckerParamChanged {
1208                param: DuckerParam::from_name(&p.name),
1209                value: p.value.clone(),
1210            });
1211        }
1212    }
1213    if let Some(node) = root.children.iter().find(|c| c.name == "RECORDER") {
1214        for p in &node.properties {
1215            out.push(DeviceEvent::RecorderParamChanged {
1216                param: RecorderParam::from_name(&p.name),
1217                value: p.value.clone(),
1218            });
1219        }
1220    }
1221    if let Some(node) = root.children.iter().find(|c| c.name == "PLAYER") {
1222        for p in &node.properties {
1223            out.push(DeviceEvent::PlayerParamChanged {
1224                param: PlayerParam::from_name(&p.name),
1225                value: p.value.clone(),
1226            });
1227        }
1228    }
1229
1230    // 7. HEADPHONE initial params (multi-instance, one node per physical jack).
1231    // The counter runs over every HEADPHONE node in tree order; its ordinal is
1232    // the headphone index that events and commands address.
1233    let mut headphone_idx: u8 = 0;
1234    for child in &root.children {
1235        if child.name != "HEADPHONE" {
1236            continue;
1237        }
1238        let headphone = headphone_idx;
1239        headphone_idx = headphone_idx.saturating_add(1);
1240        for p in &child.properties {
1241            out.push(DeviceEvent::HeadphoneParamChanged {
1242                headphone,
1243                param: HeadphoneParam::from_name(&p.name),
1244                value: p.value.clone(),
1245            });
1246        }
1247    }
1248
1249    // 8. EFFECTS_PARAMETERS initial params (multi-instance, one node per
1250    // channel-strip effects slot). Only the first contiguous run at root is the
1251    // addressable slots; the counter stops at the first non-EFFECTS_PARAMETERS
1252    // node so the nested PADEFFECTS set (a separate addressing context) is not
1253    // folded in. The ordinal is the slot index events and commands address.
1254    let mut effects_idx: u8 = 0;
1255    let mut seen_effects = false;
1256    for child in &root.children {
1257        if child.name != "EFFECTS_PARAMETERS" {
1258            // Stop at the end of the first run so nested-set siblings later in
1259            // the tree (if hoisted) never extend the addressable range.
1260            if seen_effects {
1261                break;
1262            }
1263            continue;
1264        }
1265        seen_effects = true;
1266        let effects = effects_idx;
1267        effects_idx = effects_idx.saturating_add(1);
1268        for p in &child.properties {
1269            out.push(DeviceEvent::EffectsParamChanged {
1270                effects,
1271                param: EffectsParam::from_name(&p.name),
1272                value: p.value.clone(),
1273            });
1274        }
1275    }
1276
1277    // 9. GUI initial params (singleton). Same key-less shape as the other
1278    // singletons: emit every property the single front-panel UI-state node
1279    // carries as a typed GuiParamChanged.
1280    if let Some(node) = root.children.iter().find(|c| c.name == "GUI") {
1281        for p in &node.properties {
1282            out.push(DeviceEvent::GuiParamChanged {
1283                param: GuiParam::from_name(&p.name),
1284                value: p.value.clone(),
1285            });
1286        }
1287    }
1288
1289    // 10. SOUNDPADS initial params (multi-instance PADs nested inside the
1290    // container). Only the first contiguous run of PAD nodes is the addressable
1291    // pads; the counter stops at the first non-PAD child so any sibling node
1292    // inside the container never extends the addressable range. The ordinal in
1293    // the run is the pad index events and commands address.
1294    if let Some(soundpads) = root.children.iter().find(|c| c.name == "SOUNDPADS") {
1295        let mut pad_idx: u8 = 0;
1296        let mut seen_pad = false;
1297        for child in &soundpads.children {
1298            if child.name != "PAD" {
1299                if seen_pad {
1300                    break;
1301                }
1302                continue;
1303            }
1304            seen_pad = true;
1305            let pad = pad_idx;
1306            pad_idx = pad_idx.saturating_add(1);
1307            for p in &child.properties {
1308                out.push(DeviceEvent::PadParamChanged {
1309                    pad,
1310                    param: PadParam::from_name(&p.name),
1311                    value: p.value.clone(),
1312                });
1313            }
1314        }
1315    }
1316
1317    // 11. SYSTEM initial params (singleton). Same key-less shape as the other
1318    // singletons: emit every property the single device-wide state node carries
1319    // as a typed SystemParamChanged (identity, update lifecycle, date/time,
1320    // disables, USB/storage/sharing status). `boardType` surfaces here too, the
1321    // same value `Layout::detect_model` reads to pick the device model.
1322    if let Some(node) = root.children.iter().find(|c| c.name == "SYSTEM") {
1323        for p in &node.properties {
1324            out.push(DeviceEvent::SystemParamChanged {
1325                param: SystemParam::from_name(&p.name),
1326                value: p.value.clone(),
1327            });
1328        }
1329    }
1330
1331    out
1332}
1333
1334fn int_prop(node: &Node, name: &str) -> Option<i64> {
1335    node.properties
1336        .iter()
1337        .find(|p| p.name == name)
1338        .and_then(|p| p.value.as_int())
1339}
1340
1341fn bool_prop(node: &Node, name: &str) -> Option<bool> {
1342    node.properties
1343        .iter()
1344        .find(|p| p.name == name)
1345        .and_then(|p| p.value.as_bool())
1346}
1347
1348fn string_prop<'a>(node: &'a Node, name: &str) -> Option<&'a str> {
1349    node.properties
1350        .iter()
1351        .find(|p| p.name == name)
1352        .and_then(|p| match &p.value {
1353            Value::String(s) => Some(s.as_str()),
1354            _ => None,
1355        })
1356}
1357
1358#[cfg(test)]
1359#[path = "events_tests.rs"]
1360mod tests;