Asset Connector Documentation
Loading...
Searching...
No Matches
mqtt_asset_connector.py
Go to the documentation of this file.
1"""Asset connector module for interfacing with assets via AID and MQTT."""
2
3import json
4import logging
5
6from aas_standard_parser.reference_helpers import construct_id_short_path_from_reference
7from basyx.aas.model import ModelReference, SubmodelElementCollection
8
9from ..core.asset_connector import IAssetConnector
10from .mqtt_client import MqttClient
11
12logger = logging.getLogger(__name__)
13
14
16 """Class to connect to an asset using its AID."""
17
18 _mqtt_client: MqttClient = None
19
20 def __init__(self, aid_id: str, interface_smc: SubmodelElementCollection): # noqa: D107
21 logger.debug(f"Initializing MQTTAssetConnector for AID '{aid_id}'")
22 self._aid_id_aid_id = aid_id
24 self._interface_interface = interface_smc
25 super().__init__(aid_id, interface_smc)
26
27 async def connect(self):
28 """Connect to the MQTT broker and subscribe to relevant topics."""
29 logger.info(f"Connecting to MQTT Asset for AID '{self._aid_id}'")
30 try:
31 topics = list({v.href for v in self._parsed_properties.values()})
33 except Exception as e:
34 logger.error(f"Failed to connect to MQTT topics: {topics}. Error: {e}")
35 raise ConnectionError(f"Failed to connect to MQTT topics: {topics}. Error: {e}") from e
36
37 def _connect_to_mqtt_topics(self, mqtt_topics: list[str]) -> bool:
38 """Connect to the MQTT topics using a MQTT connector.
39
40 :param mqtt_topics: A dictionary of MQTT topics to subscribe to.
41 """
42 try:
43 logger.info(f"Create MQTT client to '{self.base}'")
44 self._mqtt_client_mqtt_client = MqttClient(self.base, mqtt_topics, self._auth)
45 logger.info(f"Subscribing to MQTT topics: {mqtt_topics}")
47 self._mqtt_client_mqtt_client.start_async()
48 return True
49 except ConnectionError as ce:
50 logger.error(f"Failed to connect to MQTT topics: {mqtt_topics}. Error: {ce}")
51 raise ConnectionError(f"Failed to connect to MQTT topics: {mqtt_topics}. Error: {ce}") from ce
52
53 return False
54
55 async def get_value(self, model_reference: ModelReference) -> str | None:
56 """Get the value for a specific model reference."""
57 # TODO: maybe try to use last cached value (if any) anyway
58 if not self._mqtt_client_mqtt_client.is_connected:
59 raise ConnectionError("AssetConnector is not connected.")
60
61 if self._mqtt_client_mqtt_client is None:
62 raise ConnectionError("MQTT Client not properly initialized.")
63
64 property_idshort_path = construct_id_short_path_from_reference(model_reference)
65
66 try:
67 topic_name = self._parsed_properties[property_idshort_path].href
68 keys = self._parsed_properties[property_idshort_path].keys
69 except KeyError:
70 raise KeyError(f"Property {property_idshort_path} not found.")
71
72 value_in_payload = self._mqtt_client_mqtt_client.get_cached_value(topic_name)
73
74 if value_in_payload is None:
75 return None
76
77 # using the keys of the potentially nested properties, dive into the complex JSON object (MQTT payload)
78 # to retrieve the requested value
79 for k in keys:
80 value_in_payload = json.dumps(json.loads(value_in_payload)[k])
81
82 result = str(value_in_payload)
83 return result
84
85 async def set_value(self, endpoint_reference: ModelReference, value: dict[str]):
86 """Set the value for a specific model reference."""
87 if not self._mqtt_client_mqtt_client.is_connected:
88 raise ConnectionError("AssetConnector is not connected.")
89
90 if self._mqtt_client_mqtt_client is None:
91 raise ConnectionError("MQTT Client not properly initialized.")
92
93 property_idshort_path = construct_id_short_path_from_reference(endpoint_reference)
94
95 try:
96 topic_name = self._property_to_href_map[property_idshort_path].href
97 except KeyError:
98 raise KeyError(f"Property {property_idshort_path} not found.")
99
100 payload = json.dumps(value)
101 self._mqtt_client_mqtt_client.publish(topic_name, payload)
102 print(f"Published to topic {topic_name} with payload {payload}")
str|None get_value(self, ModelReference model_reference)
Get the value for a specific model reference.
__init__(self, str aid_id, SubmodelElementCollection interface_smc)
Initialize the AssetConnector with AID ID and interface submodel collection.
bool _connect_to_mqtt_topics(self, list[str] mqtt_topics)
Connect to the MQTT topics using a MQTT connector.
set_value(self, ModelReference endpoint_reference, dict[str] value)
Set the value for a specific model reference.
connect(self)
Connect to the MQTT broker and subscribe to relevant topics.
Connector for managing connections to MQTT topics.