autosar_data_abstraction/software_component/interface/
clientserver.rs

1use crate::{
2    AbstractionElement, ArPackage, AutosarAbstractionError, Element, EnumItem, IdentifiableAbstractionElement,
3    abstraction_element,
4    datatype::{self, AbstractAutosarDataType},
5    software_component::AbstractPortInterface,
6};
7use autosar_data::ElementName;
8use datatype::AutosarDataType;
9
10//##################################################################
11
12/// A `ClientServerInterface` defines a set of operations that can be implemented by a server and called by a client
13///
14/// Use [`ArPackage::create_client_server_interface`] to create a new client server interface
15#[derive(Debug, Clone, PartialEq, Eq, Hash)]
16pub struct ClientServerInterface(pub(crate) Element);
17abstraction_element!(ClientServerInterface, ClientServerInterface);
18impl IdentifiableAbstractionElement for ClientServerInterface {}
19impl AbstractPortInterface for ClientServerInterface {}
20
21impl ClientServerInterface {
22    /// Create a new `ClientServerInterface`
23    pub(crate) fn new(name: &str, package: &ArPackage) -> Result<Self, AutosarAbstractionError> {
24        let elements = package.element().get_or_create_sub_element(ElementName::Elements)?;
25        let client_server_interface = elements.create_named_sub_element(ElementName::ClientServerInterface, name)?;
26
27        Ok(Self(client_server_interface))
28    }
29
30    /// Add a possible error to the client server interface
31    pub fn create_possible_error(
32        &self,
33        name: &str,
34        error_code: u64,
35    ) -> Result<ApplicationError, AutosarAbstractionError> {
36        let possible_errors = self.element().get_or_create_sub_element(ElementName::PossibleErrors)?;
37        ApplicationError::new(name, error_code, &possible_errors)
38    }
39
40    /// add an operation to the client server interface
41    pub fn create_operation(&self, name: &str) -> Result<ClientServerOperation, AutosarAbstractionError> {
42        let operations = self.element().get_or_create_sub_element(ElementName::Operations)?;
43        ClientServerOperation::new(name, &operations)
44    }
45
46    /// iterate over all operations
47    pub fn operations(&self) -> impl Iterator<Item = ClientServerOperation> + Send + 'static {
48        self.element()
49            .get_sub_element(ElementName::Operations)
50            .into_iter()
51            .flat_map(|operations| operations.sub_elements())
52            .filter_map(|elem| ClientServerOperation::try_from(elem).ok())
53    }
54
55    /// iterate over all application errors
56    pub fn possible_errors(&self) -> impl Iterator<Item = ApplicationError> + Send + 'static {
57        self.element()
58            .get_sub_element(ElementName::PossibleErrors)
59            .into_iter()
60            .flat_map(|errors| errors.sub_elements())
61            .filter_map(|elem| ApplicationError::try_from(elem).ok())
62    }
63}
64
65//##################################################################
66
67/// An `ApplicationError` represents an error that can be returned by a client server operation
68#[derive(Debug, Clone, PartialEq, Eq, Hash)]
69pub struct ApplicationError(Element);
70abstraction_element!(ApplicationError, ApplicationError);
71impl IdentifiableAbstractionElement for ApplicationError {}
72
73impl ApplicationError {
74    /// Create a new `ApplicationError`
75    fn new(name: &str, error_code: u64, parent_element: &Element) -> Result<Self, AutosarAbstractionError> {
76        let application_error = parent_element.create_named_sub_element(ElementName::ApplicationError, name)?;
77        let application_error = Self(application_error);
78        application_error.set_error_code(error_code)?;
79
80        Ok(application_error)
81    }
82
83    /// Set the error code of the application error
84    pub fn set_error_code(&self, error_code: u64) -> Result<(), AutosarAbstractionError> {
85        self.element()
86            .get_or_create_sub_element(ElementName::ErrorCode)?
87            .set_character_data(error_code)?;
88        Ok(())
89    }
90
91    /// Get the error code of the application error
92    pub fn error_code(&self) -> Option<u64> {
93        self.element()
94            .get_sub_element(ElementName::ErrorCode)?
95            .character_data()?
96            .parse_integer()
97    }
98}
99
100//##################################################################
101
102/// A `ClientServerOperation` defines an operation in a `ClientServerInterface`
103#[derive(Debug, Clone, PartialEq, Eq, Hash)]
104pub struct ClientServerOperation(Element);
105abstraction_element!(ClientServerOperation, ClientServerOperation);
106impl IdentifiableAbstractionElement for ClientServerOperation {}
107
108impl ClientServerOperation {
109    /// Create a new `ClientServerOperation`
110    fn new(name: &str, parent_element: &Element) -> Result<Self, AutosarAbstractionError> {
111        let operation = parent_element.create_named_sub_element(ElementName::ClientServerOperation, name)?;
112        Ok(Self(operation))
113    }
114
115    /// Add an argument to the operation
116    pub fn create_argument<T: AbstractAutosarDataType>(
117        &self,
118        name: &str,
119        data_type: &T,
120        direction: ArgumentDirection,
121    ) -> Result<ArgumentDataPrototype, AutosarAbstractionError> {
122        let arguments = self.element().get_or_create_sub_element(ElementName::Arguments)?;
123        ArgumentDataPrototype::new(name, &arguments, data_type, direction)
124    }
125
126    /// iterate over all arguments
127    pub fn arguments(&self) -> impl Iterator<Item = ArgumentDataPrototype> + Send + 'static {
128        self.element()
129            .get_sub_element(ElementName::Arguments)
130            .into_iter()
131            .flat_map(|arguments| arguments.sub_elements())
132            .filter_map(|elem| ArgumentDataPrototype::try_from(elem).ok())
133    }
134
135    /// add a reference to possible error to the operation
136    pub fn add_possible_error(&self, error: &ApplicationError) -> Result<(), AutosarAbstractionError> {
137        if self.element().named_parent()? != error.element().named_parent()? {
138            return Err(AutosarAbstractionError::InvalidParameter(
139                "Error and operation must be in the same ClientServerInterface".to_string(),
140            ));
141        }
142
143        let possible_errors = self
144            .element()
145            .get_or_create_sub_element(ElementName::PossibleErrorRefs)?;
146        possible_errors
147            .create_sub_element(ElementName::PossibleErrorRef)?
148            .set_reference_target(error.element())?;
149        Ok(())
150    }
151
152    /// Get the possible errors of the operation
153    pub fn possible_errors(&self) -> impl Iterator<Item = ApplicationError> + Send + 'static {
154        self.element()
155            .get_sub_element(ElementName::PossibleErrorRefs)
156            .into_iter()
157            .flat_map(|errors| errors.sub_elements())
158            .filter_map(|refelem| {
159                refelem
160                    .get_reference_target()
161                    .ok()
162                    .and_then(|elem| ApplicationError::try_from(elem).ok())
163            })
164    }
165}
166
167//##################################################################
168
169/// The `ArgumentDirection` defines the direction of an argument in a `ClientServerOperation`
170///
171/// Input arguments are used to pass data from the client to the server and are usualy passed by value.
172/// Output arguments are used to pass data from the server to the client and are usually passed by reference.
173/// In/Out arguments are used to pass data in both directions and are usually passed by reference.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
175pub enum ArgumentDirection {
176    /// The argument is an input argument
177    In,
178    /// The argument is an output argument
179    Out,
180    /// The argument is an in/out argument
181    InOut,
182}
183
184impl TryFrom<EnumItem> for ArgumentDirection {
185    type Error = AutosarAbstractionError;
186
187    fn try_from(item: EnumItem) -> Result<Self, Self::Error> {
188        match item {
189            EnumItem::In => Ok(ArgumentDirection::In),
190            EnumItem::Out => Ok(ArgumentDirection::Out),
191            EnumItem::Inout => Ok(ArgumentDirection::InOut),
192            _ => Err(AutosarAbstractionError::ValueConversionError {
193                value: item.to_string(),
194                dest: "ArgumentDirection".to_string(),
195            }),
196        }
197    }
198}
199
200impl From<ArgumentDirection> for EnumItem {
201    fn from(direction: ArgumentDirection) -> Self {
202        match direction {
203            ArgumentDirection::In => EnumItem::In,
204            ArgumentDirection::Out => EnumItem::Out,
205            ArgumentDirection::InOut => EnumItem::Inout,
206        }
207    }
208}
209
210//##################################################################
211
212/// An `ArgumentDataPrototype` represents an argument in a `ClientServerOperation`
213#[derive(Debug, Clone, PartialEq, Eq, Hash)]
214pub struct ArgumentDataPrototype(Element);
215abstraction_element!(ArgumentDataPrototype, ArgumentDataPrototype);
216impl IdentifiableAbstractionElement for ArgumentDataPrototype {}
217
218impl ArgumentDataPrototype {
219    /// Create a new `ArgumentDataPrototype`
220    fn new<T: AbstractAutosarDataType>(
221        name: &str,
222        parent_element: &Element,
223        data_type: &T,
224        direction: ArgumentDirection,
225    ) -> Result<Self, AutosarAbstractionError> {
226        let argument = parent_element.create_named_sub_element(ElementName::ArgumentDataPrototype, name)?;
227        let argument = Self(argument);
228        argument.set_data_type(data_type)?;
229        argument.set_direction(direction)?;
230
231        Ok(argument)
232    }
233
234    /// Set the data type of the argument
235    pub fn set_data_type<T: AbstractAutosarDataType>(&self, data_type: &T) -> Result<(), AutosarAbstractionError> {
236        self.element()
237            .get_or_create_sub_element(ElementName::TypeTref)?
238            .set_reference_target(data_type.element())?;
239        Ok(())
240    }
241
242    /// Get the data type of the argument
243    pub fn data_type(&self) -> Option<AutosarDataType> {
244        let data_type_elem = self
245            .element()
246            .get_sub_element(ElementName::TypeTref)?
247            .get_reference_target()
248            .ok()?;
249        AutosarDataType::try_from(data_type_elem).ok()
250    }
251
252    /// Set the direction of the argument
253    pub fn set_direction(&self, direction: ArgumentDirection) -> Result<(), AutosarAbstractionError> {
254        self.element()
255            .get_or_create_sub_element(ElementName::Direction)?
256            .set_character_data::<EnumItem>(direction.into())?;
257        Ok(())
258    }
259
260    /// Get the direction of the argument
261    pub fn direction(&self) -> Option<ArgumentDirection> {
262        let value = self
263            .element()
264            .get_sub_element(ElementName::Direction)?
265            .character_data()?
266            .enum_value()?;
267
268        ArgumentDirection::try_from(value).ok()
269    }
270}
271
272//##################################################################
273
274#[cfg(test)]
275mod test {
276    use super::*;
277    use crate::AutosarModelAbstraction;
278    use autosar_data::AutosarVersion;
279    use datatype::{BaseTypeEncoding, ImplementationDataTypeSettings};
280
281    #[test]
282    fn test_client_server_interface() {
283        let model = AutosarModelAbstraction::create("filename", AutosarVersion::LATEST);
284        let package = model.get_or_create_package("/package").unwrap();
285        let client_server_interface = ClientServerInterface::new("TestInterface", &package).unwrap();
286
287        assert_eq!(client_server_interface.name().unwrap(), "TestInterface");
288        assert_eq!(client_server_interface.operations().count(), 0);
289        assert_eq!(client_server_interface.possible_errors().count(), 0);
290
291        let error = client_server_interface.create_possible_error("TestError", 42).unwrap();
292        assert_eq!(client_server_interface.possible_errors().count(), 1);
293        assert_eq!(error.name().unwrap(), "TestError");
294        assert_eq!(error.error_code().unwrap(), 42);
295
296        let operation = client_server_interface.create_operation("TestOperation").unwrap();
297        assert_eq!(client_server_interface.operations().count(), 1);
298        assert_eq!(operation.name().unwrap(), "TestOperation");
299        assert_eq!(operation.arguments().count(), 0);
300
301        operation.add_possible_error(&error).unwrap();
302        assert_eq!(operation.possible_errors().count(), 1);
303
304        let base_type = package
305            .create_sw_base_type("base", 32, BaseTypeEncoding::None, None, None, None)
306            .unwrap();
307        let impl_settings = ImplementationDataTypeSettings::Value {
308            name: "ImplementationValue".to_string(),
309            base_type,
310            compu_method: None,
311            data_constraint: None,
312        };
313        let datatype = package.create_implementation_data_type(&impl_settings).unwrap();
314        let argument = operation
315            .create_argument("TestArgument", &datatype, ArgumentDirection::In)
316            .unwrap();
317        assert_eq!(argument.name().unwrap(), "TestArgument");
318        assert_eq!(argument.data_type().unwrap().name().unwrap(), "ImplementationValue");
319        assert_eq!(argument.direction().unwrap(), ArgumentDirection::In);
320        assert_eq!(operation.arguments().count(), 1);
321    }
322}