-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathtwin.py
More file actions
329 lines (276 loc) · 11.9 KB
/
twin.py
File metadata and controls
329 lines (276 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import json
from azext_iot.digitaltwins.providers.base import (
DigitalTwinsProvider,
ErrorResponseException,
)
from azext_iot.digitaltwins.providers.model import ModelProvider
from azext_iot.common.utility import process_json_arg, unpack_msrest_error
from knack.log import get_logger
from knack.util import CLIError
logger = get_logger(__name__)
class TwinOptions():
def __init__(self, if_match=None, if_none_match=None):
self.if_match = if_match
self.if_none_match = if_none_match
self.traceparent = None
self.tracestate = None
class TwinProvider(DigitalTwinsProvider):
def __init__(self, cmd, name, rg=None):
super(TwinProvider, self).__init__(
cmd=cmd,
name=name,
rg=rg,
)
self.model_provider = ModelProvider(cmd=cmd, name=name, rg=rg)
self.query_sdk = self.get_sdk().query
self.twins_sdk = self.get_sdk().digital_twins
def invoke_query(self, query, show_cost):
from azext_iot.digitaltwins.providers.generic import accumulate_result
try:
accumulated_result, cost = accumulate_result(
self.query_sdk.query_twins,
values_name="value",
token_name="continuationToken",
token_arg_name="continuation_token",
query=query,
)
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
query_result = {}
query_result["result"] = accumulated_result
if show_cost:
query_result["cost"] = cost
return query_result
def create(self, twin_id, model_id, if_none_match=False, properties=None):
twin_request = {
"$dtId": twin_id,
"$metadata": {"$model": model_id},
}
if properties:
properties = process_json_arg(
content=properties, argument_name="properties"
)
twin_request.update(properties)
logger.info("Twin payload %s", json.dumps(twin_request))
try:
options = TwinOptions(if_none_match=("*" if if_none_match else None))
return self.twins_sdk.add(id=twin_id, twin=twin_request, digital_twins_add_options=options)
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
def get(self, twin_id):
try:
return self.twins_sdk.get_by_id(id=twin_id, raw=True).response.json()
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
def update(self, twin_id, json_patch, etag=None):
json_patch = process_json_arg(content=json_patch, argument_name="json-patch")
json_patch_collection = []
if isinstance(json_patch, dict):
json_patch_collection.append(json_patch)
if isinstance(json_patch, list):
json_patch_collection.extend(json_patch)
logger.info("Patch payload %s", json.dumps(json_patch_collection))
try:
options = TwinOptions(if_match=(etag if etag else "*"))
self.twins_sdk.update(
id=twin_id, patch_document=json_patch_collection, digital_twins_update_options=options, raw=True
)
return self.get(twin_id=twin_id)
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
def delete(self, twin_id, etag=None):
try:
options = TwinOptions(if_match=(etag if etag else "*"))
self.twins_sdk.delete(id=twin_id, digital_twins_delete_options=options, raw=True)
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
def delete_all(self, only_relationships=False):
# need to get all twins
query = "select * from digitaltwins"
twins = self.invoke_query(query=query, show_cost=False)["result"]
print(f"Found {len(twins)} twin(s).")
# go through and delete all
for twin in twins:
try:
self.delete_all_relationship(
twin_id=twin["$dtId"]
)
if not only_relationships:
self.delete(twin_id=twin["$dtId"])
except CLIError as e:
logger.warn(f"Could not delete twin {twin['$dtId']}. The error is {e}")
def add_relationship(
self,
twin_id,
target_twin_id,
relationship_id,
relationship,
if_none_match=False,
properties=None,
):
relationship_request = {
"$targetId": target_twin_id,
"$relationshipName": relationship,
}
if properties:
properties = process_json_arg(
content=properties, argument_name="properties"
)
relationship_request.update(properties)
logger.info("Relationship payload %s", json.dumps(relationship_request))
try:
options = TwinOptions(if_none_match=("*" if if_none_match else None))
return self.twins_sdk.add_relationship(
id=twin_id,
relationship_id=relationship_id,
relationship=relationship_request,
digital_twins_add_relationship_options=options,
raw=True,
).response.json()
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
def get_relationship(self, twin_id, relationship_id):
try:
return self.twins_sdk.get_relationship_by_id(
id=twin_id, relationship_id=relationship_id, raw=True
).response.json()
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
def list_relationships(
self, twin_id, incoming_relationships=False, relationship=None
):
if not incoming_relationships:
return self.twins_sdk.list_relationships(
id=twin_id, relationship_name=relationship
)
incoming_pager = self.twins_sdk.list_incoming_relationships(id=twin_id)
incoming_result = []
try:
while True:
incoming_result.extend(incoming_pager.advance_page())
except StopIteration:
pass
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
if relationship:
incoming_result = [
edge
for edge in incoming_result
if edge.relationship_name and edge.relationship_name == relationship
]
return incoming_result
def update_relationship(self, twin_id, relationship_id, json_patch, etag=None):
json_patch = process_json_arg(content=json_patch, argument_name="json-patch")
json_patch_collection = []
if isinstance(json_patch, dict):
json_patch_collection.append(json_patch)
if isinstance(json_patch, list):
json_patch_collection.extend(json_patch)
logger.info("Patch payload %s", json.dumps(json_patch_collection))
try:
options = TwinOptions(if_match=(etag if etag else "*"))
self.twins_sdk.update_relationship(
id=twin_id,
relationship_id=relationship_id,
patch_document=json_patch_collection,
digital_twins_update_relationship_options=options,
)
return self.get_relationship(
twin_id=twin_id, relationship_id=relationship_id
)
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
def delete_relationship(self, twin_id, relationship_id, etag=None):
try:
options = TwinOptions(if_match=(etag if etag else "*"))
self.twins_sdk.delete_relationship(
id=twin_id, relationship_id=relationship_id, digital_twins_delete_relationship_options=options
)
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
def delete_all_relationship(self, twin_id):
relationships = self.list_relationships(twin_id, incoming_relationships=True)
incoming_pager = self.list_relationships(twin_id)
# relationships pager needs to be advanced to get relationships
try:
while True:
relationships.extend(incoming_pager.advance_page())
except StopIteration:
pass
print(f"Found {len(relationships)} relationship(s) associated with twin {twin_id}.")
for relationship in relationships:
try:
if isinstance(relationship, dict):
self.delete_relationship(
twin_id=twin_id,
relationship_id=relationship['$relationshipId']
)
else:
self.delete_relationship(
twin_id=relationship.source_id,
relationship_id=relationship.relationship_id
)
except CLIError as e:
logger.warn(f"Could not delete relationship {relationship}. The error is {e}.")
def get_component(self, twin_id, component_path):
try:
return self.twins_sdk.get_component(
id=twin_id, component_path=component_path, raw=True
).response.json()
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
def update_component(self, twin_id, component_path, json_patch, etag=None):
json_patch = process_json_arg(content=json_patch, argument_name="json-patch")
json_patch_collection = []
if isinstance(json_patch, dict):
json_patch_collection.append(json_patch)
if isinstance(json_patch, list):
json_patch_collection.extend(json_patch)
logger.info("Patch payload %s", json.dumps(json_patch_collection))
try:
options = TwinOptions(if_match=(etag if etag else "*"))
self.twins_sdk.update_component(
id=twin_id,
component_path=component_path,
patch_document=json_patch_collection,
digital_twins_update_component_options=options,
)
return self.get_component(twin_id=twin_id, component_path=component_path)
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))
def send_telemetry(self, twin_id, telemetry=None, dt_id=None, component_path=None):
from uuid import uuid4
from datetime import datetime, timezone
local_time = datetime.now(timezone.utc).astimezone()
dt_timestamp = local_time.isoformat()
telemetry_request = {}
if telemetry:
telemetry = process_json_arg(content=telemetry, argument_name="telemetry")
else:
telemetry = {}
telemetry_request.update(telemetry)
logger.info("Telemetry payload: {}".format(json.dumps(telemetry_request)))
if not dt_id:
dt_id = str(uuid4())
try:
if component_path:
self.twins_sdk.send_component_telemetry(
id=twin_id,
message_id=dt_id,
dt_timestamp=dt_timestamp,
component_path=component_path,
telemetry=telemetry_request,
)
self.twins_sdk.send_telemetry(
id=twin_id,
message_id=dt_id,
dt_timestamp=dt_timestamp,
telemetry=telemetry_request,
)
except ErrorResponseException as e:
raise CLIError(unpack_msrest_error(e))