Skip to main content

core_events/
core_events.rs

1// Observing changes to the openDAQ core structure through the core event.
2//
3// The context's core event fires on every change within the component tree:
4// property value changes, component additions and removals, signal
5// connections, and more.  This example subscribes a closure, watches it
6// report two property writes, then unsubscribes.
7
8use opendaq::{Channel, CoreEventArgs, Instance};
9
10fn main() -> opendaq::Result<()> {
11    let instance = Instance::new()?;
12    instance.add_device("daqref://device0")?;
13
14    let channel = instance
15        .find_component("Dev/RefDev0/IO/AI/RefCh0")?
16        .expect("reference channel not found")
17        .cast::<Channel>()?;
18
19    let core_event = instance
20        .context()?
21        .expect("context")
22        .on_core_event()?
23        .expect("core event");
24
25    // The handler may run on openDAQ's own threads.  Its args come in as a
26    // generic object; cast to CoreEventArgs for the event name and the
27    // per-event-type parameters ("Name" holds the changed property's name).
28    let handler = core_event.subscribe(|_sender, args| {
29        let Some(args) = args else { return };
30        let Ok(event) = args.cast::<CoreEventArgs>() else {
31            return;
32        };
33        let name = event.event_name().unwrap_or_default();
34        let parameters = event.parameters().unwrap_or_default();
35        let changed = parameters
36            .get("Name")
37            .map(ToString::to_string)
38            .unwrap_or_default();
39        println!("  {name}: {changed}");
40    })?;
41
42    // While subscribed, each property change is reported by the handler above.
43    println!("subscribed:");
44    channel.set_property_value("Frequency", 25.0)?;
45    channel.set_property_value("Amplitude", 7.5)?;
46
47    // Unsubscribing removes the handler; further changes fire nothing.
48    core_event.unsubscribe(&handler)?;
49    println!("unsubscribed (no lines expected below):");
50    channel.set_property_value("Frequency", 50.0)?;
51
52    Ok(())
53}