Asset Connector Documentation
Loading...
Searching...
No Matches
opcua_asset_connector.py
Go to the documentation of this file.
1import json
2import logging
3
4from aas_standard_parser.reference_helpers import construct_id_short_path_from_reference
5from basyx.aas.model import ModelReference, SubmodelElementCollection
6from opcua import Client
7
8from ..core.asset_connector import IAssetConnector
9
10logger = logging.getLogger(__name__)
11
12
14 """Class to connect to an asset using its AID."""
15
16 def __init__(self, aid_id: str, interface_smc: SubmodelElementCollection):
17 """Initialize the OPCUAAssetConnector for the given AID ID and interface SMC."""
18 logger.debug(f"Initializing OPCUAAssetConnector for AID '{aid_id}'")
19 self._client = None
21 self._aid_id_aid_id = aid_id
22 self._interface_interface = interface_smc
23 super().__init__(aid_id, interface_smc)
24
25 async def connect(self):
26 """Connect to the OPC UA server."""
27 logger.info(f"Connecting to OPC UA Asset for AID '{self._aid_id}'")
28 try:
29 self._client = Client(self.base)
30 self._client.connect()
31 self.is_connectedis_connected = True
32 except Exception as e:
33 logger.error(f"Failed to connect to OPC UA server: {e}")
34 raise ConnectionError(f"Failed to connect to OPC UA server. Error: {e}") from e
35
36 async def get_value(self, endpoint_reference: ModelReference) -> str | None:
37 """Get the value for a specific model reference."""
38 if not self.is_connectedis_connected:
39 raise ConnectionError("AssetConnector is not connected.")
40
41 if self._client is None:
42 raise ConnectionError("OPCUA Client not properly initialized.")
43
44 property_idshort_path = construct_id_short_path_from_reference(endpoint_reference)
45 node_id = self._parsed_properties[property_idshort_path].href
46 keys = self._parsed_properties[property_idshort_path].keys
47
48 node = self._client.get_node(node_id)
49 value_in_payload = node.get_value()
50
51 if value_in_payload is None:
52 return None
53
54 # using the keys of the potentially nested properties, dive into the complex JSON object (MQTT payload)
55 # to retrieve the requested value
56 for k in keys:
57 value_in_payload = json.dumps(json.loads(value_in_payload)[k])
58
59 return str(value_in_payload)
__init__(self, str aid_id, SubmodelElementCollection interface_smc)
Initialize the OPCUAAssetConnector for the given AID ID and interface SMC.
str|None get_value(self, ModelReference endpoint_reference)
Get the value for a specific model reference.