Skip to main content

ServerCapabilityConfig

Struct ServerCapabilityConfig 

Source
pub struct ServerCapabilityConfig(/* private fields */);
Expand description

Wrapper over the openDAQ daqServerCapabilityConfig interface.

Implementations§

Source§

impl ServerCapabilityConfig

Source

pub fn add_address(&self, address: &str) -> Result<()>

Sets the device’s address

§Returns
  • address: The device’s address

Calls the openDAQ C function daqServerCapabilityConfig_addAddress().

Source

pub fn add_address_info(&self, address_info: &AddressInfo) -> Result<()>

Calls the openDAQ C function daqServerCapabilityConfig_addAddressInfo().

Source

pub fn add_connection_string(&self, connection_string: &str) -> Result<()>

Sets the connection string of device with current protocol

§Parameters
  • connection_string: The connection string of device

Calls the openDAQ C function daqServerCapabilityConfig_addConnectionString().

Source

pub fn server_capability( protocol_id: &str, protocol_name: &str, protocol_type: ProtocolType, ) -> Result<ServerCapabilityConfig>

Calls the openDAQ C function daqServerCapabilityConfig_createServerCapability().

Source

pub fn set_connection_string(&self, connection_string: &str) -> Result<()>

Sets the connection string of device with current protocol

§Parameters
  • connection_string: The connection string of device

Calls the openDAQ C function daqServerCapabilityConfig_setConnectionString().

Source

pub fn set_connection_type(&self, type_: &str) -> Result<()>

Sets the type of connection

§Parameters
  • type: The type of connection

Calls the openDAQ C function daqServerCapabilityConfig_setConnectionType().

Source

pub fn set_core_events_enabled(&self, enabled: bool) -> Result<()>

Sets the boolean flag indicating whether the server capability supports core event propagation to clients

§Parameters
  • enabled: True if core events are enabled; false otherwise

Calls the openDAQ C function daqServerCapabilityConfig_setCoreEventsEnabled().

Source

pub fn set_port(&self, port: i64) -> Result<()>

Sets the port of the device

§Parameters
  • port: The port of the device

Calls the openDAQ C function daqServerCapabilityConfig_setPort().

Source

pub fn set_prefix(&self, prefix: &str) -> Result<()>

Sets the prefix of the connection string (eg. “daq.nd” or “daq.opcua”)

§Parameters
  • prefix: The connection string prefix

Calls the openDAQ C function daqServerCapabilityConfig_setPrefix().

Source

pub fn set_protocol_id(&self, protocol_id: &str) -> Result<()>

Sets the ID of protocol

§Parameters
  • protocol_id: The ID of protocol

Calls the openDAQ C function daqServerCapabilityConfig_setProtocolId().

Source

pub fn set_protocol_name(&self, protocol_name: &str) -> Result<()>

Sets the name of protocol

§Parameters
  • protocol_name: The name of protocol

Calls the openDAQ C function daqServerCapabilityConfig_setProtocolName().

Source

pub fn set_protocol_type(&self, type_: ProtocolType) -> Result<()>

Sets the type of protocol

§Parameters
  • type: The type of protocol

Calls the openDAQ C function daqServerCapabilityConfig_setProtocolType().

Source

pub fn set_protocol_version(&self, version: &str) -> Result<()>

Sets the protocol version

§Parameters
  • version: The protocol version

Calls the openDAQ C function daqServerCapabilityConfig_setProtocolVersion().

Methods from Deref<Target = ServerCapability>§

Source

pub fn address_info(&self) -> Result<Vec<AddressInfo>>

Gets the list of address information objects.

§Returns
  • address_info: The list of address information objects. Address information duplicates the connection string and address as available on the Server Capability object. Additionally, it provides information on what type of address it is (e.g., IPv4, IPv6), as well as whether the address is reachable.

Calls the openDAQ C function daqServerCapability_getAddressInfo().

Source

pub fn addresses(&self) -> Result<Vec<String>>

Gets the device’s list of addresses with the current protocol.

§Returns
  • addresses: The device’s list of addresses (hosts)

Calls the openDAQ C function daqServerCapability_getAddresses().

Source

pub fn connection_string(&self) -> Result<String>

Gets the connection string of the device with the current protocol.

§Returns
  • connection_string: The connection string of the device (URL to connect).

Calls the openDAQ C function daqServerCapability_getConnectionString().

Source

pub fn connection_strings(&self) -> Result<Vec<String>>

Gets the connection string of the device with the current protocol.

§Returns
  • connection_strings: The connection string of the device (URL to connect).

Calls the openDAQ C function daqServerCapability_getConnectionStrings().

Source

pub fn connection_type(&self) -> Result<String>

Gets the type of connection supported by the device.

§Returns
  • type: The type of connection (e.g., “TCP/IP”).

Calls the openDAQ C function daqServerCapability_getConnectionType().

Source

pub fn core_events_enabled(&self) -> Result<bool>

Gets the client update method supported by the device.

§Returns
  • enabled: The client update method (Boolean value indicating if core events are enabled for communication between server and client device).

Calls the openDAQ C function daqServerCapability_getCoreEventsEnabled().

Source

pub fn port(&self) -> Result<Option<i64>>

Gets the port of the device with the current protocol.

§Returns
  • port: The port of the device.

Calls the openDAQ C function daqServerCapability_getPort().

Source

pub fn prefix(&self) -> Result<String>

Gets the prefix of the connection string (eg. “daq.nd” or “daq.opcua”)

§Parameters
  • prefix: The connection string prefix

Calls the openDAQ C function daqServerCapability_getPrefix().

Source

pub fn protocol_id(&self) -> Result<String>

Gets the id of the protocol supported by the device. Should not contain spaces or special characters except for ‘_’ and ‘-’.

§Returns
  • protocol_id: The id of the protocol.

Calls the openDAQ C function daqServerCapability_getProtocolId().

Source

pub fn protocol_name(&self) -> Result<String>

Gets the name of the protocol supported by the device.

§Returns
  • protocol_name: The name of the protocol (e.g., “OpenDAQNativeStreaming”, “OpenDAQOPCUA”, “OpenDAQLTStreaming”).

Calls the openDAQ C function daqServerCapability_getProtocolName().

Source

pub fn protocol_type(&self) -> Result<ProtocolType>

Gets the type of protocol supported by the device.

§Returns
  • type: The type of protocol (Enumeration value reflecting protocol type: “ConfigurationAndStreaming”, “Configuration”, “Streaming”, “Unknown”).

Calls the openDAQ C function daqServerCapability_getProtocolType().

Source

pub fn protocol_version(&self) -> Result<String>

Gets the protocol version supported by the device’s protocol.

§Returns
  • version: The protocol version.

Calls the openDAQ C function daqServerCapability_getProtocolVersion().

Methods from Deref<Target = PropertyObject>§

Source

pub fn add_property(&self, property: &Property) -> Result<()>

Adds the property to the Property object.

§Parameters
  • property: The property to be added.
§Errors
  • OPENDAQ_ERR_INVALIDVALUE: if the property has no name.
  • OPENDAQ_ERR_ALREADYEXISTS: if a property with the same name is already part of the Property object.
  • OPENDAQ_ERR_FROZEN: if the Property object is frozen. The Property is frozen once added to the Property object, making it immutable. The same Property cannot be added to multiple different Property objects.

Calls the openDAQ C function daqPropertyObject_addProperty().

Examples found in repository?
examples/download_log_files.rs (line 38)
19fn main() -> opendaq::Result<()> {
20    let work_dir = std::env::temp_dir().join("opendaq-rs-log-example");
21    let downloads = work_dir.join("downloads");
22    fs::create_dir_all(&downloads).expect("create working directories");
23    let device_log = work_dir.join("ref_device_simulator.log");
24    let device_log_path = device_log.to_string_lossy().into_owned();
25
26    // Start from a clean log so the reported size reflects only this run.
27    let _ = fs::remove_file(&device_log);
28
29    let builder = InstanceBuilder::new()?;
30    // Find the bundled modules.
31    let modules = opendaq::native_library_directory().expect("bundled native modules");
32    builder.set_module_path(&modules.to_string_lossy())?;
33    builder.add_logger_sink(&LoggerSink::basic_file(&device_log_path)?)?;
34    let instance = Instance::from_builder(&builder)?;
35
36    // The reference device reads these two properties from its add-device config.
37    let config = PropertyObject::new()?;
38    config.add_property(&Property::bool("EnableLogging", true, true)?)?;
39    config.add_property(&Property::string("LoggingPath", &device_log_path, true)?)?;
40
41    let device = instance
42        .add_device_with("daqref://device0", Some(&config))?
43        .expect("reference device");
44
45    // Flush the logger so everything buffered so far is actually on disk
46    // before we read it.
47    let context = instance.context()?.expect("instance context");
48    context.logger()?.expect("instance logger").flush()?;
49
50    let infos = device.log_file_infos()?;
51    if infos.is_empty() {
52        println!("Device exposes no log files.");
53        return Ok(());
54    }
55    println!("Device exposes {} log file(s):", infos.len());
56    println!();
57    for info in infos {
58        let id = info.id()?;
59        let destination = downloads.join(info.name()?);
60        println!("- {}", info.name()?);
61        println!("    id:            {id}");
62        println!("    size:          {} bytes", info.size()?);
63        println!("    encoding:      {}", info.encoding()?);
64        println!("    last-modified: {}", info.last_modified()?);
65        // Size/offset let you fetch just part of a file; here, a short head preview.
66        println!("    preview:       {:?}", device.log_with(&id, 60, 0)?);
67        // Plain `log` fetches the whole file in one call.
68        let content = device.log(&id)?;
69        fs::write(&destination, &content).expect("write the downloaded log");
70        println!(
71            "    downloaded {} chars -> {}",
72            content.len(),
73            destination.display()
74        );
75        println!();
76    }
77    Ok(())
78}
Source

pub fn begin_update(&self) -> Result<()>

Begins batch configuration of the object. Batched configuration is used to apply several settings at once. To begin batch configuration, call beginUpdate. When the setPropertyValue is called on the object, the changes are not immediately applied to it. When endUpdate is called, the property values set between the beginUpdate and endUpdate method calls are applied. It triggers the ˙OnPropertyWriteEventfor each property value set, and theOnEndUpdateevent.beginUpdate` is called recursively for each child property object.

Calls the openDAQ C function daqPropertyObject_beginUpdate().

Source

pub fn clear_property_value(&self, property_name: &str) -> Result<()>

Clears the Property value from the Property object

§Parameters
  • property_name: The name of the Property of which value should be cleared.
§Errors
  • OPENDAQ_ERR_NOTFOUND: if a Property with given propertyName is not part of the Property object.
  • OPENDAQ_ERR_FROZEN: if the Property object is frozen. When a Property value is set, the value is written in the internal dictionary of Property values. This function will remove said value from the dictionary. If the tries to obtain the Property value of a property that does not have a set Property value, then the default value is returned. Importantly, clearing the value of an Object-type property will call clear on all the child object’s properties.

Calls the openDAQ C function daqPropertyObject_clearPropertyValue().

Source

pub fn clear_property_values(&self) -> Result<()>

Clears values of all properties contained in the Property object, including nested child properties. This function clears the values by internally invoking clearPropertyValue(...) for all properties returned by getAllProperties(); for object-type properties it therefore clears their child properties as well. Read-only properties and frozen objects are skipped.

Calls the openDAQ C function daqPropertyObject_clearPropertyValues().

Source

pub fn end_update(&self) -> Result<()>

Ends batch configuration of the object. Batched configuration is used to apply several settings at once. To begin batch configuration, call beginUpdate. When the setPropertyValue is called on the object, the changes are not immediately applied to it. When endUpdate is called, the property values set between the beginUpdate and endUpdate method calls are applied. It triggers the ˙OnPropertyWriteEventfor each property value set, and theOnEndUpdateevent.endUpdate` is called recursively for each child property object.

Calls the openDAQ C function daqPropertyObject_endUpdate().

Source

pub fn find_properties( &self, property_filter: &SearchFilter, ) -> Result<Vec<Property>>

Retrieves a list of properties from the Property object that match the given property filter.

§Parameters
  • property_filter: A filter used to select relevant properties. Can include a recursive wrapper to search thru nested property objects.
  • component_filter: An optional filter to determine which components’ properties are included in the search. A recursive wrapper can be used to enable tree-traversal search.
§Returns
  • properties: The list containing the matching properties. If the propertyFilter is nullptr, only the visible properties directly associated with the current object are retrieved. When searching for properties within a component, if no componentFilter is provided, only the current component is searched. If a componentFilter is provided but the current component does not match it, the result will be an empty list.

Calls the openDAQ C function daqPropertyObject_findProperties().

Source

pub fn find_properties_with( &self, property_filter: &SearchFilter, component_filter: Option<&SearchFilter>, ) -> Result<Vec<Property>>

Retrieves a list of properties from the Property object that match the given property filter.

§Parameters
  • property_filter: A filter used to select relevant properties. Can include a recursive wrapper to search thru nested property objects.
  • component_filter: An optional filter to determine which components’ properties are included in the search. A recursive wrapper can be used to enable tree-traversal search.
§Returns
  • properties: The list containing the matching properties. If the propertyFilter is nullptr, only the visible properties directly associated with the current object are retrieved. When searching for properties within a component, if no componentFilter is provided, only the current component is searched. If a componentFilter is provided but the current component does not match it, the result will be an empty list.

Calls the openDAQ C function daqPropertyObject_findProperties().

Source

pub fn all_properties(&self) -> Result<Vec<Property>>

Returns a list of all properties contained in the Property object.

§Returns
  • properties: The List of properties. Properties are retrieved regardless of their visibility. They are sorted in insertion order unless a custom order is specified. This function returns both the properties added to the Property object, as well as those of its class.

Calls the openDAQ C function daqPropertyObject_getAllProperties().

Source

pub fn class_name(&self) -> Result<String>

Gets the name of the class the Property object was constructed with.

§Returns
  • class_name: The class’s name. Contains an empty string if the class name is not configured. A Property object inherits all properties of the Property object class of the same name. Such Property objects have access to the Type manager from which they can retrieve its class type and its properties.

Calls the openDAQ C function daqPropertyObject_getClassName().

Source

pub fn on_any_property_value_read(&self) -> Result<Option<Event>>

Gets the Event that is triggered whenever any Property value is read.The event is triggered after the specific Property event.

§Returns
  • event: The read Event. A handler can be added to the event containing a callback function which is invoked whenever the event is triggered. The callback function requires two parameters - a Property object, as well as a “Property value event args” object. The callback will be invoked with the Property object holding the read value as the first argument. The second argument holds an event args object that contains the read Property value, event type (Read), and a method of overriding the read value. If the read value is overridden, the overridden value is read instead.

Calls the openDAQ C function daqPropertyObject_getOnAnyPropertyValueRead().

Source

pub fn on_any_property_value_write(&self) -> Result<Option<Event>>

Gets the Event that is triggered whenever any Property value is written. The event is triggered after the specific Property event.

§Returns
  • event: The write Event. A handler can be added to the event containing a callback function which is invoked whenever the event is triggered. The callback function requires two parameters - a Property object, as well as a “Property value event args” object. The callback will be invoked with the Property object holding the written-to property as the first argument The second argument holds an event args object that contains the written value, event type (Update), and a method of overriding the written value. If the written value is overridden, the overridden value is stored in the Property object instead.

Calls the openDAQ C function daqPropertyObject_getOnAnyPropertyValueWrite().

Source

pub fn on_end_update(&self) -> Result<Option<Event>>

Gets the Event that is triggered whenever the batch configuration is applied.

§Returns
  • event: The Event. A handler can be added to the event containing a callback function which is invoked whenever the event is triggered. The callback function requires one parameter - a “End update value event args” object. The callback will be invoked with the batch configuration is applied, i.e. from the endUpdate method. The first argument holds an event args object that contains a list of properties updated.

Calls the openDAQ C function daqPropertyObject_getOnEndUpdate().

Source

pub fn on_property_value_read( &self, property_name: &str, ) -> Result<Option<Event>>

Gets the Event that is triggered whenever a Property value of a Property named propertyName is read.

§Parameters
  • property_name: The name of the property.
§Returns
  • event: The read Event.
§Errors
  • OPENDAQ_ERR_NOTFOUND: if the Property object does not contain a Property named propertyName. A handler can be added to the event containing a callback function which is invoked whenever the event is triggered. The callback function requires two parameters - a Property object, as well as a “Property value event args” object. The callback will be invoked with the Property object holding the read value as the first argument. The second argument holds an event args object that contains the read Property value, event type (Read), and a method of overriding the read value. If the read value is overridden, the overridden value is read instead.

Calls the openDAQ C function daqPropertyObject_getOnPropertyValueRead().

Source

pub fn on_property_value_write( &self, property_name: &str, ) -> Result<Option<Event>>

Gets the Event that is triggered whenever a Property value is written to the Property named propertyName.

§Parameters
  • property_name: The name of the property.
§Returns
  • event: The write Event.
§Errors
  • OPENDAQ_ERR_NOTFOUND: if the Property object does not contain a Property named propertyName. A handler can be added to the event containing a callback function which is invoked whenever the event is triggered. The callback function requires two parameters - a Property object, as well as a “Property value event args” object. The callback will be invoked with the Property object holding the written-to property as the first argument The second argument holds an event args object that contains the written value, event type (Update), and a method of overriding the written value. If the written value is overridden, the overridden value is stored in the Property object instead.

Calls the openDAQ C function daqPropertyObject_getOnPropertyValueWrite().

Examples found in repository?
examples/smoke.rs (line 64)
7fn main() -> opendaq::Result<()> {
8    let instance = Instance::new()?;
9
10    println!("Available devices:");
11    for info in instance.available_devices()? {
12        println!(" - {}: {}", info.connection_string()?, info.name()?);
13    }
14
15    let device = instance.add_device("daqref://device0")?.expect("device");
16    println!("Added device: {}", device.name()?);
17
18    let channel = instance
19        .find_component("Dev/RefDev0/IO/AI/RefCh0")?
20        .expect("reference channel not found")
21        .cast::<Channel>()?;
22    let signal = &channel.signals()?[0];
23
24    // Batched property updates.
25    {
26        let batch = BatchedPropertyUpdate::new(&[&device, &channel])?;
27        device.set_property_value("GlobalSampleRate", 1000)?;
28        channel.set_property_value("Frequency", 50.0)?;
29        batch.commit()?;
30    }
31    println!(
32        "GlobalSampleRate = {}",
33        device.property_value("GlobalSampleRate")?
34    );
35
36    // Stream reading with domain + tick conversion.
37    let reader = StreamReader::<f64>::new(signal)?;
38    let (samples, ticks) = reader.read_with_domain(100, 2000)?;
39    println!(
40        "read {} samples, {} ticks",
41        samples.sample_count(),
42        ticks.len()
43    );
44    let converter = TickConverter::from_signal(signal)?;
45    if let Some(first) = ticks.first() {
46        println!(
47            "first tick {} -> {:?}",
48            first,
49            converter.tick_to_system_time(*first)
50        );
51    }
52
53    // Callables: a Rust closure as an openDAQ function, called through openDAQ.
54    let sum = FunctionObject::from_fn(|args| {
55        let a = args[0].as_i64().unwrap_or(0);
56        let b = args[1].as_i64().unwrap_or(0);
57        Ok(Value::from(a + b))
58    })?;
59    let result = sum.call(&[Value::from(20), Value::from(22)])?;
60    println!("sum(20, 22) = {result}");
61
62    // Events: subscribe to property changes on the channel.
63    let events = channel
64        .on_property_value_write("Amplitude")?
65        .expect("event");
66    let handler = events.subscribe(|_sender, args| {
67        if let Some(args) = args {
68            println!("  event fired: {args}");
69        }
70    })?;
71    channel.set_property_value("Amplitude", 2.5)?;
72    events.unsubscribe(&handler)?;
73    channel.set_property_value("Amplitude", 1.0)?;
74    println!("Amplitude = {}", channel.property_value("Amplitude")?);
75
76    Ok(())
77}
Source

pub fn permission_manager(&self) -> Result<Option<PermissionManager>>

Gets the permission manager of property object.

§Returns
  • permission_manager: The permission manager of property object.

Calls the openDAQ C function daqPropertyObject_getPermissionManager().

Source

pub fn property(&self, property_name: &str) -> Result<Option<Property>>

Gets the Property with the given propertyName.

§Parameters
  • property_name: The name of the property.
§Returns
  • property: The retrieved Property.
§Errors
  • OPENDAQ_ERR_NOTFOUND: if the Property object does not contain the requested Property. The property is obtained from either the Property object class of the Property object, or the object’s local list of properties. The Property held by the object/class is not returned directly, but is instead cloned, and bound to the Property object. This allows for evaluation of Property metadata that depends on other properties of the Property object. For example, a Property’s visibility might depend on the value of another Property. To make evaluation of the visibility parameter possible, the Property must be able to access its owning Property object. Likewise, Reference properties always point at another Property of a Property object. Again, for this to be possible, the Property must be able to access its owning Property object, to be able to retrieve its referenced Property.

Calls the openDAQ C function daqPropertyObject_getProperty().

Examples found in repository?
examples/connect_view_only_client.rs (line 61)
47fn main() -> opendaq::Result<()> {
48    let instance = Instance::new()?;
49
50    let config = instance
51        .create_default_add_device_config()?
52        .expect("default add-device config");
53
54    // The "General" child object holds the protocol-independent options,
55    // ClientType among them; its selection values name the available modes.
56    let general = config
57        .property_value("General")?
58        .into_object()?
59        .cast::<PropertyObject>()?;
60    let client_type = general
61        .property("ClientType")?
62        .expect("ClientType property");
63    println!("Available ClientType options:");
64    if let Value::Dict(mut options) = client_type.selection_values()? {
65        options.sort_by_key(|(key, _)| key.as_i64());
66        for (key, name) in options {
67            println!("  {key} = {name}");
68        }
69    }
70
71    config.set_property_value("General.ClientType", 2)?; // 2 = view-only
72    let connection_string =
73        std::env::var("OPENDAQ_DEVICE").unwrap_or_else(|_| "daq.nd://127.0.0.1".into());
74
75    match instance.add_device_with(&connection_string, Some(&config)) {
76        Ok(Some(device)) => probe_view_only_device(&device)?,
77        Ok(None) => println!("Could not connect to {connection_string}: no device returned."),
78        Err(err) => {
79            println!("Could not connect to {connection_string}: {err}");
80            println!("Start an openDAQ device/simulator there, or set OPENDAQ_DEVICE.");
81        }
82    }
83    Ok(())
84}
More examples
Hide additional examples
examples/call_function_property.rs (line 51)
17fn main() -> opendaq::Result<()> {
18    let instance = Instance::new()?;
19    let device = instance.add_device("daqref://device0")?.expect("device");
20
21    let sum = function_property(&device, "Protected.Sum")?;
22    println!(
23        "Protected.Sum(7, 5)   = {}",
24        sum.call(&[Value::from(7), Value::from(5)])?
25    );
26    println!(
27        "Protected.Sum(40, 2)  = {}",
28        sum.call(&[Value::from(40), Value::from(2)])?
29    );
30    println!(
31        "Protected.Sum(100, 1) = {}",
32        function_property(&device, "Protected.Sum")?.call(&[Value::from(100), Value::from(1)])?
33    );
34
35    // SumList takes a single argument: a list of numbers.
36    let sum_list = function_property(&device, "Protected.SumList")?;
37    println!(
38        "Protected.SumList([1, 2, 3, 4]) = {}",
39        sum_list.call(&[Value::from(vec![1, 2, 3, 4])])?
40    );
41    println!(
42        "Protected.SumList([]) = {}",
43        sum_list.call(&[Value::List(Vec::new())])?
44    );
45
46    // `call` passes arguments straight through, and an implementation is free
47    // to ignore extras (the reference device's Sum does).  The declared
48    // signature lives in the property's callable info -- check the arity
49    // there before calling when it matters.
50    let info = device
51        .property("Protected.Sum")?
52        .expect("Sum property")
53        .callable_info()?
54        .expect("callable info");
55    let expected = info.arguments()?.len();
56    let args = [Value::from(1), Value::from(2), Value::from(3)];
57    if args.len() == expected {
58        println!("\nProtected.Sum(1, 2, 3) = {}", sum.call(&args)?);
59    } else {
60        println!(
61            "\nWrong arity is rejected: Protected.Sum expects {expected} arguments, got {}.",
62            args.len()
63        );
64    }
65    Ok(())
66}
Source

pub fn property_selection_value(&self, property_name: &str) -> Result<Value>

Gets the selected value of the Property, if the Property is a Selection property.

§Parameters
  • property_name: The name of the Property.
§Returns
  • value: The selected value.
§Errors
  • OPENDAQ_ERR_NOTFOUND: if a Property with given propertyName is not part of the Property object.
  • OPENDAQ_ERR_INVALIDPROPERTY: if the Property either has no Selection values, or the Selection values are not a list or dictionary.
  • OPENDAQ_ERR_INVALIDTYPE: if the retrieved value does not match the Property’s item type. This function serves as a shortcut to obtaining the Property value of a Property, and using it to retrieve the currently selected value from the Selection values of the Property. For example, if the Selection values contain the following list “[“banana”, “apple”, “pear”]“, and the corresponding Property value is set to 1, retrieving the Property selection value will return the string “apple”.

Calls the openDAQ C function daqPropertyObject_getPropertySelectionValue().

Source

pub fn property_value(&self, property_name: &str) -> Result<Value>

Gets the value of the Property with the given name.

§Parameters
  • property_name: The name of the Property.
§Returns
  • value: The returned Property value.
§Errors
  • OPENDAQ_ERR_NOTFOUND: if a property with given propertyName is not part of the Property object.
  • OPENDAQ_ERR_INVALIDPARAMETER: if attempting to get a value at an index of a non-list Property.
  • OPENDAQ_ERR_OUTOFRANGE: if attempting to get a value of a list Property at an out-of-bounds index. The value is retrieved from a local dictionary of Property values where they are stored when set. If a value is not present under the propertyName key, the default value of the corresponding Property is returned. If said property is not part of the Property object, an error occurs. @subsection value_get_child_property_objects Child Property objects The Property value getter allows for direct retrieval of values of child Property objects. To get the Property value of a child Property object, the propertyName parameter should be of the format: “childName.propertyName”. This pattern can also be used to access nested properties - for example “childName1.childName2.childName3.propertyName”. @subsection value_get_list_properties List properties If the requested Property is a list-type object, an item of the list at a selected index can be retrieved instead of the list itself. To do so, add a [index] suffix to the propertyName parameter. For example “ListProperty[1]” retrieves the 2nd item stored in the list Property value of the Property named “ListProperty”. @subsection value_get_selection_properties Selection properties If the requested Property has the Selection values fields configured, the Property value getter returns an index/key of the selected item in the Selection values list/dictionary.

Calls the openDAQ C function daqPropertyObject_getPropertyValue().

Examples found in repository?
examples/call_function_property.rs (line 12)
10fn function_property(device: &Device, name: &str) -> opendaq::Result<FunctionObject> {
11    device
12        .property_value(name)?
13        .into_object()?
14        .cast::<FunctionObject>()
15}
More examples
Hide additional examples
examples/batch_properties.rs (line 11)
7fn show_settings(label: &str, channel: &Channel) -> opendaq::Result<()> {
8    println!(
9        "{label} {}:  Amplitude={}  Frequency={}  Waveform={}",
10        channel.name()?,
11        channel.property_value("Amplitude")?,
12        channel.property_value("Frequency")?,
13        channel.property_value("Waveform")?
14    );
15    Ok(())
16}
examples/component_tree.rs (line 24)
17fn property_value_string(object: &PropertyObject, property: &Property) -> opendaq::Result<String> {
18    Ok(match property.value_type()? {
19        CoreType::Bool
20        | CoreType::Int
21        | CoreType::Float
22        | CoreType::String
23        | CoreType::Ratio
24        | CoreType::ComplexNumber => match object.property_value(&property.name()?)? {
25            Value::Str(text) => format!("{text:?}"),
26            value => value.to_string(),
27        },
28        other => format!("<{other:?}>"),
29    })
30}
examples/connect_view_only_client.rs (line 34)
27fn probe_view_only_device(device: &Device) -> opendaq::Result<()> {
28    println!("Connected to {} as a view-only client.", device.name()?);
29    println!("Visible signals: {}", device.signals_recursive()?.len());
30    match first_writable_property_name(device)? {
31        Some(name) => {
32            // Write the property's current value back to itself: harmless if
33            // it were allowed, but a view-only connection must reject it.
34            let value = device.property_value(&name)?;
35            match device.set_property_value(&name, value) {
36                Ok(()) => println!("Unexpected: writing {name:?} was allowed."),
37                Err(err) => {
38                    println!("Write to {name:?} refused, as expected for view-only: {err}")
39                }
40            }
41        }
42        None => println!("Device exposes no writable property to probe."),
43    }
44    Ok(())
45}
46
47fn main() -> opendaq::Result<()> {
48    let instance = Instance::new()?;
49
50    let config = instance
51        .create_default_add_device_config()?
52        .expect("default add-device config");
53
54    // The "General" child object holds the protocol-independent options,
55    // ClientType among them; its selection values name the available modes.
56    let general = config
57        .property_value("General")?
58        .into_object()?
59        .cast::<PropertyObject>()?;
60    let client_type = general
61        .property("ClientType")?
62        .expect("ClientType property");
63    println!("Available ClientType options:");
64    if let Value::Dict(mut options) = client_type.selection_values()? {
65        options.sort_by_key(|(key, _)| key.as_i64());
66        for (key, name) in options {
67            println!("  {key} = {name}");
68        }
69    }
70
71    config.set_property_value("General.ClientType", 2)?; // 2 = view-only
72    let connection_string =
73        std::env::var("OPENDAQ_DEVICE").unwrap_or_else(|_| "daq.nd://127.0.0.1".into());
74
75    match instance.add_device_with(&connection_string, Some(&config)) {
76        Ok(Some(device)) => probe_view_only_device(&device)?,
77        Ok(None) => println!("Could not connect to {connection_string}: no device returned."),
78        Err(err) => {
79            println!("Could not connect to {connection_string}: {err}");
80            println!("Start an openDAQ device/simulator there, or set OPENDAQ_DEVICE.");
81        }
82    }
83    Ok(())
84}
examples/smoke.rs (line 33)
7fn main() -> opendaq::Result<()> {
8    let instance = Instance::new()?;
9
10    println!("Available devices:");
11    for info in instance.available_devices()? {
12        println!(" - {}: {}", info.connection_string()?, info.name()?);
13    }
14
15    let device = instance.add_device("daqref://device0")?.expect("device");
16    println!("Added device: {}", device.name()?);
17
18    let channel = instance
19        .find_component("Dev/RefDev0/IO/AI/RefCh0")?
20        .expect("reference channel not found")
21        .cast::<Channel>()?;
22    let signal = &channel.signals()?[0];
23
24    // Batched property updates.
25    {
26        let batch = BatchedPropertyUpdate::new(&[&device, &channel])?;
27        device.set_property_value("GlobalSampleRate", 1000)?;
28        channel.set_property_value("Frequency", 50.0)?;
29        batch.commit()?;
30    }
31    println!(
32        "GlobalSampleRate = {}",
33        device.property_value("GlobalSampleRate")?
34    );
35
36    // Stream reading with domain + tick conversion.
37    let reader = StreamReader::<f64>::new(signal)?;
38    let (samples, ticks) = reader.read_with_domain(100, 2000)?;
39    println!(
40        "read {} samples, {} ticks",
41        samples.sample_count(),
42        ticks.len()
43    );
44    let converter = TickConverter::from_signal(signal)?;
45    if let Some(first) = ticks.first() {
46        println!(
47            "first tick {} -> {:?}",
48            first,
49            converter.tick_to_system_time(*first)
50        );
51    }
52
53    // Callables: a Rust closure as an openDAQ function, called through openDAQ.
54    let sum = FunctionObject::from_fn(|args| {
55        let a = args[0].as_i64().unwrap_or(0);
56        let b = args[1].as_i64().unwrap_or(0);
57        Ok(Value::from(a + b))
58    })?;
59    let result = sum.call(&[Value::from(20), Value::from(22)])?;
60    println!("sum(20, 22) = {result}");
61
62    // Events: subscribe to property changes on the channel.
63    let events = channel
64        .on_property_value_write("Amplitude")?
65        .expect("event");
66    let handler = events.subscribe(|_sender, args| {
67        if let Some(args) = args {
68            println!("  event fired: {args}");
69        }
70    })?;
71    channel.set_property_value("Amplitude", 2.5)?;
72    events.unsubscribe(&handler)?;
73    channel.set_property_value("Amplitude", 1.0)?;
74    println!("Amplitude = {}", channel.property_value("Amplitude")?);
75
76    Ok(())
77}
Source

pub fn updating(&self) -> Result<bool>

Returns the state of batch configuration.

§Returns
  • updating: True if the object is performing batch update of its properties. Batched configuration is used to apply several settings at once. To begin batch configuration, call beginUpdate. When the setPropertyValue is called on the object, the changes are not immediately applied. When endUpdate is called, the property values set between the beginUpdate and endUpdate method calls are applied. This method returns True if beginUpdate method has been called on the objectandendUpdate` has not been called yet.

Calls the openDAQ C function daqPropertyObject_getUpdating().

Source

pub fn visible_properties(&self) -> Result<Vec<Property>>

Returns a list of visible properties contained in the Property object.

§Returns
  • properties: The List of properties. A Property is visible if both the Visible parameter is set to true, and IsReferenced is false. The properties are sorted in insertion order unless a custom order is specified. This function returns both the properties added to the Property object, as well as those of its class.

Calls the openDAQ C function daqPropertyObject_getVisibleProperties().

Examples found in repository?
examples/component_tree.rs (line 34)
33fn draw_properties(component: &Component, prefix: &str) -> opendaq::Result<()> {
34    for property in component.visible_properties()? {
35        println!(
36            "{prefix}• {} : {:?} = {}",
37            property.name()?,
38            property.value_type()?,
39            property_value_string(component, &property)?
40        );
41    }
42    Ok(())
43}
More examples
Hide additional examples
examples/connect_view_only_client.rs (line 15)
14fn first_writable_property_name(object: &PropertyObject) -> opendaq::Result<Option<String>> {
15    for property in object.visible_properties()? {
16        if property.read_only()? {
17            continue;
18        }
19        if matches!(property.value_type()?, CoreType::Func | CoreType::Proc) {
20            continue;
21        }
22        return Ok(Some(property.name()?));
23    }
24    Ok(None)
25}
Source

pub fn has_property(&self, property_name: &str) -> Result<bool>

Checks if the Property object contains a property named propertyName.

§Parameters
  • property_name: The name of the property.
§Returns
  • has_property: True if the Property object contains the Property; false otherwise.

Calls the openDAQ C function daqPropertyObject_hasProperty().

Source

pub fn remove_property(&self, property_name: &str) -> Result<()>

Removes the Property named propertyName from the Property object.

§Parameters
  • property_name: The name of the Property to be removed.
§Errors
  • OPENDAQ_ERR_NOTFOUND: if the Property object does not contain a Property named propertyName, or the Property is part of the Property object’s Property object class.
  • OPENDAQ_ERR_FROZEN: if the Property object is frozen. A property can only be removed from a Property object, if it was added to the object, and not inherited from its class.

Calls the openDAQ C function daqPropertyObject_removeProperty().

Source

pub fn set_property_order(&self, ordered_property_names: &[&str]) -> Result<()>

Sets a custom order of properties as defined in the list of property names.

§Parameters
  • ordered_property_names: A list of names of properties. The order of the list is applied to the object’s properties.
§Errors
  • OPENDAQ_ERR_FROZEN: if the Property object is frozen. The list should contain names of properties available in the object. When retrieving the Property object’s properties, they will be sorted in the order in which the names appear in the provided list. Any properties not in the custom order are kept in insertion order at the end of the Property object’s list of properties.

Calls the openDAQ C function daqPropertyObject_setPropertyOrder().

Source

pub fn set_property_selection_value( &self, property_name: &str, value: impl Into<Value>, ) -> Result<()>

Sets the value of a Selection property by the selection item value (e.g. string, float, or list/dict value).

§Parameters
  • property_name: The name of the Property.
  • value: The selection value to set (must be one of the Property’s selection values). Cannot be null.
§Errors
  • OPENDAQ_ERR_NOTFOUND: if a Property with given propertyName is not part of the Property object, or the value is not in the selection.
  • OPENDAQ_ERR_INVALIDPROPERTY: if the Property has no Selection values.
  • OPENDAQ_ERR_ACCESSDENIED: if the property is Read-only.
  • OPENDAQ_ERR_FROZEN: if the Property object is frozen. Works for all Selection properties (list or dictionary): the value is the actual selection item (e.g. a string from the list, or the value part of a key-value pair in the dictionary). Use setPropertyValue when setting by index/key.

Calls the openDAQ C function daqPropertyObject_setPropertySelectionValue().

Source

pub fn set_property_value( &self, property_name: &str, value: impl Into<Value>, ) -> Result<()>

Sets the value of the Property with the given name.

§Parameters
  • property_name: The name of the Property.
  • value: The Property value to be set. Cannot be null.
§Errors
  • OPENDAQ_ERR_NOTFOUND: if a property with given propertyName is not part of the Property object.
  • OPENDAQ_ERR_ACCESSDENIED: if the property is Read-only.
  • OPENDAQ_ERR_CONVERSIONFAILED: if the value cannot be converted to the Value type of the Property.
  • OPENDAQ_ERR_INVALIDTYPE: if the value is a list/dictionary/object with invalid keys/items/fields.
  • OPENDAQ_ERR_VALIDATE_FAILED: if the Validator fails to validate the value.
  • OPENDAQ_ERR_COERCION_FAILED: if the Coercer fails to coerce the value.
  • OPENDAQ_ERR_FROZEN: if the Property object is frozen.
  • OPENDAQ_ERR_IGNORED: if the value is the same as the default, or the previously written value. Stores the provided value into an internal dictionary of property name and value pairs. This property value can later be retrieved through the corresponding getter method when invoked with the same propertyName. The provided value must adhere to the restrictions of the corresponding Property (that bears the name propertyName). If such a Property is part of the Property object, the setter call will fail. Some restrictions include: - The core type of the value must match that of the Property Value type. - If the Property is a numeric type, the value must be equal or greater than the Min value, and equal or smaller than the Max value. - If the Property is Read-only, the setter will fail. - The value will be validated by the Property validator causing the setter method to fail if validation is unsuccessful. - The value will be coerced to fit the coercion expression of the Property coercer before being written into the local dictionary of property values. Setting the value of a Property will override either its default value or the value that was set beforehand. @subsection patterns Behaviour patterns of note - When setting the value of a Property with the Selection values field configured (a Selection property), the value must be an integer type, and acts as an index/key into the list/dictionary of Selection values. - If the Property is a Reference property (the Referenced property field is configured), the value is actually written under the key of the referenced Property, not the one specified through the propertyName argument. - When setting a list or dictionary type property, the list items and dictionary keys and items must be homogeneous, and of the same type as specified by the item and key type of the Property. - Setting a Property value will invoke the corresponding onPropertyValueWrite event. @subsection value_set_child_property_objects Child Property objects The Property value setter allows for direct configuration of any child Property objects. To set the Property value of a child Property object, the propertyName parameter should be of the format: “childName.propertyName”. This pattern can also be used to access nested properties - for example “childName1.childName2.childName3.propertyName”.

Calls the openDAQ C function daqPropertyObject_setPropertyValue().

Examples found in repository?
examples/connect_view_only_client.rs (line 35)
27fn probe_view_only_device(device: &Device) -> opendaq::Result<()> {
28    println!("Connected to {} as a view-only client.", device.name()?);
29    println!("Visible signals: {}", device.signals_recursive()?.len());
30    match first_writable_property_name(device)? {
31        Some(name) => {
32            // Write the property's current value back to itself: harmless if
33            // it were allowed, but a view-only connection must reject it.
34            let value = device.property_value(&name)?;
35            match device.set_property_value(&name, value) {
36                Ok(()) => println!("Unexpected: writing {name:?} was allowed."),
37                Err(err) => {
38                    println!("Write to {name:?} refused, as expected for view-only: {err}")
39                }
40            }
41        }
42        None => println!("Device exposes no writable property to probe."),
43    }
44    Ok(())
45}
46
47fn main() -> opendaq::Result<()> {
48    let instance = Instance::new()?;
49
50    let config = instance
51        .create_default_add_device_config()?
52        .expect("default add-device config");
53
54    // The "General" child object holds the protocol-independent options,
55    // ClientType among them; its selection values name the available modes.
56    let general = config
57        .property_value("General")?
58        .into_object()?
59        .cast::<PropertyObject>()?;
60    let client_type = general
61        .property("ClientType")?
62        .expect("ClientType property");
63    println!("Available ClientType options:");
64    if let Value::Dict(mut options) = client_type.selection_values()? {
65        options.sort_by_key(|(key, _)| key.as_i64());
66        for (key, name) in options {
67            println!("  {key} = {name}");
68        }
69    }
70
71    config.set_property_value("General.ClientType", 2)?; // 2 = view-only
72    let connection_string =
73        std::env::var("OPENDAQ_DEVICE").unwrap_or_else(|_| "daq.nd://127.0.0.1".into());
74
75    match instance.add_device_with(&connection_string, Some(&config)) {
76        Ok(Some(device)) => probe_view_only_device(&device)?,
77        Ok(None) => println!("Could not connect to {connection_string}: no device returned."),
78        Err(err) => {
79            println!("Could not connect to {connection_string}: {err}");
80            println!("Start an openDAQ device/simulator there, or set OPENDAQ_DEVICE.");
81        }
82    }
83    Ok(())
84}
More examples
Hide additional examples
examples/batch_properties.rs (line 28)
18fn main() -> opendaq::Result<()> {
19    let instance = Instance::new()?;
20    let device = instance.add_device("daqref://device0")?.expect("device");
21    let channels = device.channels()?;
22    let (ch0, ch1) = (&channels[0], &channels[1]);
23
24    show_settings("Before:          ", ch0)?;
25    show_settings("Before:          ", ch1)?;
26
27    let batch = BatchedPropertyUpdate::new(&[ch0, ch1])?;
28    ch0.set_property_value("Amplitude", 2.5)?;
29    ch0.set_property_value("Frequency", 25.0)?;
30    ch0.set_property_value("Waveform", 1)?;
31    ch1.set_property_value("Amplitude", 4.0)?;
32    ch1.set_property_value("Frequency", 50.0)?;
33    ch1.set_property_value("Waveform", 2)?;
34    // Still inside the batch: the writes above are staged but not yet applied.
35    show_settings("During (staged): ", ch0)?;
36    show_settings("During (staged): ", ch1)?;
37    batch.commit()?;
38
39    show_settings("After the batch: ", ch0)?;
40    show_settings("After the batch: ", ch1)?;
41    Ok(())
42}
examples/multireader.rs (line 35)
27fn main() -> opendaq::Result<()> {
28    let instance = Instance::new()?;
29    instance.add_device("daqref://device0")?;
30
31    let channels = [
32        find_channel(&instance, "Dev/RefDev0/IO/AI/RefCh0")?,
33        find_channel(&instance, "Dev/RefDev0/IO/AI/RefCh1")?,
34    ];
35    channels[0].set_property_value("Frequency", 0.5)?;
36    channels[1].set_property_value("Frequency", 2.0)?;
37
38    let signals = [
39        channels[0].signals()?[0].clone(),
40        channels[1].signals()?[0].clone(),
41    ];
42    let reader = MultiReader::<f64>::new(&signals)?;
43
44    // The first reads can return nothing while the reader synchronises the
45    // signals onto the common domain; retry until rows arrive.
46    for _ in 0..10 {
47        let (values, domain) = reader.read_with_domain(8, 1000)?;
48        if domain[0].is_empty() {
49            continue;
50        }
51        let converter = TickConverter::from_multi_reader(&reader)?;
52        print!("{:<16}", "timestamp");
53        for index in 0..values.len() {
54            print!("{:>14}", format!("signal {index}"));
55        }
56        println!();
57        for (row, tick) in domain[0].iter().enumerate() {
58            print!("{:<16}", time_of_day(converter.tick_to_unix_nanos(*tick)));
59            for signal_values in &values {
60                print!("{:>14.6}", signal_values[row]);
61            }
62            println!();
63        }
64        return Ok(());
65    }
66    println!("Multi reader did not synchronise in time.");
67    Ok(())
68}
examples/core_events.rs (line 44)
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}
examples/smoke.rs (line 27)
7fn main() -> opendaq::Result<()> {
8    let instance = Instance::new()?;
9
10    println!("Available devices:");
11    for info in instance.available_devices()? {
12        println!(" - {}: {}", info.connection_string()?, info.name()?);
13    }
14
15    let device = instance.add_device("daqref://device0")?.expect("device");
16    println!("Added device: {}", device.name()?);
17
18    let channel = instance
19        .find_component("Dev/RefDev0/IO/AI/RefCh0")?
20        .expect("reference channel not found")
21        .cast::<Channel>()?;
22    let signal = &channel.signals()?[0];
23
24    // Batched property updates.
25    {
26        let batch = BatchedPropertyUpdate::new(&[&device, &channel])?;
27        device.set_property_value("GlobalSampleRate", 1000)?;
28        channel.set_property_value("Frequency", 50.0)?;
29        batch.commit()?;
30    }
31    println!(
32        "GlobalSampleRate = {}",
33        device.property_value("GlobalSampleRate")?
34    );
35
36    // Stream reading with domain + tick conversion.
37    let reader = StreamReader::<f64>::new(signal)?;
38    let (samples, ticks) = reader.read_with_domain(100, 2000)?;
39    println!(
40        "read {} samples, {} ticks",
41        samples.sample_count(),
42        ticks.len()
43    );
44    let converter = TickConverter::from_signal(signal)?;
45    if let Some(first) = ticks.first() {
46        println!(
47            "first tick {} -> {:?}",
48            first,
49            converter.tick_to_system_time(*first)
50        );
51    }
52
53    // Callables: a Rust closure as an openDAQ function, called through openDAQ.
54    let sum = FunctionObject::from_fn(|args| {
55        let a = args[0].as_i64().unwrap_or(0);
56        let b = args[1].as_i64().unwrap_or(0);
57        Ok(Value::from(a + b))
58    })?;
59    let result = sum.call(&[Value::from(20), Value::from(22)])?;
60    println!("sum(20, 22) = {result}");
61
62    // Events: subscribe to property changes on the channel.
63    let events = channel
64        .on_property_value_write("Amplitude")?
65        .expect("event");
66    let handler = events.subscribe(|_sender, args| {
67        if let Some(args) = args {
68            println!("  event fired: {args}");
69        }
70    })?;
71    channel.set_property_value("Amplitude", 2.5)?;
72    events.unsubscribe(&handler)?;
73    channel.set_property_value("Amplitude", 1.0)?;
74    println!("Amplitude = {}", channel.property_value("Amplitude")?);
75
76    Ok(())
77}
examples/add_function_block.rs (line 34)
18fn main() -> opendaq::Result<()> {
19    // Instance::new() already loads the bundled modules; build from an
20    // InstanceBuilder when you want to control the module search path.
21    let builder = InstanceBuilder::new()?;
22    // The bundled modules (reference device, function blocks, streaming):
23    let bundled = opendaq::native_library_directory().expect("native libraries");
24    builder.set_module_path(&bundled.to_string_lossy())?;
25    // Your own modules folder:
26    // builder.add_module_path("/path/to/your/modules")?;
27    let instance = Instance::from_builder(&builder)?;
28    instance.add_device("daqref://device0")?;
29
30    let channel = instance
31        .find_component("Dev/RefDev0/IO/AI/RefCh0")?
32        .expect("reference channel not found")
33        .cast::<Channel>()?;
34    channel.set_property_value("Amplitude", 5.0)?;
35    channel.set_property_value("DC", 1.0)?;
36
37    let statistics = instance
38        .add_function_block("RefFBModuleStatistics")?
39        .expect("statistics function block");
40    statistics.set_property_value("BlockSize", 100)?;
41
42    let status = statistics.status_container()?.expect("status container");
43    println!(
44        "Before connect: {} ({})",
45        status.status("ComponentStatus")?.expect("status").value()?,
46        status.status_message("ComponentStatus")?
47    );
48
49    let port = &statistics.input_ports()?[0];
50    let signal = &channel.signals()?[0];
51    port.connect(signal)?;
52
53    println!(
54        "After connect:  {} ({})",
55        status.status("ComponentStatus")?.expect("status").value()?,
56        status.status_message("ComponentStatus")?
57    );
58
59    let outputs = statistics.signals()?;
60    let avg = signal_by_local_id(&outputs, "avg")?.expect("avg signal");
61    let rms = signal_by_local_id(&outputs, "rms")?.expect("rms signal");
62    let reader = MultiReader::<f64>::new(&[avg, rms])?;
63
64    // The first reads may return nothing while the block waits for a complete
65    // input descriptor (the multi reader by default doesn't skip events), so
66    // retry until samples arrive.
67    for _attempt in 0..20 {
68        let values = reader.read(5, 1000)?;
69        if !values[0].is_empty() {
70            println!("{:>10}{:>12}", "avg", "rms");
71            for (a, r) in values[0].iter().zip(&values[1]) {
72                println!("{a:>10.4}{r:>12.4}");
73            }
74            return Ok(());
75        }
76    }
77    println!("Statistics block produced no samples in time.");
78    Ok(())
79}

Methods from Deref<Target = BaseObject>§

Source

pub fn cast<T: Interface>(&self) -> Result<T>

Query this object for interface T, returning a wrapper that owns its own reference.

This is a genuine queryInterface: an object’s interfaces live at different virtual-table offsets, so the pointer for one interface is not binary-compatible with another and must be queried, not merely reinterpreted. Fails with an openDAQ error when the object does not implement T (use BaseObject::try_cast / BaseObject::is_a to probe first).

For the few interfaces the C API exposes no GUID for (T::interface_id() is None), the pointer is reinterpreted unchecked, which is sound only when the object really lies on T’s inheritance chain.

Examples found in repository?
examples/call_function_property.rs (line 14)
10fn function_property(device: &Device, name: &str) -> opendaq::Result<FunctionObject> {
11    device
12        .property_value(name)?
13        .into_object()?
14        .cast::<FunctionObject>()
15}
More examples
Hide additional examples
examples/component_tree.rs (line 48)
46fn children(component: &Component) -> opendaq::Result<Vec<Component>> {
47    if component.is_a::<Folder>() {
48        component.cast::<Folder>()?.items()
49    } else {
50        Ok(Vec::new())
51    }
52}
examples/multireader.rs (line 24)
20fn find_channel(instance: &Instance, path: &str) -> opendaq::Result<Channel> {
21    instance
22        .find_component(path)?
23        .unwrap_or_else(|| panic!("channel {path} not found"))
24        .cast::<Channel>()
25}
examples/search_filter.rs (line 25)
22fn show<T: Interface>(label: &str, components: Vec<T>) -> opendaq::Result<()> {
23    let ids = components
24        .iter()
25        .map(|c| c.to_base_object().cast::<Component>()?.local_id())
26        .collect::<opendaq::Result<Vec<_>>>()?;
27    let listing = if ids.is_empty() {
28        "(none)".to_string()
29    } else {
30        ids.join(", ")
31    };
32    println!("{label}\n    => {listing}\n");
33    Ok(())
34}
35
36fn main() -> opendaq::Result<()> {
37    let instance = Instance::new()?;
38    instance.add_device("daqref://device0")?;
39    let root = instance.root_device()?.expect("root device");
40
41    // Give a couple of channels some tags, so the tag filter has something to
42    // match.  (RefCh0 and RefCh1 come from the reference device unlabelled.)
43    let everything = SearchFilter::recursive(&SearchFilter::any()?)?;
44    for channel in root.channels_with(Some(&everything))? {
45        let tags = channel.tags()?.expect("tags").cast::<TagsPrivate>()?;
46        tags.add("analog")?;
47        if channel.local_id()? == "RefCh0" {
48            tags.add("primary")?;
49        }
50    }
51
52    show(
53        "channels, no filter (immediate children only)",
54        root.channels()?,
55    )?;
56
57    show(
58        "channels, recursive(any)",
59        root.channels_with(Some(&SearchFilter::recursive(&SearchFilter::any()?)?))?,
60    )?;
61
62    show(
63        "channels, recursive(id = RefCh1)",
64        root.channels_with(Some(&SearchFilter::recursive(&SearchFilter::local_id(
65            "RefCh1",
66        )?)?))?,
67    )?;
68
69    let ai0_or_ai1 = SearchFilter::or(
70        &SearchFilter::local_id("AI0")?,
71        &SearchFilter::local_id("AI1")?,
72    )?;
73    show(
74        "signals, recursive(id = AI0 OR id = AI1)",
75        root.signals_with(Some(&SearchFilter::recursive(&ai0_or_ai1)?))?,
76    )?;
77
78    let not_ref_ch1 = SearchFilter::not(&SearchFilter::local_id("RefCh1")?)?;
79    show(
80        "channels, recursive(NOT id = RefCh1)",
81        root.channels_with(Some(&SearchFilter::recursive(&not_ref_ch1)?))?,
82    )?;
83
84    let analog_and_not_ref_ch1 = SearchFilter::and(
85        &SearchFilter::required_tags(vec!["analog"])?,
86        &SearchFilter::not(&SearchFilter::local_id("RefCh1")?)?,
87    )?;
88    show(
89        "channels, recursive(tag = analog AND NOT id = RefCh1)",
90        root.channels_with(Some(&SearchFilter::recursive(&analog_and_not_ref_ch1)?))?,
91    )?;
92
93    Ok(())
94}
examples/streamreader.rs (line 15)
8fn main() -> opendaq::Result<()> {
9    let instance = Instance::new()?;
10    instance.add_device("daqref://device0")?;
11
12    let channel = instance
13        .find_component("Dev/RefDev0/IO/AI/RefCh0")?
14        .expect("reference channel not found")
15        .cast::<Channel>()?;
16    let signal = &channel.signals()?[0];
17
18    let reader = StreamReader::<f64>::new(signal)?;
19    println!("some samples: {:?}", reader.read(100, 1000)?.values());
20    println!("and more samples: {:?}", reader.read(100, 1000)?.values());
21    println!("and more still: {:?}", reader.read(100, 1000)?.values());
22    Ok(())
23}
examples/streamreader_with_timestamps.rs (line 46)
39fn main() -> opendaq::Result<()> {
40    let instance = Instance::new()?;
41    instance.add_device("daqref://device0")?;
42
43    let channel = instance
44        .find_component("Dev/RefDev0/IO/AI/RefCh0")?
45        .expect("reference channel not found")
46        .cast::<Channel>()?;
47    let signal = &channel.signals()?[0];
48
49    let reader = StreamReader::<f64>::new(signal)?;
50    let converter = TickConverter::from_signal(signal)?;
51
52    let (values, ticks) = reader.read_with_domain(10, 2000)?;
53    println!("Read {} samples:", values.sample_count());
54    for (value, tick) in values.iter().zip(&ticks) {
55        println!(
56            "  {value:.6} @ {}",
57            timestamp_to_string(converter.tick_to_unix_nanos(*tick))
58        );
59    }
60    Ok(())
61}
Source

pub fn try_cast<T: Interface>(&self) -> Option<T>

Like BaseObject::cast, but returns None when the object does not implement T.

Source

pub fn is_a<T: Interface>(&self) -> bool

True when the object implements interface T (a borrowInterface probe; adds no reference). Returns false for interfaces without a GUID in the C API, which cannot be probed.

Examples found in repository?
examples/component_tree.rs (line 47)
46fn children(component: &Component) -> opendaq::Result<Vec<Component>> {
47    if component.is_a::<Folder>() {
48        component.cast::<Folder>()?.items()
49    } else {
50        Ok(Vec::new())
51    }
52}
Source

pub fn hash_code(&self) -> Result<usize>

The object’s hash code.

Source

pub fn equals<T: Interface>(&self, other: &T) -> Result<bool>

True when openDAQ considers the two objects equal.

Source

pub fn ptr_eq<T: Interface>(&self, other: &T) -> bool

Identity comparison: both wrappers refer to the same native object. (Note that pointers to different interfaces of one object differ; this compares the raw interface pointers.)

Source

pub fn dispose(&self) -> Result<()>

Release the object’s internal resources early (openDAQ dispose). The wrapper itself stays alive; most callers never need this.

Source

pub fn component_kind(&self) -> Option<ComponentKind>

The most-derived component interface this object implements (probed most-derived first), or None when it is not a component.

Examples found in repository?
examples/component_tree.rs (line 10)
8fn type_label(component: &Component) -> String {
9    component
10        .component_kind()
11        .map_or_else(|| "Component".to_string(), |kind| format!("{kind:?}"))
12}
Source

pub fn to_value(&self) -> Result<Value>

The natural Rust value of this object: a boxed scalar yields its native value, a daq list a Vec, a daq dict key/value pairs – with elements converted recursively – and an object with no natural Rust form (a device, a property object, …) comes back as Value::Object, for the caller to BaseObject::cast.

Trait Implementations§

Source§

impl Clone for ServerCapabilityConfig

Source§

fn clone(&self) -> ServerCapabilityConfig

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ServerCapabilityConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for ServerCapabilityConfig

Source§

type Target = ServerCapability

The resulting type after dereferencing.
Source§

fn deref(&self) -> &ServerCapability

Dereferences the value.
Source§

impl Display for ServerCapabilityConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<&ServerCapabilityConfig> for Value

Source§

fn from(value: &ServerCapabilityConfig) -> Value

Converts to this type from the input type.
Source§

impl From<ServerCapabilityConfig> for Value

Source§

fn from(value: ServerCapabilityConfig) -> Value

Converts to this type from the input type.
Source§

impl Interface for ServerCapabilityConfig

Source§

const NAME: &'static str = "daqServerCapabilityConfig"

The openDAQ interface name, e.g. "daqDevice".
Source§

fn interface_id() -> Option<IntfID>

The interface’s GUID, or None for the few coretypes interfaces the C API exposes no id for (IBaseObject, IFunction, IProcedure, …).
Source§

unsafe fn from_raw(ptr: *mut c_void) -> Option<Self>

Adopt an owned raw interface pointer (takes ownership of one reference; does not add one). Returns None for null. Read more
Source§

fn as_base_object(&self) -> &BaseObject

This wrapper viewed as the root IBaseObject interface.
Source§

fn as_raw(&self) -> *mut c_void

The raw interface pointer (still owned by this wrapper).
Source§

fn to_base_object(&self) -> BaseObject

A new owning BaseObject handle to the same underlying object.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.