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