locka99 / opcua

A client and server implementation of the OPC UA specification written in Rust
Mozilla Public License 2.0
496 stars 131 forks source link

Getting Value from LocalizedText Variant #126

Closed forcmti closed 3 years ago

forcmti commented 3 years ago

Some of the types variable getting from event Handler is of "LocalizedText" Variant.

To Obtain the actual message from the "LocalizedText", is there any method is there. Only thing i can think of is converting into string and doing string manipulation to get the message.

Is there any proper method to get "text" property from LocalizedText.

For Example My Response from OPCUA Server for Message that i printed i got is

Message: LocalizedText(LocalizedText { locale: UAString { value: None }, text: UAString { value: Some("The alarm severity has increased.") } })

Is there any simple method i am missing, so i can get the "text" value from LocalizedText. For UAString , i know by calling value function, you can get the String.

So for LocalizedText is there any method like that?

schroeder- commented 3 years ago

You can directly access the text member of LocalizedText struct.

let text = LocalizedText::new(....);
let s = s.text.value();
forcmti commented 3 years ago

Yeah above can be done if you are creating a LocalizedText.

I should have specified, the type i am getting is &opcua_client::prelude::Variant.

So if i print the variable with code.

 println!("Data : {:?}",field);

Output in Terminal

Data : LocalizedText(LocalizedText { locale: UAString { value: None }, text: UAString { value: Some("The alarm severity has increased.") } })

field is of type : &opcua_client::prelude::Variant when i try to call field.text.value()

no field `text` on type `&opcua_client::prelude::Variant`

So should i have to convert opcua_client::prelude::Variant into other type to get the Data. I only want the text part of it where Some("The alarm severity has increased.") and to store in a variable.

I looked at the Documentation of Variant enum it has LocalizedText(Box<LocalizedText>) So is it possible to get the value from Variant enum.

schroeder- commented 3 years ago

You can match a Variant for example:

        match field{
            Variant::LocalizedText(text) => text.text.value(),
            Variant::String(text) => text.value(),
            _ => ...
        }

or use if let:

        if let Variant::LocalizedText(text) = field{
            ... 
        } else {
            ...
        }
forcmti commented 3 years ago

Thanks man, Why didn't i think of this, now i have to think like this. It worked perfectly.