1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// OPCUA for Rust
// SPDX-License-Identifier: MPL-2.0
// Copyright (C) 2017-2022 Adam Lock

//! Contains the implementation of `Method` and `MethodBuilder`.

use std::sync::{Arc, RwLock};

use opcua_types::service_types::{Argument, MethodAttributes};

use crate::{
    address_space::{
        address_space::MethodCallback,
        base::Base,
        node::{Node, NodeBase},
        variable::VariableBuilder,
    },
    session::SessionManager,
};

node_builder_impl!(MethodBuilder, Method);
node_builder_impl_component_of!(MethodBuilder);
node_builder_impl_generates_event!(MethodBuilder);

impl MethodBuilder {
    /// Specify output arguments from the method. This will create an OutputArguments
    /// variable child of the method which describes the out parameters.
    pub fn output_args(self, address_space: &mut AddressSpace, arguments: &[Argument]) -> Self {
        self.insert_args("OutputArguments", address_space, arguments);
        self
    }

    /// Specify input arguments to the method. This will create an InputArguments
    /// variable child of the method which describes the in parameters.
    pub fn input_args(self, address_space: &mut AddressSpace, arguments: &[Argument]) -> Self {
        self.insert_args("InputArguments", address_space, arguments);
        self
    }

    pub fn callback(mut self, callback: MethodCallback) -> Self {
        self.node.set_callback(callback);
        self
    }

    fn args_to_variant(arguments: &[Argument]) -> Variant {
        let arguments = arguments
            .iter()
            .map(|arg| {
                Variant::from(ExtensionObject::from_encodable(
                    ObjectId::Argument_Encoding_DefaultBinary,
                    arg,
                ))
            })
            .collect::<Vec<Variant>>();
        Variant::from((VariantTypeId::ExtensionObject, arguments))
    }

    fn insert_args(
        &self,
        args_name: &str,
        address_space: &mut AddressSpace,
        arguments: &[Argument],
    ) {
        let fn_node_id = self.node.node_id();
        let args_id = NodeId::next_numeric(fn_node_id.namespace);
        let args_value = Self::args_to_variant(arguments);
        VariableBuilder::new(&args_id, args_name, args_name)
            .property_of(fn_node_id)
            .has_type_definition(VariableTypeId::PropertyType)
            .data_type(DataTypeId::Argument)
            .value_rank(1)
            .array_dimensions(&[arguments.len() as u32])
            .value(args_value)
            .insert(address_space);
    }
}

/// A `Method` is a type of node within the `AddressSpace`.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct Method {
    base: Base,
    executable: bool,
    user_executable: bool,
    #[derivative(Debug = "ignore")]
    callback: Option<MethodCallback>,
}

impl Default for Method {
    fn default() -> Self {
        Self {
            base: Base::new(NodeClass::Method, &NodeId::null(), "", ""),
            executable: false,
            user_executable: false,
            callback: None,
        }
    }
}

node_base_impl!(Method);

impl Node for Method {
    fn get_attribute_max_age(
        &self,
        timestamps_to_return: TimestampsToReturn,
        attribute_id: AttributeId,
        index_range: NumericRange,
        data_encoding: &QualifiedName,
        max_age: f64,
    ) -> Option<DataValue> {
        match attribute_id {
            AttributeId::Executable => Some(self.executable().into()),
            AttributeId::UserExecutable => Some(self.user_executable().into()),
            _ => self.base.get_attribute_max_age(
                timestamps_to_return,
                attribute_id,
                index_range,
                data_encoding,
                max_age,
            ),
        }
    }

    fn set_attribute(
        &mut self,
        attribute_id: AttributeId,
        value: Variant,
    ) -> Result<(), StatusCode> {
        match attribute_id {
            AttributeId::Executable => {
                if let Variant::Boolean(v) = value {
                    self.set_executable(v);
                    Ok(())
                } else {
                    Err(StatusCode::BadTypeMismatch)
                }
            }
            AttributeId::UserExecutable => {
                if let Variant::Boolean(v) = value {
                    self.set_user_executable(v);
                    Ok(())
                } else {
                    Err(StatusCode::BadTypeMismatch)
                }
            }
            _ => self.base.set_attribute(attribute_id, value),
        }
    }
}

impl Method {
    pub fn new<R, S>(
        node_id: &NodeId,
        browse_name: R,
        display_name: S,
        executable: bool,
        user_executable: bool,
    ) -> Method
    where
        R: Into<QualifiedName>,
        S: Into<LocalizedText>,
    {
        Method {
            base: Base::new(NodeClass::Method, node_id, browse_name, display_name),
            executable,
            user_executable,
            callback: None,
        }
    }

    pub fn from_attributes<S>(
        node_id: &NodeId,
        browse_name: S,
        attributes: MethodAttributes,
    ) -> Result<Self, ()>
    where
        S: Into<QualifiedName>,
    {
        let mandatory_attributes = AttributesMask::DISPLAY_NAME
            | AttributesMask::EXECUTABLE
            | AttributesMask::USER_EXECUTABLE;
        let mask = AttributesMask::from_bits(attributes.specified_attributes).ok_or(())?;
        if mask.contains(mandatory_attributes) {
            let mut node = Self::new(
                node_id,
                browse_name,
                attributes.display_name,
                attributes.executable,
                attributes.user_executable,
            );
            if mask.contains(AttributesMask::DESCRIPTION) {
                node.set_description(attributes.description);
            }
            if mask.contains(AttributesMask::WRITE_MASK) {
                node.set_write_mask(WriteMask::from_bits_truncate(attributes.write_mask));
            }
            if mask.contains(AttributesMask::USER_WRITE_MASK) {
                node.set_user_write_mask(WriteMask::from_bits_truncate(attributes.user_write_mask));
            }
            Ok(node)
        } else {
            error!("Method cannot be created from attributes - missing mandatory values");
            Err(())
        }
    }

    pub fn is_valid(&self) -> bool {
        self.has_callback() && self.base.is_valid()
    }

    pub fn executable(&self) -> bool {
        self.executable
    }

    pub fn set_executable(&mut self, executable: bool) {
        self.executable = executable;
    }

    pub fn user_executable(&self) -> bool {
        // User executable cannot be true unless executable is true
        self.executable && self.user_executable
        // TODO this should check the current session state to determine if the user
        //  has permissions to execute this method
    }

    pub fn set_user_executable(&mut self, user_executable: bool) {
        self.user_executable = user_executable;
    }

    pub fn set_callback(&mut self, callback: MethodCallback) {
        self.callback = Some(callback);
    }

    pub fn has_callback(&self) -> bool {
        self.callback.is_some()
    }

    pub fn call(
        &mut self,
        session_id: &NodeId,
        session_manager: Arc<RwLock<SessionManager>>,
        request: &CallMethodRequest,
    ) -> Result<CallMethodResult, StatusCode> {
        if let Some(ref mut callback) = self.callback {
            // Call the handler
            callback.call(session_id, session_manager, request)
        } else {
            error!(
                "Method call to {} has no handler, treating as invalid",
                self.node_id()
            );
            Err(StatusCode::BadMethodInvalid)
        }
    }
}