AAS HTTP Client Documentation
Loading...
Searching...
No Matches
sm_registry_implementation.py
Go to the documentation of this file.
1"""Submodel Registry Implementation Module."""
2
3import json
4import logging
5from typing import TYPE_CHECKING
6
7import requests
8from pydantic import BaseModel
9
10if TYPE_CHECKING:
11 from aas_http_client.classes.client.aas_client import AasHttpClient
12
13
14from aas_http_client.utilities.constants import LogIntensity
15from aas_http_client.utilities.encoder import encode_base_64
17 STATUS_CODE_200,
18 STATUS_CODE_201,
19 STATUS_CODE_204,
20 STATUS_CODE_404,
21 log_response,
22)
23
24_logger = logging.getLogger(__name__)
25
26
28 """Implementation of Submodel Registry related API calls."""
29
30 def __init__(self, client: "AasHttpClient"):
31 """Initializes the SubmodelRegistryImplementation with the given client."""
32 self._client = client
33
34 session = client.get_session()
35 if session is None:
36 raise ValueError(
37 "HTTP session is not initialized in the client. Call 'initialize()' method of the client before creating SubmodelRegistryImplementation instance."
38 )
39
40 self._session: requests.Session = session
41
42 # GET /submodel-descriptors/{submodelIdentifier}
43 def get_submodel_descriptor_by_id(self, submodel_identifier: str) -> dict | None:
44 """Returns the Submodel Descriptor for the given submodel identifier.
45
46 :param submodel_identifier: The unique identifier of the Submodel Descriptor
47 :return: Submodel Descriptor data or None if an error occurred
48 """
49 if not self._client.encoded_ids:
50 submodel_identifier = encode_base_64(submodel_identifier)
52 url = f"{self._client.base_url}/submodel-descriptors/{submodel_identifier}"
53
54 self._client.set_token()
55
56 try:
57 response = self._session.get(url, timeout=self._client.time_out)
58 _logger.debug(f"Call REST API url '{response.url}'")
59
60 if response.status_code == STATUS_CODE_404:
61 if self._client.get_log_intensity() == LogIntensity.HIGH:
62 _logger.warning(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
63 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
64 _logger.debug(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
65
66 _logger.debug(response.text)
67 return None
68
69 if response.status_code != STATUS_CODE_200:
70 log_response(response)
71 return None
72
73 except requests.exceptions.RequestException as e:
74 _logger.error(f"Error call REST API: {e}")
75 return None
76
77 content = response.content.decode("utf-8")
78 return json.loads(content)
79
80 # PUT /submodel-descriptors/{submodelIdentifier}
81 def put_submodel_descriptor_by_id(self, submodel_identifier: str, request_body: dict) -> bool:
82 """Creates or updates an existing Submodel Descriptor.
83
84 :param submodel_identifier: The unique identifier of the Submodel Descriptor
85 :param request_body: Submodel Descriptor object
86 :return: Updated Submodel Descriptor data or None if an error occurred
87 """
88 if not self._client.encoded_ids:
89 submodel_identifier = encode_base_64(submodel_identifier)
91 url = f"{self._client.base_url}/submodel-descriptors/{submodel_identifier}"
92
93 self._client.set_token()
94
95 try:
96 response = self._session.put(url, json=request_body, timeout=self._client.time_out)
97 _logger.debug(f"Call REST API url '{response.url}'")
98
99 if response.status_code == STATUS_CODE_404:
100 if self._client.get_log_intensity() == LogIntensity.HIGH:
101 _logger.warning(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
102 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
103 _logger.debug(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
104
105 _logger.debug(response.text)
106 return False
107
108 if response.status_code != STATUS_CODE_204:
109 log_response(response)
110 return False
111
112 except requests.exceptions.RequestException as e:
113 _logger.error(f"Error call REST API: {e}")
114 return False
115
116 return True
117
118 # DELETE /submodel-descriptors/{submodelIdentifier}
119 def delete_submodel_descriptor_by_id(self, submodel_identifier: str) -> bool:
120 """Deletes a Submodel Descriptor, i.e. de-registers a submodel.
121
122 :param submodel_identifier: The unique identifier of the Submodel Descriptor
123 :return: True if deletion was successful, False otherwise
124 """
125 if not self._client.encoded_ids:
126 submodel_identifier = encode_base_64(submodel_identifier)
128 url = f"{self._client.base_url}/submodel-descriptors/{submodel_identifier}"
129
130 self._client.set_token()
131
132 try:
133 response = self._session.delete(url, timeout=self._client.time_out)
134 _logger.debug(f"Call REST API url '{response.url}'")
135
136 if response.status_code == STATUS_CODE_404:
137 if self._client.get_log_intensity() == LogIntensity.HIGH:
138 _logger.warning(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
139 elif self._client.get_log_intensity() == LogIntensity.STANDARD:
140 _logger.debug(f"Submodel Descriptor with id '{submodel_identifier}' not found.")
141
142 _logger.debug(response.text)
143 return False
144
145 if response.status_code != STATUS_CODE_204:
146 log_response(response)
147 return False
148
149 except requests.exceptions.RequestException as e:
150 _logger.error(f"Error call REST API: {e}")
151 return False
152
153 return True
154
155 # GET /submodel-descriptors
156 def get_all_submodel_descriptors(self, limit: int = 100, cursor: str = "") -> dict | None:
157 """Returns all Submodel Descriptors.
158
159 :param limit: The maximum number of elements in the response array
160 :param cursor: A server-generated identifier retrieved from pagingMetadata that specifies from which position the result listing should continue
161 :return: Submodel Descriptors data or None if an error occurred
162 """
163 url = f"{self._client.base_url}/submodel-descriptors"
164
165 params: dict[str, str] = {}
166 if limit:
167 params["limit"] = str(limit)
168 if cursor:
169 params["cursor"] = cursor
170
171 self._client.set_token()
172
173 try:
174 response = self._session.get(url, params=params, timeout=self._client.time_out)
175 _logger.debug(f"Call REST API url '{response.url}'")
176
177 if response.status_code != STATUS_CODE_200:
178 log_response(response)
179 return None
180
181 except requests.exceptions.RequestException as e:
182 _logger.error(f"Error call REST API: {e}")
183 return None
184
185 content = response.content.decode("utf-8")
186 return json.loads(content)
187
188 # POST /submodel-descriptors
189 def post_submodel_descriptor(self, request_body: dict) -> dict | None:
190 """Creates a new Submodel Descriptor, i.e. registers a submodel.
191
192 :param request_body: Submodel Descriptor object
193 :return: Created Submodel Descriptor data or None if an error occurred
194 """
195 url = f"{self._client.base_url}/submodel-descriptors"
196
197 self._client.set_token()
198
199 try:
200 response = self._session.post(url, json=request_body, timeout=self._client.time_out)
201 _logger.debug(f"Call REST API url '{response.url}'")
202
203 if response.status_code != STATUS_CODE_201:
204 log_response(response)
205 return None
206
207 except requests.exceptions.RequestException as e:
208 _logger.error(f"Error call REST API: {e}")
209 return None
210
211 content = response.content.decode("utf-8")
212 return json.loads(content)
213
214 # DELETE /submodel-descriptors
215 def delete_all_submodel_descriptors(self) -> bool:
216 """Deletes all Submodel Descriptors.
217
218 :return: True if deletion was successful, False otherwise
219 """
220 url = f"{self._client.base_url}/submodel-descriptors"
221
222 self._client.set_token()
223
224 try:
225 response = self._session.delete(url, timeout=self._client.time_out)
226 _logger.debug(f"Call REST API url '{response.url}'")
227
228 if response.status_code != STATUS_CODE_204:
229 log_response(response)
230 return False
231
232 except requests.exceptions.RequestException as e:
233 _logger.error(f"Error call REST API: {e}")
234 return False
235
236 return True
237
238 # GET /description
239 def get_self_description(self) -> dict | None:
240 """Returns the self-describing information of a network resource (ServiceDescription).
241
242 :return: self-describing information of a network resource
243 """
244 url = f"{self._client.base_url}/description"
245
246 self._client.set_token()
247
248 try:
249 response = self._session.get(url, timeout=self._client.time_out)
250 _logger.debug(f"Call REST API url '{response.url}'")
251
252 if response.status_code != STATUS_CODE_200:
253 log_response(response)
254 return None
255
256 except requests.exceptions.RequestException as e:
257 _logger.error(f"Error call REST API: {e}")
258 return None
259
260 content = response.content.decode("utf-8")
261 return json.loads(content)
bool delete_submodel_descriptor_by_id(self, str submodel_identifier)
Deletes a Submodel Descriptor, i.e.
dict|None get_all_submodel_descriptors(self, int limit=100, str cursor="")
Returns all Submodel Descriptors.
bool put_submodel_descriptor_by_id(self, str submodel_identifier, dict request_body)
Creates or updates an existing Submodel Descriptor.
dict|None get_submodel_descriptor_by_id(self, str submodel_identifier)
Returns the Submodel Descriptor for the given submodel identifier.
dict|None post_submodel_descriptor(self, dict request_body)
Creates a new Submodel Descriptor, i.e.
dict|None get_self_description(self)
Returns the self-describing information of a network resource (ServiceDescription).
__init__(self, "AasHttpClient" client)
Initializes the SubmodelRegistryImplementation with the given client.