autosar_data_abstraction/communication/controller/
ethernet.rs

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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
use crate::communication::{
    AbstractCommunicationConnector, AbstractCommunicationController, EthernetPhysicalChannel, EthernetVlanInfo,
};
use crate::{abstraction_element, AbstractionElement, AutosarAbstractionError, EcuInstance};
use autosar_data::{AutosarDataError, AutosarModel, Element, ElementName, ElementsIterator, WeakElement};

/// An `EcuInstance` needs an `EthernetCommunicationController` in order to connect to an ethernet cluster.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EthernetCommunicationController(Element);
abstraction_element!(EthernetCommunicationController, EthernetCommunicationController);

impl EthernetCommunicationController {
    // create an EthernetCommunicationController
    pub(crate) fn new(
        name: &str,
        ecu: &EcuInstance,
        mac_address: Option<String>,
    ) -> Result<Self, AutosarAbstractionError> {
        let commcontrollers = ecu.element().get_or_create_sub_element(ElementName::CommControllers)?;
        let ctrl = commcontrollers.create_named_sub_element(ElementName::EthernetCommunicationController, name)?;
        let ethccc = ctrl
            .create_sub_element(ElementName::EthernetCommunicationControllerVariants)?
            .create_sub_element(ElementName::EthernetCommunicationControllerConditional)?;
        if let Some(mac_address) = mac_address {
            // creating the mac address element fails if the supplied string has an invalid format
            let result = ethccc
                .create_sub_element(ElementName::MacUnicastAddress)
                .and_then(|mua| mua.set_character_data(mac_address));
            if let Err(mac_address_error) = result {
                let _ = commcontrollers.remove_sub_element(ctrl);
                return Err(mac_address_error.into());
            }
        }
        let coupling_port_name = format!("{name}_CouplingPort");
        let _ = ethccc
            .create_sub_element(ElementName::CouplingPorts)
            .and_then(|cps| cps.create_named_sub_element(ElementName::CouplingPort, &coupling_port_name));

        Ok(Self(ctrl))
    }

    /// return an iterator over the [`EthernetPhysicalChannel`]s connected to this controller
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # use autosar_data_abstraction::*;
    /// # let model = AutosarModel::new();
    /// # model.create_file("filename", AutosarVersion::Autosar_00048).unwrap();
    /// # let package = ArPackage::get_or_create(&model, "/pkg1").unwrap();
    /// # let system = package.create_system("System", SystemCategory::SystemExtract).unwrap();
    /// # let ecu_instance = system.create_ecu_instance("ecu_name", &package).unwrap();
    /// let ethernet_controller = ecu_instance.create_ethernet_communication_controller("EthCtrl", None).unwrap();
    /// # let cluster = system.create_ethernet_cluster("Cluster", &package).unwrap();
    /// # let physical_channel = cluster.create_physical_channel("Channel", None).unwrap();
    /// ethernet_controller.connect_physical_channel("connection", &physical_channel).unwrap();
    /// for channel in ethernet_controller.connected_channels() {
    ///     // ...
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// - [`AutosarAbstractionError::ModelError`] An error occurred in the Autosar model while trying to create the ECU-INSTANCE
    pub fn connected_channels(&self) -> impl Iterator<Item = EthernetPhysicalChannel> {
        if let Ok(ecu) = self.ecu_instance().map(|ecuinstance| ecuinstance.element().clone()) {
            EthernetCtrlChannelsIterator::new(self, &ecu)
        } else {
            EthernetCtrlChannelsIterator {
                connector_iter: None,
                comm_controller: self.0.clone(),
                model: None,
            }
        }
    }

    /// Connect this [`EthernetCommunicationController`] inside an [`EcuInstance`] to an [`EthernetPhysicalChannel`] in the [`crate::System`]
    ///
    /// Creates an `EthernetCommunicationConnector` in the [`EcuInstance`] that contains this [`EthernetCommunicationController`].
    ///
    /// This function establishes the relationships:
    ///  - [`EthernetPhysicalChannel`] -> `EthernetCommunicationConnector`
    ///  - `EthernetCommunicationConnector` -> [`EthernetCommunicationController`]
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # use autosar_data_abstraction::*;
    /// # let model = AutosarModel::new();
    /// # model.create_file("filename", AutosarVersion::Autosar_00048).unwrap();
    /// # let package = ArPackage::get_or_create(&model, "/pkg1").unwrap();
    /// # let system = package.create_system("System", SystemCategory::SystemExtract).unwrap();
    /// # let ecu_instance = system.create_ecu_instance("ecu_name", &package).unwrap();
    /// let ethernet_controller = ecu_instance.create_ethernet_communication_controller("EthCtrl", None).unwrap();
    /// # let cluster = system.create_ethernet_cluster("Cluster", &package).unwrap();
    /// # let physical_channel = cluster.create_physical_channel("Channel", None).unwrap();
    /// ethernet_controller.connect_physical_channel("connection", &physical_channel).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// - [`AutosarAbstractionError::ModelError`] An error occurred in the Autosar model while trying to create the ECU-INSTANCE
    pub fn connect_physical_channel(
        &self,
        connection_name: &str,
        eth_channel: &EthernetPhysicalChannel,
    ) -> Result<EthernetCommunicationConnector, AutosarAbstractionError> {
        let ecu: Element = self.0.named_parent()?.unwrap();
        let cluster_of_channel = eth_channel.cluster()?;

        // There can be multiple connectors referring to a single EthernetCommunicationController,
        // but all of these connectors must refer to different PhysicalChannels
        // (= VLANs) of the same EthernetCluster.
        for phys_channel in self.connected_channels() {
            if phys_channel == *eth_channel {
                return Err(AutosarAbstractionError::ItemAlreadyExists);
            }

            if phys_channel.cluster()? != cluster_of_channel {
                return Err(AutosarAbstractionError::InvalidParameter(
                    "The EthernetCommunicationController may only refer to different channels within the same cluster"
                        .to_string(),
                ));
            }
        }

        // create a new connector
        let connectors = ecu.get_or_create_sub_element(ElementName::Connectors)?;
        let connector = EthernetCommunicationConnector::new(connection_name, &connectors, self)?;

        // if the ethernet physical channel has a category (WIRED / WIRELESS / CANXL) then
        // set the category of the connector to the same value
        if let Some(category) = eth_channel
            .element()
            .get_sub_element(ElementName::Category)
            .and_then(|cat| cat.character_data())
            .and_then(|cdata| cdata.string_value())
        {
            let _ = connector
                .element()
                .create_sub_element(ElementName::Category)
                .and_then(|cat| cat.set_character_data(category));
        }

        // create a communication connector ref in the ethernet channel that refers to this connector
        let channel_connctor_refs = eth_channel
            .element()
            .get_or_create_sub_element(ElementName::CommConnectors)?;
        channel_connctor_refs
            .create_sub_element(ElementName::CommunicationConnectorRefConditional)
            .and_then(|ccrc| ccrc.create_sub_element(ElementName::CommunicationConnectorRef))
            .and_then(|ccr| ccr.set_reference_target(connector.element()))?;

        // if the PhysicalChannel has VLAN info AND if there is a coupling port in this CommunicationController
        // then the coupling port should link to the PhysicalChannel / VLAN
        if let Some(EthernetVlanInfo { .. }) = eth_channel.vlan_info() {
            if let Some(coupling_port) = self
                .0
                .get_sub_element(ElementName::EthernetCommunicationControllerVariants)
                .and_then(|eccv| eccv.get_sub_element(ElementName::EthernetCommunicationControllerConditional))
                .and_then(|eccc| eccc.get_sub_element(ElementName::CouplingPorts))
                .and_then(|cps| cps.get_sub_element(ElementName::CouplingPort))
            {
                coupling_port
                    .get_or_create_sub_element(ElementName::VlanMemberships)
                    .and_then(|vms| vms.create_sub_element(ElementName::VlanMembership))
                    .and_then(|vm| vm.create_sub_element(ElementName::VlanRef))
                    .and_then(|vr| vr.set_reference_target(eth_channel.element()))?;
            }
        }

        Ok(connector)
    }
}

impl AbstractCommunicationController for EthernetCommunicationController {}

//##################################################################

/// A connector between an [`EthernetCommunicationController`] in an ECU and an [`EthernetPhysicalChannel`]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EthernetCommunicationConnector(Element);
abstraction_element!(EthernetCommunicationConnector, EthernetCommunicationConnector);

impl EthernetCommunicationConnector {
    pub(crate) fn new(
        name: &str,
        parent: &Element,
        controller: &EthernetCommunicationController,
    ) -> Result<Self, AutosarAbstractionError> {
        let connector = parent.create_named_sub_element(ElementName::EthernetCommunicationConnector, name)?;
        connector
            .create_sub_element(ElementName::CommControllerRef)
            .and_then(|refelem| refelem.set_reference_target(&controller.0))?;
        Ok(Self(connector))
    }
}

impl AbstractCommunicationConnector for EthernetCommunicationConnector {
    type CommunicationControllerType = EthernetCommunicationController;

    fn controller(&self) -> Result<Self::CommunicationControllerType, AutosarAbstractionError> {
        let controller = self
            .element()
            .get_sub_element(ElementName::CommControllerRef)
            .ok_or_else(|| {
                AutosarAbstractionError::ModelError(AutosarDataError::ElementNotFound {
                    target: ElementName::CommControllerRef,
                    parent: self.element().element_name(),
                })
            })?
            .get_reference_target()?;
        EthernetCommunicationController::try_from(controller)
    }
}

//##################################################################

#[doc(hidden)]
pub struct EthernetCtrlChannelsIterator {
    connector_iter: Option<ElementsIterator>,
    comm_controller: Element,
    model: Option<AutosarModel>,
}

impl EthernetCtrlChannelsIterator {
    fn new(controller: &EthernetCommunicationController, ecu: &Element) -> Self {
        let iter = ecu.get_sub_element(ElementName::Connectors).map(|c| c.sub_elements());
        let comm_controller = controller.element().clone();
        let model = comm_controller.model().ok();
        Self {
            connector_iter: iter,
            comm_controller,
            model,
        }
    }
}

impl Iterator for EthernetCtrlChannelsIterator {
    type Item = EthernetPhysicalChannel;

    fn next(&mut self) -> Option<Self::Item> {
        let model = self.model.as_ref()?;
        let connector_iter = self.connector_iter.as_mut()?;
        for connector in connector_iter.by_ref() {
            if connector.element_name() == ElementName::EthernetCommunicationConnector {
                if let Some(commcontroller_of_connector) = connector
                    .get_sub_element(ElementName::CommControllerRef)
                    .and_then(|ccr| ccr.get_reference_target().ok())
                {
                    if commcontroller_of_connector == self.comm_controller {
                        for ref_origin in model
                            .get_references_to(&connector.path().ok()?)
                            .iter()
                            .filter_map(WeakElement::upgrade)
                            .filter_map(|elem| elem.named_parent().ok().flatten())
                        {
                            // This assumes that each connector will only ever be referenced by at most one
                            // PhysicalChannel, which is true for well-formed files.
                            if ref_origin.element_name() == ElementName::EthernetPhysicalChannel {
                                return EthernetPhysicalChannel::try_from(ref_origin).ok();
                            }
                        }
                    }
                }
            }
        }
        None
    }
}

//##################################################################

#[cfg(test)]
mod test {
    use super::*;
    use crate::{communication::EthernetVlanInfo, ArPackage, SystemCategory};
    use autosar_data::{AutosarModel, AutosarVersion};

    #[test]
    fn controller() {
        let model = AutosarModel::new();
        model.create_file("filename", AutosarVersion::Autosar_00048).unwrap();
        let pkg = ArPackage::get_or_create(&model, "/test").unwrap();
        let system = pkg.create_system("System", SystemCategory::SystemDescription).unwrap();
        let ecu = system.create_ecu_instance("ECU", &pkg).unwrap();

        // can't create a controller with an invalid MAC address
        let result = ecu.create_ethernet_communication_controller("Controller", Some("abcdef".to_string()));
        assert!(result.is_err());

        // create a controller
        let result = ecu.create_ethernet_communication_controller("Controller", Some("01:02:03:04:05:06".to_string()));
        let controller = result.unwrap();

        // create some physical channels
        let cluster = system.create_ethernet_cluster("EthCluster", &pkg).unwrap();
        let channel1 = cluster.create_physical_channel("C1", None).unwrap();
        let vlan_info = EthernetVlanInfo {
            vlan_name: "VLAN_1".to_string(),
            vlan_id: 1,
        };
        let channel2 = cluster.create_physical_channel("C2", Some(vlan_info)).unwrap();

        // connect the controller to channel1
        let connector = controller
            .connect_physical_channel("connection_name1", &channel1)
            .unwrap();
        assert_eq!(connector.controller().unwrap(), controller);
        // can't connect to the same channel again
        let result = controller.connect_physical_channel("connection_name2", &channel1);
        assert!(result.is_err());
        // connect the controller to channel2
        let result = controller.connect_physical_channel("connection_name2", &channel2);
        assert!(result.is_ok());

        // create a different cluster and channel, then try to connect the controller to it
        let cluster2 = system.create_ethernet_cluster("EthCluster2", &pkg).unwrap();
        let channel3 = cluster2.create_physical_channel("C3", None).unwrap();
        let result = controller.connect_physical_channel("connection_name3", &channel3);
        // can't connect one ethernet controller to channels from different clusters
        assert!(result.is_err());

        let count = controller.connected_channels().count();
        assert_eq!(count, 2);

        // remove the controller and try to list its connected channels again
        let ctrl_parent = controller.element().parent().unwrap().unwrap();
        ctrl_parent.remove_sub_element(controller.element().clone()).unwrap();
        let count = controller.connected_channels().count();
        assert_eq!(count, 0);
    }

    #[test]
    fn connector() {
        let model = AutosarModel::new();
        model.create_file("filename", AutosarVersion::Autosar_00048).unwrap();
        let pkg = ArPackage::get_or_create(&model, "/test").unwrap();
        let system = pkg.create_system("System", SystemCategory::SystemDescription).unwrap();
        let ecu = system.create_ecu_instance("ECU", &pkg).unwrap();

        let controller = ecu
            .create_ethernet_communication_controller("Controller", None)
            .unwrap();
        assert_eq!(controller.ecu_instance().unwrap(), ecu);

        let cluster = system.create_ethernet_cluster("EthCluster", &pkg).unwrap();
        let channel = cluster.create_physical_channel("C1", None).unwrap();

        // create a connector
        let connector = controller
            .connect_physical_channel("connection_name", &channel)
            .unwrap();
        assert_eq!(connector.controller().unwrap(), controller);
        assert_eq!(connector.ecu_instance().unwrap(), ecu);

        // remove the connector and try to get the controller from it
        let conn_parent = connector.element().parent().unwrap().unwrap();
        conn_parent.remove_sub_element(connector.element().clone()).unwrap();
        let result = connector.controller();
        assert!(result.is_err());
    }
}