Skip to main content

mx_remote/
event.rs

1// Author: Lars Op den Kamp (lars@opdenkamp-it.nl)
2// Copyright (c) 2026 Op den Kamp IT Solutions
3
4//! Events and the handler that receives them.
5
6use crate::types::*;
7use crate::wire::{
8    BayUid, DeviceUid, EdidProfile, LinkFeature, RcAction, RcKey, RcType, V2ipFpgaFeature,
9};
10
11/// Declares the event set.
12///
13/// One declaration produces the [`Event`] enum, the [`EventHandler`] trait and
14/// the dispatch that connects them, so a new event cannot reach the enum
15/// without reaching the trait, and cannot be dispatched without fanning in to
16/// the generic update. The fan-in is written once here rather than repeated at
17/// each call site.
18///
19/// The section an event is declared in decides what it fans in to: `device`
20/// events reach `on_device_update`, `bay` events reach `on_bay_update`, and
21/// `bay_and_device` events reach both. A link change concerns the bay and the
22/// device that owns it, which is why it is neither of the first two.
23macro_rules! events {
24    (
25        device {
26            $( $(#[$dmeta:meta])* $dvariant:ident => $dmethod:ident ( $($darg:ident : $dty:ty),* ); )*
27        }
28        bay {
29            $( $(#[$bmeta:meta])* $bvariant:ident => $bmethod:ident ( $($barg:ident : $bty:ty),* ); )*
30        }
31        bay_and_device {
32            $( $(#[$lmeta:meta])* $lvariant:ident => $lmethod:ident ( $($larg:ident : $lty:ty),* ); )*
33        }
34    ) => {
35        /// Something that changed, or a request that arrived.
36        ///
37        /// Events are collected while the state lock is held and dispatched
38        /// after it is released, so a handler may call back into the library.
39        #[derive(Clone, Debug, PartialEq)]
40        #[non_exhaustive]
41        pub enum Event {
42            $(
43                $(#[$dmeta])*
44                $dvariant {
45                    /// The device the event concerns.
46                    device: DeviceUid,
47                    $( #[allow(missing_docs)] $darg: $dty, )*
48                },
49            )*
50            $(
51                $(#[$bmeta])*
52                $bvariant {
53                    /// The bay the event concerns.
54                    bay: BayUid,
55                    $( #[allow(missing_docs)] $barg: $bty, )*
56                },
57            )*
58            $(
59                $(#[$lmeta])*
60                $lvariant {
61                    /// The bay the event concerns.
62                    bay: BayUid,
63                    $( #[allow(missing_docs)] $larg: $lty, )*
64                },
65            )*
66        }
67
68        /// Receives events.
69        ///
70        /// Every method has a no-op default, so an implementation names only
71        /// the events it cares about. Handlers run one at a time from the
72        /// thread that produced the event, with no lock held: calling back into
73        /// the library from one is safe, but blocking for long stalls the
74        /// receive path.
75        #[allow(unused_variables)]
76        pub trait EventHandler: Send + Sync {
77            $(
78                $(#[$dmeta])*
79                fn $dmethod(&self, device: DeviceUid $(, $darg: $dty)*) {}
80            )*
81            $(
82                $(#[$bmeta])*
83                fn $bmethod(&self, bay: BayUid $(, $barg: $bty)*) {}
84            )*
85            $(
86                $(#[$lmeta])*
87                fn $lmethod(&self, bay: BayUid $(, $larg: $lty)*) {}
88            )*
89
90            /// Fired after every device-level event above.
91            fn on_device_update(&self, device: DeviceUid) {}
92
93            /// Fired after every bay-level event above.
94            fn on_bay_update(&self, bay: BayUid) {}
95        }
96
97        impl Event {
98            /// Delivers this event to `handler`, then the generic update it
99            /// fans in to.
100            pub(crate) fn dispatch(self, handler: &dyn EventHandler) {
101                match self {
102                    $(
103                        Self::$dvariant { device $(, $darg)* } => {
104                            handler.$dmethod(device $(, $darg)*);
105                            handler.on_device_update(device);
106                        }
107                    )*
108                    $(
109                        Self::$bvariant { bay $(, $barg)* } => {
110                            handler.$bmethod(bay $(, $barg)*);
111                            handler.on_bay_update(bay);
112                        }
113                    )*
114                    $(
115                        Self::$lvariant { bay $(, $larg)* } => {
116                            handler.$lmethod(bay $(, $larg)*);
117                            handler.on_bay_update(bay);
118                            handler.on_device_update(bay.device);
119                        }
120                    )*
121                }
122            }
123        }
124    };
125}
126
127/// Ignores every event.
128///
129/// The handler a client that only reads state through [`Remote`] needs, since
130/// the trait is not optional and its methods all default to nothing.
131///
132/// [`Remote`]: crate::Remote
133impl EventHandler for () {}
134
135events! {
136    device {
137        /// The device's configuration changed.
138        DeviceConfigChanged => on_device_config_changed();
139        /// The device has reported every part of its configuration.
140        DeviceConfigComplete => on_device_config_complete();
141        /// The device started or stopped answering.
142        DeviceOnlineChanged => on_device_online_changed(online: bool);
143        /// The device reported new temperatures.
144        DeviceTemperatureChanged => on_device_temperature_changed(temperatures: Vec<u8>);
145        /// A firmware component reported its version.
146        FirmwareVersionChanged => on_firmware_version_changed(version: FirmwareVersion);
147        /// The device reported a system status.
148        SystemStatusChanged => on_system_status_changed(status: u16, message: String);
149        /// A network port reported its link state.
150        NetworkStatusChanged => on_network_status_changed(status: NetworkPortStatus);
151        /// The device reported V2IP statistics.
152        V2ipStatsChanged => on_v2ip_stats_changed(stats: V2ipDeviceStats);
153        /// The streams the device's source bays advertise changed.
154        V2ipSourcesChanged => on_v2ip_sources_changed(sources: Vec<V2ipStreamSources>);
155        /// The device's V2IP encoder configuration changed.
156        V2ipDetailsChanged => on_v2ip_details_changed(details: DeviceV2ipDetails);
157        /// The streams the device's sink is subscribed to changed. A request
158        /// addressed to it fires this too - see [`DeviceV2ipSink`].
159        V2ipSinkChanged => on_v2ip_sink_changed(sink: DeviceV2ipSink);
160        /// A multiviewer reported its state.
161        MultiviewerStatusChanged => on_multiviewer_status_changed(status: MultiviewerStatus);
162        /// The device reported a different audio endpoint tree, or an
163        /// endpoint's status changed.
164        AudioEndpointsChanged => on_audio_endpoints_changed(endpoints: AudioEndpoints);
165        /// The device reported its mesh master.
166        MeshMasterChanged => on_mesh_master_changed(master: DeviceUid);
167        /// The device reported its view of the mesh topology.
168        TopologyChanged => on_topology_changed(topology: Vec<TopologyEntry>);
169        /// A ProAmp8 reported its Dolby settings.
170        AmpDolbySettingsChanged => on_amp_dolby_settings_changed(settings: AmpDolbySettings);
171        /// Installer setup was completed or cleared.
172        SetupStatusChanged => on_setup_status_changed(completed: bool);
173        /// The installer id changed.
174        InstallerIdChanged => on_installer_id_changed(installer_id: u16);
175        /// The sink was told to show a window.
176        TilingChanged => on_tiling_changed(tiling: V2ipTilingConfig);
177        /// The device reported what its video processor supports.
178        V2ipFeaturesChanged => on_v2ip_features_changed(features: V2ipFpgaFeature);
179        /// The device's settings changed.
180        V2ipDeviceSettingsChanged => on_v2ip_device_settings_changed(settings: V2ipDeviceSettings);
181        /// The device reported a different VLAN configuration.
182        V2ipVlanChanged => on_v2ip_vlan_changed(vlan: V2ipVlan);
183        /// The sink reported its test card.
184        V2ipTestcardChanged => on_v2ip_testcard_changed(testcard: V2ipTestcard);
185        /// The device announced a different time zone for its mesh.
186        TimeZoneChanged => on_time_zone_changed(time_zone: TimeZone);
187        /// A source bay's remote-control configuration changed.
188        RcSettingsChanged => on_rc_settings_changed(settings: RcSettings);
189        /// A V2IP device was linked to a remote peer.
190        V2ipLinkChanged => on_v2ip_link_changed(target: DeviceUid);
191        /// A multiviewer command arrived.
192        MultiviewerCommand => on_multiviewer_command(command: MultiviewerCommand);
193        /// An audio endpoint was switched to a new source.
194        AudioSelectInput => on_audio_select_input(change: AudioChangeSource);
195        /// An audio endpoint was muted or unmuted.
196        AudioEndpointMute => on_audio_endpoint_mute(endpoint: u16, muted: bool);
197        /// An audio endpoint's trigger changed.
198        AudioEndpointTrigger => on_audio_endpoint_trigger(endpoint: u16, active: bool);
199        /// An audio endpoint's source was locked or unlocked.
200        AudioEndpointLock => on_audio_endpoint_lock(endpoint: u16, locked: bool);
201        /// An audio endpoint's volume changed.
202        AudioEndpointVolume => on_audio_endpoint_volume(endpoint: u16, volume: u32);
203        /// A peer asked every device to announce itself.
204        DiscoverRequest => on_discover_request();
205        /// A peer asked a device to switch a sink.
206        SetRouteRequested => on_set_route_requested(request: SetRouteRequest);
207        /// A peer asked a device for its EDID.
208        EdidRequested => on_edid_requested(request: EdidRequest);
209        /// A device answered with its EDID.
210        EdidReceived => on_edid_received(edid: EdidRecord);
211        /// A peer asked a device to rename a bay.
212        BayNameChangeRequested => on_bay_name_change_requested(change: BayNameChange);
213        /// A peer asked a device to switch its EDID profile.
214        EdidProfileChangeRequested => on_edid_profile_change_requested(change: EdidProfileChange);
215        /// A peer asked a device to reboot.
216        RebootRequested => on_reboot_requested(request: RebootRequest);
217        /// A peer asked devices to factory-reset.
218        FactoryResetRequested => on_factory_reset_requested(request: FactoryResetRequest);
219        /// A device sent its monitoring pulse.
220        MonitoringPulse => on_monitoring_pulse();
221        /// A peer asked a device to upgrade its FPGA.
222        UpgradeFpgaRequested => on_upgrade_fpga_requested();
223        /// A peer asked a device to re-detect its bays.
224        DetectBaysRequested => on_detect_bays_requested();
225        /// A peer asked a sink to enter or leave power save.
226        PowerSaveRequested => on_power_save_requested(request: V2ipPowerSaveRequest);
227        /// A peer asked a device to send a remote-control key.
228        KeyTransmitRequested => on_key_transmit_requested(request: KeyTransmitRequest);
229        /// A peer asked a device to perform a remote-control action.
230        ActionTransmitRequested => on_action_transmit_requested(request: ActionTransmitRequest);
231        /// A peer asked a device to blast raw infrared.
232        IrTransmitRequested => on_ir_transmit_requested(request: IrTransmitRequest);
233        /// A device was added to or removed from the source blacklist.
234        BlacklistChanged => on_blacklist_changed(change: V2ipBlacklistChange);
235        /// A video wall command arrived.
236        VideoWallCommand => on_video_wall_command(command: VideoWallCommand);
237    }
238    bay {
239        /// A bay was seen for the first time.
240        BayRegistered => on_bay_registered();
241        /// The bay's routed video source changed.
242        VideoSourceChanged => on_video_source_changed(source: Option<BayUid>);
243        /// The bay's routed audio source changed.
244        AudioSourceChanged => on_audio_source_changed(source: Option<BayUid>);
245        /// The bay's volume or mute state changed.
246        VolumeChanged => on_volume_changed(volume: VolumeMuteStatus);
247        /// The attached device's power state changed.
248        PowerChanged => on_power_changed(power: PowerStatus);
249        /// The bay was renamed.
250        NameChanged => on_name_changed(name: String);
251        /// A signal appeared or disappeared.
252        SignalDetectedChanged => on_signal_detected_changed(detected: bool);
253        /// The bay started or stopped reporting a fault.
254        FaultyChanged => on_faulty_changed(faulty: bool);
255        /// The bay was hidden or shown.
256        HiddenChanged => on_hidden_changed(hidden: bool);
257        /// Power over Ethernet started or stopped supplying the bay.
258        PoePoweredChanged => on_poe_powered_changed(powered: bool);
259        /// The HDBaseT link came up or went down.
260        HdbtConnectedChanged => on_hdbt_connected_changed(connected: bool);
261        /// The signal format description changed.
262        SignalTypeChanged => on_signal_type_changed(signal_type: String);
263        /// Hot-plug detect was asserted or released.
264        HpdDetectedChanged => on_hpd_detected_changed(detected: bool);
265        /// A CEC device answered or stopped answering.
266        CecDetectedChanged => on_cec_detected_changed(detected: bool);
267        /// The audio return channel changed.
268        ArcChanged => on_arc_changed(arc: ArcStatus);
269        /// The input's EDID profile changed.
270        EdidProfileChanged => on_edid_profile_changed(profile: EdidProfile);
271        /// The input's remote-control type changed.
272        RcTypeChanged => on_rc_type_changed(rc_type: RcType);
273        /// A remote-control key was pressed on the bay.
274        KeyPressed => on_key_pressed(key: RcKey);
275        /// A remote-control action was received on the bay.
276        ActionReceived => on_action_received(action: RcAction);
277        /// The bay started or stopped mirroring another output.
278        MirrorStatusChanged => on_mirror_status_changed(mirror: BayMirrorStatus);
279        /// A ProAmp8 zone's settings changed.
280        AmpZoneSettingsChanged => on_amp_zone_settings_changed(settings: AmpZoneSettings);
281        /// A volume step was requested on the bay.
282        VolumeStep => on_volume_step(up: bool);
283        /// The bay detected audio clipping.
284        AudioClipped => on_audio_clip(clip: AudioClip);
285        /// Raw infrared was captured on the bay.
286        IrCaptured => on_ir_captured(capture: IrCapture);
287        /// The devices filtered out of this sink's picker changed.
288        FilteredDevicesChanged => on_filtered_devices_changed(filtered: Vec<DeviceUid>);
289        /// The audio endpoint the bay carries changed.
290        AudioEndpointChanged => on_audio_endpoint_changed(endpoint: u8);
291        /// The bay's V2IP encoder was enabled or disabled.
292        EncoderDisabledChanged => on_encoder_disabled_changed(disabled: bool);
293        /// The bay's V2IP decoder was enabled or disabled.
294        DecoderDisabledChanged => on_decoder_disabled_changed(disabled: bool);
295    }
296    bay_and_device {
297        /// The bay was linked to a bay on another device.
298        ///
299        /// `linked_serial` is the serial of the device at the other end of the
300        /// link, and `bay_name` the name of the bay whose link record changed:
301        /// this bay on the device that reported the change, and the far bay on
302        /// its peer. Both ends are told, so both fire.
303        BayLinked => on_bay_linked(linked_serial: String, bay_name: String, features: LinkFeature);
304        /// The bay's link to another device was removed.
305        ///
306        /// The arguments describe the link that was removed, and mean what
307        /// they do on [`Event::BayLinked`].
308        BayUnlinked => on_bay_unlinked(linked_serial: String, bay_name: String);
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315    use std::sync::Mutex;
316
317    #[derive(Default)]
318    struct Recorder {
319        calls: Mutex<Vec<String>>,
320    }
321
322    impl Recorder {
323        fn record(&self, what: &str) {
324            if let Ok(mut calls) = self.calls.lock() {
325                calls.push(what.to_owned());
326            }
327        }
328
329        fn calls(&self) -> Vec<String> {
330            self.calls.lock().map(|c| c.clone()).unwrap_or_default()
331        }
332    }
333
334    impl EventHandler for Recorder {
335        fn on_power_changed(&self, _bay: BayUid, power: PowerStatus) {
336            self.record(&format!("power={power}"));
337        }
338
339        fn on_setup_status_changed(&self, _device: DeviceUid, completed: bool) {
340            self.record(&format!("setup={completed}"));
341        }
342
343        fn on_bay_update(&self, _bay: BayUid) {
344            self.record("bay_update");
345        }
346
347        fn on_device_update(&self, _device: DeviceUid) {
348            self.record("device_update");
349        }
350    }
351
352    const DEVICE: DeviceUid = DeviceUid::from_array([9; 16]);
353
354    #[test]
355    fn a_bay_event_fires_its_own_method_then_the_generic_bay_update() {
356        let recorder = Recorder::default();
357        Event::PowerChanged {
358            bay: BayUid::new(DEVICE, 3),
359            power: PowerStatus::On,
360        }
361        .dispatch(&recorder);
362        assert_eq!(recorder.calls(), ["power=on", "bay_update"]);
363    }
364
365    #[test]
366    fn a_device_event_fires_its_own_method_then_the_generic_device_update() {
367        let recorder = Recorder::default();
368        Event::SetupStatusChanged {
369            device: DEVICE,
370            completed: true,
371        }
372        .dispatch(&recorder);
373        assert_eq!(recorder.calls(), ["setup=true", "device_update"]);
374    }
375
376    #[test]
377    fn a_link_event_fires_both_generic_updates() {
378        let recorder = Recorder::default();
379        Event::BayUnlinked {
380            bay: BayUid::new(DEVICE, 3),
381            linked_serial: "AB1234".to_owned(),
382            bay_name: "Output 1".to_owned(),
383        }
384        .dispatch(&recorder);
385        assert_eq!(recorder.calls(), ["bay_update", "device_update"]);
386    }
387
388    #[test]
389    fn an_event_a_handler_does_not_name_still_fires_the_generic_update() {
390        let recorder = Recorder::default();
391        Event::MonitoringPulse { device: DEVICE }.dispatch(&recorder);
392        assert_eq!(
393            recorder.calls(),
394            ["device_update"],
395            "the default no-op must not swallow the fan-in"
396        );
397    }
398}