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

How to create data type from json Value? #118

Closed jigar88 closed 3 years ago

jigar88 commented 3 years ago

I am making nodes based on json messages. In the messages I have various values like f64, i64, bool and String. How can I make it equivalent Variant for variable dat type. In python I used to do it easily with Variant class. I have snip of python code I used to convert opcua datatype from json.

from opcua.ua.uatypes import VariantType

def get_tag_data_type(tag_value):
    if type(tag_value) is bool:
        return VariantType.Boolean
    elif type(tag_value) is int:
        return VariantType.Int64
    elif type(tag_value) is float:
        return VariantType.Float
    else:
        return VariantType.String

I am trying to approach similarly but it gives an error for multiple type of return.

use serde_json::{Value, from_str};
use opcua_server::prelude::{NodeId, Variant, VariantTypeId};

pub fn get_data_type(tag_value: Value) {
    if tag_value.is_boolean() {
        return VariantTypeId::Boolean
    } else if tag_value.is_i64() {
        return VariantTypeId::Int64
    }
}

How can I similar result with this library?

schroeder- commented 3 years ago

You should add a return type to your function definition. Also not all paths return a value. Try this instead:

pub fn get_data_type(tag_value: Value) -> VariantTypeId {
    match tag_value{
        Value::Null => VariantTypeId::Empty,
        Value::Bool(b) => VariantTypeId::Boolean,
        Value::Number(n) => VariantTypeId::Int64,
        _ => VariantTypeId::Empty
    }
}
jigar88 commented 3 years ago

@schroeder- This is great help, thankyou :-)