aas-standard-parser 0.1.6__tar.gz → 0.1.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/PKG-INFO +1 -1
  2. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/aas_standard_parser/__init__.py +2 -2
  3. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/aas_standard_parser/aid_parser.py +103 -70
  4. aas_standard_parser-0.1.8/aas_standard_parser/aimc_parser.py +272 -0
  5. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/aas_standard_parser/collection_helpers.py +26 -23
  6. aas_standard_parser-0.1.8/aas_standard_parser/demo/demo_process.py +18 -0
  7. aas_standard_parser-0.1.8/aas_standard_parser/demo/logging_handler.py +197 -0
  8. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/aas_standard_parser/submodel_parser.py +24 -26
  9. aas_standard_parser-0.1.8/aas_standard_parser/utils.py +25 -0
  10. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/aas_standard_parser.egg-info/PKG-INFO +1 -1
  11. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/aas_standard_parser.egg-info/SOURCES.txt +5 -1
  12. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/pyproject.toml +1 -1
  13. aas_standard_parser-0.1.8/tests/test_aimc_parser.py +97 -0
  14. aas_standard_parser-0.1.6/aas_standard_parser/aimc_parser.py +0 -344
  15. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/LICENSE +0 -0
  16. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/README.md +0 -0
  17. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/aas_standard_parser/reference_helpers.py +0 -0
  18. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/aas_standard_parser.egg-info/dependency_links.txt +0 -0
  19. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/aas_standard_parser.egg-info/requires.txt +0 -0
  20. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/aas_standard_parser.egg-info/top_level.txt +0 -0
  21. {aas_standard_parser-0.1.6 → aas_standard_parser-0.1.8}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aas-standard-parser
3
- Version: 0.1.6
3
+ Version: 0.1.8
4
4
  Summary: Some auxiliary functions for parsing standard submodels
5
5
  Author-email: Daniel Klein <daniel.klein@em.ag>
6
6
  License: MIT License
@@ -13,7 +13,7 @@ except importlib.metadata.PackageNotFoundError:
13
13
  __project__ = "aas-standard-parser"
14
14
  __package__ = "aas-standard-parser"
15
15
 
16
+ from aas_standard_parser import aimc_parser
16
17
  from aas_standard_parser.aid_parser import AIDParser
17
- from aas_standard_parser.aimc_parser import AIMCParser
18
18
 
19
- __all__ = ["AIMCParser", "AIDParser"]
19
+ __all__ = ["AIDParser", "aimc_parser"]
@@ -1,32 +1,44 @@
1
1
  """This module provides functions to parse AID Submodels and extract MQTT interface descriptions."""
2
+
2
3
  import base64
3
4
  from typing import Dict, List
4
5
 
5
6
  from basyx.aas.model import (
6
7
  Property,
7
8
  SubmodelElement,
8
- SubmodelElementCollection, SubmodelElementList, Submodel,
9
+ SubmodelElementCollection,
10
+ SubmodelElementList,
9
11
  )
10
12
 
11
- from aas_standard_parser.collection_helpers import find_by_semantic_id, find_all_by_semantic_id, find_by_id_short
13
+ from aas_standard_parser.collection_helpers import find_all_by_semantic_id, find_by_id_short, find_by_semantic_id
12
14
 
13
15
 
14
- class PropertyDetails:
16
+ class IProtocolBinding:
17
+ def __init__(self):
18
+ pass
19
+
20
+
21
+ class HttpProtocolBinding(IProtocolBinding):
22
+ def __init__(self, method_name: str, headers: Dict[str, str]):
23
+ super().__init__()
24
+ self.method_name = method_name
25
+ self.headers = headers
26
+
15
27
 
16
- def __init__(self, href: str, keys: List[str]):
28
+ class PropertyDetails:
29
+ def __init__(self, href: str, keys: List[str], protocol_binding: IProtocolBinding = None):
17
30
  self.href = href
18
31
  self.keys = keys
32
+ self.protocol_binding = protocol_binding
19
33
 
20
34
 
21
35
  class IAuthenticationDetails:
22
-
23
36
  def __init__(self):
24
37
  # TODO: different implementations for different AID versions
25
38
  pass
26
39
 
27
40
 
28
41
  class BasicAuthenticationDetails(IAuthenticationDetails):
29
-
30
42
  def __init__(self, user: str, password: str):
31
43
  self.user = user
32
44
  self.password = password
@@ -34,17 +46,15 @@ class BasicAuthenticationDetails(IAuthenticationDetails):
34
46
 
35
47
 
36
48
  class NoAuthenticationDetails(IAuthenticationDetails):
37
-
38
49
  def __init__(self):
39
50
  super().__init__()
40
51
 
41
52
 
42
- class AIDParser():
43
-
53
+ class AIDParser:
44
54
  def __init__(self):
45
55
  pass
46
56
 
47
- def get_base_url_from_interface(self, aid_interface: SubmodelElementCollection) -> str:
57
+ def parse_base(self, aid_interface: SubmodelElementCollection) -> str:
48
58
  """Get the base address (EndpointMetadata.base) from a SMC describing an interface in the AID."""
49
59
 
50
60
  endpoint_metadata: SubmodelElementCollection | None = find_by_semantic_id(
@@ -53,16 +63,13 @@ class AIDParser():
53
63
  if endpoint_metadata is None:
54
64
  raise ValueError(f"'EndpointMetadata' SMC not found in the provided '{aid_interface.id_short}' SMC.")
55
65
 
56
- base: Property | None = find_by_semantic_id(
57
- endpoint_metadata.value, "https://www.w3.org/2019/wot/td#baseURI"
58
- )
66
+ base: Property | None = find_by_semantic_id(endpoint_metadata.value, "https://www.w3.org/2019/wot/td#baseURI")
59
67
  if base is None:
60
68
  raise ValueError("'base' Property not found in 'EndpointMetadata' SMC.")
61
69
 
62
70
  return base.value
63
71
 
64
-
65
- def create_property_to_href_map(self, aid_interface: SubmodelElementCollection) -> Dict[str, PropertyDetails]:
72
+ def parse_properties(self, aid_interface: SubmodelElementCollection) -> Dict[str, PropertyDetails]:
66
73
  """Find all first-level and nested properties in a provided SMC describing one interface in the AID.
67
74
  Map each property (either top-level or nested) to the according 'href' attribute.
68
75
  Nested properties are further mapped to the hierarchical list of keys
@@ -88,38 +95,58 @@ class AIDParser():
88
95
  fl_properties: List[SubmodelElement] = find_all_by_semantic_id(
89
96
  properties.value, "https://admin-shell.io/idta/AssetInterfacesDescription/1/0/PropertyDefinition"
90
97
  )
91
- # TODO: some AIDs have typos in that semanticId but we only support the official ones
92
- #fl_properties_alternative: List[SubmodelElement] = find_all_by_semantic_id(
93
- # properties.value, "https://admin-shell.io/idta/AssetInterfaceDescription/1/0/PropertyDefinition"
94
- #)
95
- #fl_properties.extend(fl_properties_alternative)
96
98
  if fl_properties is None:
97
- #raise ValueError(f"No first-level 'property' SMC not found in 'properties' SMC.")
99
+ print(f"WARN: No first-level 'property' SMC not found in 'properties' SMC.")
98
100
  return {}
99
101
 
100
- def traverse_property(smc: SubmodelElementCollection, parent_path: str, href: str, key_path: List[str | int],
101
- is_items=False, idx=None, is_top_level=False):
102
+ def traverse_property(
103
+ smc: SubmodelElementCollection,
104
+ parent_path: str,
105
+ href: str,
106
+ key_path: List[str | int],
107
+ is_items=False,
108
+ idx=None,
109
+ is_top_level=False,
110
+ protocol_binding: IProtocolBinding = None,
111
+ ):
102
112
  # determine local key only if not top-level
103
113
  if not is_top_level:
104
114
  if is_items and idx is not None:
105
- local_key = idx # integer index
115
+ # is a nested "items" property -> add index to the list of keys
116
+ local_key = idx
106
117
  else:
107
- key_prop = find_by_semantic_id(
108
- smc.value, "https://admin-shell.io/idta/AssetInterfacesDescription/1/0/key"
109
- )
110
- local_key = key_prop.value if key_prop else smc.id_short # string
118
+ # is a nested "properties" property -> add value of "key" attribute or idShort to list of keys
119
+ key_prop = find_by_semantic_id(smc.value, "https://admin-shell.io/idta/AssetInterfacesDescription/1/0/key")
120
+ local_key = key_prop.value if key_prop else smc.id_short
111
121
  new_key_path = key_path + [local_key]
112
122
  else:
113
- new_key_path = key_path # top-level: no key added
114
-
115
- # register this property
123
+ # TODO: use the key of the first-level property (or its idShort otherwise)
124
+ # is a top-level property
125
+ # key_prop: Property | None = find_by_semantic_id(
126
+ # smc.value, "https://admin-shell.io/idta/AssetInterfacesDescription/1/0/key"
127
+ # )
128
+ # local_key = key_prop.value if key_prop else smc.id_short
129
+ # new_key_path = [local_key]
130
+
131
+ new_key_path = key_path
132
+ # NOTE (Tom Gneuß, 2025-10-20)
133
+ # See GitHub Issue: https://github.com/admin-shell-io/submodel-templates/issues/197
134
+ # First-level properties are allowed to have a "key" attribute - otherwise the idShort path is used.
135
+ # However, complex first-level properties would represent, e.g., the JSON payload (object) itself.
136
+ # This JSON payload does only have keys for nested elements.
137
+ # So, using the key (or idShort) of the first-level property to get the JSON object from the payload
138
+ # is not possible.
139
+ # On the other hand: the first-level property could intentionally be something within the JSON object.
140
+ # In that case, having a "key" (or using the idSort) is entirely valid.
141
+ # How to distinguish both cases?
142
+
143
+ # create the idShort path of this property
116
144
  full_path = f"{parent_path}.{smc.id_short}"
117
- mapping[full_path] = PropertyDetails(href, new_key_path)
145
+ # add this property with all its details to the mapping -> href (from top-level parent if this is nested),
146
+ # protocol bindings (from top-level parent if this is nested), list of keys
147
+ mapping[full_path] = PropertyDetails(href, new_key_path, protocol_binding)
118
148
 
119
149
  # traverse nested "properties" or "items"
120
- # (nested properties = object members, nested items = array elements)
121
- # TODO: some apparently use the wrong semanticId:
122
- # "https://www.w3.org/2019/wot/td#PropertyAffordance"
123
150
  for nested_sem_id in [
124
151
  "https://www.w3.org/2019/wot/json-schema#properties",
125
152
  "https://www.w3.org/2019/wot/json-schema#items",
@@ -133,52 +160,66 @@ class AIDParser():
133
160
  nested_properties: List[SubmodelElement] = find_all_by_semantic_id(
134
161
  nested_group.value, "https://www.w3.org/2019/wot/json-schema#propertyName"
135
162
  )
136
- # TODO: some AIDs have typos or use wrong semanticIds but we only support the official ones
137
- #nested_properties_alternative1: List[SubmodelElement] = find_all_by_semantic_id(
138
- # nested_group.value, "https://admin-shell.io/idta/AssetInterfaceDescription/1/0/PropertyDefinition"
139
- #)
140
- # nested_properties_alternative2: List[SubmodelElement] = find_all_by_semantic_id(
141
- # nested_group.value, "https://admin-shell.io/idta/AssetInterfacesDescription/1/0/PropertyDefinition"
142
- # )
143
- #nested_properties.extend(nested_properties_alternative1)
144
- #nested_properties.extend(nested_properties_alternative2)
145
163
 
146
164
  # traverse all nested properties/items recursively
147
165
  for idx, nested in enumerate(nested_properties):
148
166
  if nested_sem_id.endswith("#items"):
149
- # for arrays: append index instead of property key
167
+ # for arrays: append index instead of "key" attribute
150
168
  traverse_property(nested, full_path, href, new_key_path, is_items=True, idx=idx)
151
169
  else:
152
170
  traverse_property(nested, full_path, href, new_key_path)
153
171
 
154
172
  # process all first-level properties
155
- for fl_property in fl_properties:
156
- forms: SubmodelElementCollection | None = find_by_semantic_id(
157
- fl_property.value, "https://www.w3.org/2019/wot/td#hasForm"
158
- )
173
+ for fl_property in fl_properties: # type: SubmodelElementCollection
174
+ forms: SubmodelElementCollection | None = find_by_semantic_id(fl_property.value, "https://www.w3.org/2019/wot/td#hasForm")
159
175
  if forms is None:
160
176
  raise ValueError(f"'forms' SMC not found in '{fl_property.id_short}' SMC.")
161
177
 
162
- href: Property | None = find_by_semantic_id(
163
- forms.value, "https://www.w3.org/2019/wot/hypermedia#hasTarget"
164
- )
178
+ href: Property | None = find_by_semantic_id(forms.value, "https://www.w3.org/2019/wot/hypermedia#hasTarget")
165
179
  if href is None:
166
180
  raise ValueError("'href' Property not found in 'forms' SMC.")
167
181
 
182
+ # get the href value of the first-level property
168
183
  href_value = href.value
184
+
185
+ # construct the idShort path up to "Interface_.InteractionMetadata.properties"
186
+ # will be used as prefix for the idShort paths of the first-level and nested properties
169
187
  idshort_path_prefix = f"{aid_interface.id_short}.{interaction_metadata.id_short}.{properties.id_short}"
170
188
 
189
+ # check which protocol-specific subtype of forms is used
190
+ # there is no clean solution for determining the subtype (e.g., a supplSemId)
191
+ # -> can only be figured out if the specific fields are present
192
+ protocol_binding: IProtocolBinding = None
193
+
194
+ # ... try HTTP ("htv_methodName" must be present)
195
+ htv_method_name: Property | None = find_by_semantic_id(forms.value, "https://www.w3.org/2011/http#methodName")
196
+ if htv_method_name is not None:
197
+ protocol_binding: HttpProtocolBinding = HttpProtocolBinding(htv_method_name.value, {})
198
+ htv_headers: SubmodelElementCollection | None = find_by_semantic_id(forms.value, "https://www.w3.org/2011/http#headers")
199
+ if htv_headers is not None:
200
+ for header in htv_headers.value: # type: SubmodelElementCollection
201
+ htv_field_name: Property | None = find_by_semantic_id(header.value, "https://www.w3.org/2011/http#fieldName")
202
+ htv_field_value: Property | None = find_by_semantic_id(header.value, "https://www.w3.org/2011/http#fieldValue")
203
+ protocol_binding.headers[htv_field_name.value] = htv_field_value.value
204
+
205
+ # TODO: the other protocols
206
+ # ... try Modbus
207
+ # ... try MQTT
208
+
209
+ # recursively parse the first-level property and its nested properties (if any)
171
210
  traverse_property(
172
- fl_property,
173
- idshort_path_prefix,
174
- href_value,
175
- [],
176
- is_top_level=True
211
+ smc=fl_property,
212
+ parent_path=idshort_path_prefix,
213
+ href=href_value,
214
+ key_path=[],
215
+ is_items=False,
216
+ idx=None,
217
+ is_top_level=True,
218
+ protocol_binding=protocol_binding,
177
219
  )
178
220
 
179
221
  return mapping
180
222
 
181
-
182
223
  def parse_security(self, aid_interface: SubmodelElementCollection) -> IAuthenticationDetails:
183
224
  """Extract the authentication details (EndpointMetadata.security) from the provided interface in the AID.
184
225
 
@@ -191,9 +232,7 @@ class AIDParser():
191
232
  if endpoint_metadata is None:
192
233
  raise ValueError(f"'EndpointMetadata' SMC not found in the provided '{aid_interface.id_short}' SMC.")
193
234
 
194
- security: SubmodelElementList | None = find_by_semantic_id(
195
- endpoint_metadata.value, "https://www.w3.org/2019/wot/td#hasSecurityConfiguration"
196
- )
235
+ security: SubmodelElementList | None = find_by_semantic_id(endpoint_metadata.value, "https://www.w3.org/2019/wot/td#hasSecurityConfiguration")
197
236
  if security is None:
198
237
  raise ValueError("'security' SML not found in 'EndpointMetadata' SMC.")
199
238
 
@@ -212,16 +251,12 @@ class AIDParser():
212
251
  raise ValueError("'securityDefinitions' SMC not found in 'EndpointMetadata' SMC.")
213
252
 
214
253
  # find the security scheme SMC with the same idShort as mentioned in the reference "sc"
215
- referenced_security: SubmodelElementCollection | None = find_by_id_short(
216
- security_definitions.value, sc_idshort
217
- )
254
+ referenced_security: SubmodelElementCollection | None = find_by_id_short(security_definitions.value, sc_idshort)
218
255
  if referenced_security is None:
219
256
  raise ValueError(f"Referenced security scheme '{sc_idshort}' SMC not found in 'securityDefinitions' SMC")
220
257
 
221
258
  # get the name of the security scheme
222
- scheme: Property | None = find_by_semantic_id(
223
- referenced_security.value, "https://www.w3.org/2019/wot/security#SecurityScheme"
224
- )
259
+ scheme: Property | None = find_by_semantic_id(referenced_security.value, "https://www.w3.org/2019/wot/security#SecurityScheme")
225
260
  if scheme is None:
226
261
  raise ValueError(f"'scheme' Property not found in referenced security scheme '{sc_idshort}' SMC.")
227
262
 
@@ -232,9 +267,7 @@ class AIDParser():
232
267
  auth_details = NoAuthenticationDetails()
233
268
 
234
269
  case "basic":
235
- basic_sc_name: Property | None = find_by_semantic_id(
236
- referenced_security.value, "https://www.w3.org/2019/wot/security#name"
237
- )
270
+ basic_sc_name: Property | None = find_by_semantic_id(referenced_security.value, "https://www.w3.org/2019/wot/security#name")
238
271
  if basic_sc_name is None:
239
272
  raise ValueError("'name' Property not found in 'basic_sc' SMC")
240
273
 
@@ -0,0 +1,272 @@
1
+ """Parser for Mapping Configurations in AIMC Submodel."""
2
+
3
+ import json
4
+ import logging
5
+ from dataclasses import dataclass, field
6
+
7
+ import basyx.aas.adapter.json
8
+ from basyx.aas import model
9
+
10
+ import aas_standard_parser.collection_helpers as ch
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class SourceSinkRelation:
16
+ """Class representing a source-sink relation in the mapping configuration."""
17
+
18
+ aid_submodel_id: str = field(metadata={"description": "Identifier of the AID submodel used by the source reference."})
19
+ source: model.ExternalReference = field(metadata={"description": "Reference to the source property in the AID submodel."})
20
+ sink: model.ExternalReference = field(metadata={"description": "Reference to the sink property in the target submodel."})
21
+ property_name: str = field(metadata={"description": "Name of the mapped property."})
22
+ source_parent_path: list[str] = field(metadata={"description": "List of idShorts representing the parent path of the reference."})
23
+
24
+ def source_as_dict(self) -> dict:
25
+ """Convert the source reference to a dictionary.
26
+
27
+ :return: The source reference as a dictionary.
28
+ """
29
+ dict_string = json.dumps(self.source, cls=basyx.aas.adapter.json.AASToJsonEncoder)
30
+ dict_string = dict_string.replace("GlobalReference", "Submodel").replace("FragmentReference", "SubmodelElementCollection")
31
+ return json.loads(dict_string)
32
+
33
+ def sink_as_dict(self) -> dict:
34
+ """Convert the sink reference to a dictionary.
35
+
36
+ :return: The sink reference as a dictionary.
37
+ """
38
+ return json.loads(json.dumps(self.sink, cls=basyx.aas.adapter.json.AASToJsonEncoder))
39
+
40
+ def get_source_parent_property_group_name(self) -> str:
41
+ """Get the name of the parent property group from the source. Ignore 'properties' entries from the path."""
42
+ if len(self.source_parent_path) == 0:
43
+ return ""
44
+
45
+ return next((n for n in reversed(self.source_parent_path) if n != "properties"), "")
46
+
47
+
48
+ class MappingConfiguration:
49
+ """Class representing a mapping configuration."""
50
+
51
+ interface_reference: model.ReferenceElement = field(metadata={"description": "Reference to the interface in the AID submodel."})
52
+ aid_submodel_id: str = field(metadata={"description": "Identifier of the AID submodel used by the interface reference."})
53
+ source_sink_relations: list[SourceSinkRelation] = field(metadata={"description": "List of source-sink relations in the mapping configuration."})
54
+
55
+
56
+ class MappingConfigurations:
57
+ """Class representing mapping configurations from AIMC submodel."""
58
+
59
+ configurations: list[MappingConfiguration] = field(metadata={"description": "List of mapping configurations."})
60
+ aid_submodel_ids: list[str] = field(metadata={"description": "List of AID submodel IDs used in the mapping configurations."})
61
+
62
+
63
+ def get_mapping_configuration_root_element(aimc_submodel: model.Submodel) -> model.SubmodelElementCollection | None:
64
+ """Get the mapping configuration root submodel element collection from the AIMC submodel.
65
+
66
+ :param aimc_submodel: The AIMC submodel to extract the mapping configuration root from.
67
+ :return: The mapping configuration root submodel element collection or None if not found.
68
+ """
69
+ # check if AIMC submodel is None
70
+ if aimc_submodel is None:
71
+ logger.error("AIMC submodel is None.")
72
+ return None
73
+
74
+ # get 'MappingConfigurations' element list by its semantic ID
75
+ mc_element = ch.find_by_in_semantic_id(aimc_submodel.submodel_element, "idta/AssetInterfacesMappingConfiguration/1/0/MappingConfigurations")
76
+ if mc_element is None:
77
+ logger.error("'MappingConfigurations' element list not found in AIMC submodel.")
78
+
79
+ return mc_element
80
+
81
+
82
+ def get_mapping_configuration_elements(aimc_submodel: model.Submodel) -> list[model.SubmodelElementCollection] | None:
83
+ """Get all mapping configurations from the AIMC submodel.
84
+
85
+ :param aimc_submodel: The AIMC submodel to extract mapping configurations from.
86
+ :return: A dictionary containing all mapping configurations.
87
+ """
88
+ # check if AIMC submodel is None
89
+ if aimc_submodel is None:
90
+ logger.error("AIMC submodel is None.")
91
+ return None
92
+
93
+ # get mapping configuration root element
94
+ root_element = get_mapping_configuration_root_element(aimc_submodel)
95
+ if root_element is None:
96
+ return None
97
+
98
+ # find all 'MappingConfiguration' elements by their semantic ID
99
+ mapping_configurations = ch.find_all_by_in_semantic_id(root_element.value, "idta/AssetInterfacesMappingConfiguration/1/0/MappingConfiguration")
100
+
101
+ logger.debug(f"Found {len(mapping_configurations)} mapping configuration elements in AIMC submodel.")
102
+
103
+ return mapping_configurations
104
+
105
+
106
+ def parse_mapping_configurations(aimc_submodel: model.Submodel) -> MappingConfigurations:
107
+ """Parse all mapping configurations in the AIMC submodel.
108
+
109
+ :param aimc_submodel: The AIMC submodel to parse mapping configurations from.
110
+ :return: A list of parsed mapping configurations.
111
+ """
112
+ logger.info("Parse mapping configurations from AIMC submodel.")
113
+
114
+ mapping_configurations: list[MappingConfiguration] = []
115
+
116
+ # get all mapping configuration elements
117
+ mapping_configurations_elements = get_mapping_configuration_elements(aimc_submodel)
118
+ if mapping_configurations_elements is None:
119
+ logger.error("No mapping configuration elements found in AIMC submodel.")
120
+ return mapping_configurations_elements
121
+
122
+ # parse each mapping configuration element
123
+ for mc_element in mapping_configurations_elements:
124
+ mc = parse_mapping_configuration_element(mc_element)
125
+ if mc is not None:
126
+ mapping_configurations.append(mc)
127
+
128
+ logger.debug(f"Parsed {len(mapping_configurations)} mapping configurations.")
129
+
130
+ mcs = MappingConfigurations()
131
+ mcs.configurations = mapping_configurations
132
+ # add all unique AID submodel IDs from all mapping configurations
133
+ mcs.aid_submodel_ids = list({mc.aid_submodel_id for mc in mapping_configurations})
134
+
135
+ logger.debug(f"Found {len(mcs.aid_submodel_ids)} unique AID submodel IDs in mapping configurations.")
136
+ logger.debug(f"Found {len(mcs.configurations)} mapping configurations in AIMC submodel.")
137
+
138
+ return mcs
139
+
140
+
141
+ def parse_mapping_configuration_element(
142
+ mapping_configuration_element: model.SubmodelElementCollection,
143
+ ) -> MappingConfiguration | None:
144
+ """Parse a mapping configuration element.
145
+
146
+ :param mapping_configuration_element: The mapping configuration element to parse.
147
+ :return: The parsed mapping configuration or None if parsing failed.
148
+ """
149
+ if mapping_configuration_element is None:
150
+ logger.error("Mapping configuration element is None.")
151
+ return None
152
+
153
+ logger.debug(f"Parse mapping configuration '{mapping_configuration_element}'")
154
+
155
+ # get interface reference element
156
+ interface_reference = _get_interface_reference_element(mapping_configuration_element)
157
+ if interface_reference is None:
158
+ return None
159
+
160
+ source_sink_relations = _generate_source_sink_relations(mapping_configuration_element)
161
+
162
+ if len(source_sink_relations) == 0:
163
+ logger.error(f"No source-sink relations found in mapping configuration '{mapping_configuration_element.id_short}'.")
164
+ return None
165
+
166
+ # check if all relations have the same AID submodel
167
+ aid_submodel_ids = list({source_sink_relation.aid_submodel_id for source_sink_relation in source_sink_relations})
168
+
169
+ if len(aid_submodel_ids) != 1:
170
+ logger.error(
171
+ f"Multiple AID submodel IDs found in mapping configuration '{mapping_configuration_element.id_short}': {aid_submodel_ids}. Expected exactly one AID submodel ID."
172
+ )
173
+ return None
174
+
175
+ mc = MappingConfiguration()
176
+ mc.interface_reference = interface_reference
177
+ mc.source_sink_relations = source_sink_relations
178
+ # add all unique AID submodel IDs from source-sink relations
179
+ mc.aid_submodel_id = aid_submodel_ids[0]
180
+ return mc
181
+
182
+
183
+ def _get_interface_reference_element(
184
+ mapping_configuration_element: model.SubmodelElementCollection,
185
+ ) -> model.ReferenceElement | None:
186
+ """Get the interface reference ID from the mapping configuration element.
187
+
188
+ :param mapping_configuration_element: The mapping configuration element to extract the interface reference ID from.
189
+ :return: The interface reference ID or None if not found.
190
+ """
191
+ logger.debug(f"Get 'InterfaceReference' from mapping configuration '{mapping_configuration_element}'.")
192
+
193
+ interface_ref: model.ReferenceElement = ch.find_by_in_semantic_id(
194
+ mapping_configuration_element, "idta/AssetInterfacesMappingConfiguration/1/0/InterfaceReference"
195
+ )
196
+
197
+ if interface_ref is None or not isinstance(interface_ref, model.ReferenceElement):
198
+ logger.error(f"'InterfaceReference' not found in mapping configuration '{mapping_configuration_element.id_short}'.")
199
+ return None
200
+
201
+ if interface_ref.value is None or len(interface_ref.value.key) == 0:
202
+ logger.error(f"'InterfaceReference' has no value in mapping configuration '{mapping_configuration_element.id_short}'.")
203
+ return None
204
+
205
+ return interface_ref
206
+
207
+
208
+ def _generate_source_sink_relations(mapping_configuration_element: model.SubmodelElementCollection) -> list[SourceSinkRelation]:
209
+ source_sink_relations: list[SourceSinkRelation] = []
210
+
211
+ logger.debug(f"Get 'MappingSourceSinkRelations' from mapping configuration '{mapping_configuration_element}'.")
212
+
213
+ relations_list: model.SubmodelElementList = ch.find_by_in_semantic_id(
214
+ mapping_configuration_element, "/idta/AssetInterfacesMappingConfiguration/1/0/MappingSourceSinkRelations"
215
+ )
216
+
217
+ if relations_list is None or not isinstance(relations_list, model.SubmodelElementList):
218
+ logger.error(f"'MappingSourceSinkRelations' not found in mapping configuration '{mapping_configuration_element.id_short}'.")
219
+ return source_sink_relations
220
+
221
+ for source_sink_relation in relations_list.value:
222
+ logger.debug(f"Parse source-sink relation '{source_sink_relation}'.")
223
+
224
+ if not isinstance(source_sink_relation, model.RelationshipElement):
225
+ logger.warning(f"'{source_sink_relation}' is not a RelationshipElement")
226
+ continue
227
+
228
+ if source_sink_relation.first is None or len(source_sink_relation.first.key) == 0:
229
+ logger.warning(f"'first' reference is missing in RelationshipElement '{source_sink_relation.id_short}'")
230
+ continue
231
+
232
+ if source_sink_relation.second is None or len(source_sink_relation.second.key) == 0:
233
+ logger.warning(f"'second' reference is missing in RelationshipElement '{source_sink_relation.id_short}'")
234
+ continue
235
+
236
+ source_ref = source_sink_relation.first
237
+
238
+ global_ref = next((key for key in source_ref.key if key.type == model.KeyTypes.GLOBAL_REFERENCE), None)
239
+
240
+ if global_ref is None:
241
+ logger.warning(f"No GLOBAL_REFERENCE key found in 'first' reference of RelationshipElement '{source_sink_relation.id_short}'")
242
+ continue
243
+
244
+ last_fragment_ref = next(
245
+ (key for key in reversed(source_ref.key) if key.type == model.KeyTypes.FRAGMENT_REFERENCE),
246
+ None,
247
+ )
248
+
249
+ if last_fragment_ref is None:
250
+ logger.warning(f"No FRAGMENT_REFERENCE key found in 'first' reference of RelationshipElement '{source_sink_relation.id_short}'")
251
+ continue
252
+
253
+ relation = SourceSinkRelation()
254
+ relation.source = source_sink_relation.first
255
+ relation.sink = source_sink_relation.second
256
+ relation.aid_submodel_id = global_ref.value
257
+ relation.property_name = last_fragment_ref.value
258
+ relation.source_parent_path = _get_reference_parent_path(source_ref)
259
+
260
+ source_sink_relations.append(relation)
261
+
262
+ return source_sink_relations
263
+
264
+
265
+ def _get_reference_parent_path(reference: model.ExternalReference) -> list[str]:
266
+ """Get the parent path of a reference as a list of idShorts.
267
+
268
+ :param reference: The reference to extract the parent path from.
269
+ :return: A list of idShorts representing the parent path.
270
+ """
271
+ # Exclude the last key which is the actual element
272
+ return [key.value for key in reference.key[:-1] if key.type == model.KeyTypes.FRAGMENT_REFERENCE]