This repository has been archived by the owner on May 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.py
440 lines (362 loc) · 14.4 KB
/
client.py
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
"""Core interoperability client module
This module provides a Python interface to the SUAS interoperability API.
Users should use the AsyncClient to manage the interface, as it has performance
features. A simpler Client is also given as a base implementation.
See README.md for more details."""
from concurrent.futures import ThreadPoolExecutor
import functools
import json
import requests
import threading
from .exceptions import InteropError
from .interop_types import Mission
from .interop_types import MovingObstacle
from .interop_types import StationaryObstacle
from .interop_types import Target
class Client(object):
"""Client which provides authenticated access to interop API.
The constructor makes a login request, and all future requests will
automatically send the authentication cookie.
This client uses a single session to make blocking requests to the
interoperability server. This is the base core implementation. The
AsyncClient uses this base Client to add performance features.
"""
def __init__(self, url, username, password, timeout=1):
"""Create a new Client and login.
Args:
url: Base URL of interoperability server
(e.g., http://localhost:8000).
username: Interoperability username.
password: Interoperability password.
timeout: Individual session request timeout (seconds).
"""
self.url = url
self.timeout = timeout
self.session = requests.Session()
# All endpoints require authentication, so always login.
self.post('/api/login',
data={'username': username,
'password': password})
def get(self, uri, **kwargs):
"""GET request to server.
Args:
uri: Server URI to access (without base URL).
**kwargs: Arguments to requests.Session.get method.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
"""
r = self.session.get(self.url + uri, timeout=self.timeout, **kwargs)
if not r.ok:
raise InteropError(r)
return r
def post(self, uri, **kwargs):
"""POST request to server.
Args:
uri: Server URI to access (without base URL).
**kwargs: Arguments to requests.Session.post method.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
"""
r = self.session.post(self.url + uri, timeout=self.timeout, **kwargs)
if not r.ok:
raise InteropError(r)
return r
def put(self, uri, **kwargs):
"""PUT request to server.
Args:
uri: Server URI to access (without base URL).
**kwargs: Arguments to requests.Session.put method.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
"""
r = self.session.put(self.url + uri, timeout=self.timeout, **kwargs)
if not r.ok:
raise InteropError(r)
return r
def delete(self, uri):
"""DELETE request to server.
Args:
uri: Server URI to access (without base URL).
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
"""
r = self.session.delete(self.url + uri, timeout=self.timeout)
if not r.ok:
raise InteropError(r)
return r
def get_missions(self):
"""GET missions.
Returns:
List of Mission.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
ValueError or AttributeError: Malformed response from server.
"""
r = self.get('/api/missions')
return [Mission.deserialize(m) for m in r.json()]
def post_telemetry(self, telem):
"""POST new telemetry.
Args:
telem: Telemetry object containing telemetry state.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
"""
self.post('/api/telemetry', data=telem.serialize())
def get_obstacles(self):
"""GET obstacles.
Returns:
List of StationaryObstacles and list of MovingObstacles
i.e., ([StationaryObstacle], [MovingObstacles]).
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
ValueError or AttributeError: Malformed response from server.
"""
r = self.get('/api/obstacles')
d = r.json()
stationary = []
for o in d['stationary_obstacles']:
stationary.append(StationaryObstacle.deserialize(o))
moving = []
for o in d['moving_obstacles']:
moving.append(MovingObstacle.deserialize(o))
return stationary, moving
def get_targets(self):
"""GET targets.
Returns:
List of Target objects which are viewable by user.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
ValueError or AttributeError: Malformed response from server.
"""
r = self.get('/api/odlcs')
return [Target.deserialize(t) for t in r.json()]
def get_target(self, target_id):
"""GET target.
Args:
target_id: The ID of the target to get.
Returns:
Target object with corresponding ID.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
ValueError or AttributeError: Malformed response from server.
"""
r = self.get('/api/odlcs/%d' % target_id)
return Target.deserialize(r.json())
def post_target(self, target):
"""POST target.
Args:
target: The target to upload.
Returns:
The target after upload, which will include the target ID and user.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
ValueError or AttributeError: Malformed response from server.
"""
r = self.post('/api/odlcs', data=json.dumps(target.serialize()))
return Target.deserialize(r.json())
def put_target(self, target_id, target):
"""PUT target.
Args:
target_id: The ID of the target to update.
target: The target details to update.
Returns:
The target after being updated.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
ValueError or AttributeError: Malformed response from server.
"""
r = self.put('/api/odlcs/%d' % target_id,
data=json.dumps(target.serialize()))
return Target.deserialize(r.json())
def delete_target(self, target_id):
"""DELETE target.
Args:
target_id: The ID of the target to delete.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
"""
self.delete('/api/odlcs/%d' % target_id)
def get_target_image(self, target_id):
"""GET target image.
Args:
target_id: The ID of the target for which to get the image.
Returns:
The image data that was previously uploaded.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
"""
return self.get('/api/odlcs/%d/image' % target_id).content
def post_target_image(self, target_id, image_data):
"""POST target image. Image must be PNG or JPEG data.
Args:
target_id: The ID of the target for which to upload an image.
image_data: The image data (bytes loaded from file) to upload.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
"""
self.put_target_image(target_id, image_data)
def put_target_image(self, target_id, image_data):
"""PUT target image. Image must be PNG or JPEG data.
Args:
target_id: The ID of the target for which to upload an image.
image_data: The image data (bytes loaded from file) to upload.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
"""
self.put('/api/odlcs/%d/image' % target_id, data=image_data)
def delete_target_image(self, target_id):
"""DELETE target image.
Args:
target_id: The ID of the target image to delete.
Raises:
InteropError: Error from server.
requests.Timeout: Request timeout.
"""
self.delete('/api/odlcs/%d/image' % target_id)
class AsyncClient(object):
"""Client which uses the base to be more performant.
This client uses Futures with a ThreadPoolExecutor. This allows requests to
be executed asynchronously. Asynchronous execution with multiple Clients
enables requests to be processed in parallel and with pipeline execution at
the server, which can drastically improve achievable interoperability rate
as observed at the client.
Note that methods return Future objects. Users should handle the response
and errors appropriately. If serial request execution is desired, ensure the
Future response or error is received prior to making another request.
"""
def __init__(self, url, username, password, timeout=1, workers=8):
"""Create a new AsyncClient and login.
Args:
url: Base URL of interoperability server
(e.g., http://localhost:8000)
username: Interoperability username
password: Interoperability password
timeout: Individual session request timeout (seconds)
workers: Number of threads to use for sending/receiving requests.
"""
self.client = Client(url, username, password, timeout)
self.executor = ThreadPoolExecutor(max_workers=workers)
def get_missions(self):
"""GET missions.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.get_missions)
def post_telemetry(self, telem):
"""POST new telemetry.
Args:
telem: Telemetry object containing telemetry state.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.post_telemetry, telem)
def get_obstacles(self):
"""GET obstacles.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.get_obstacles)
def get_targets(self):
"""GET targets.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.get_targets)
def get_target(self, target_id):
"""GET target.
Args:
target_id: The ID of the target to get.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.get_target, target_id)
def post_target(self, target):
"""POST target.
Args:
target: The target to upload.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.post_target, target)
def put_target(self, target_id, target):
"""PUT target.
Args:
target_id: The ID of the target to update.
target: The target details to update.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.put_target, target_id, target)
def delete_target(self, target_id):
"""DELETE target.
Args:
target_id: The ID of the target to delete.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.delete_target, target_id)
def get_target_image(self, target_id):
"""GET target image.
Args:
target_id: The ID of the target for which to get the image.
Returns:
The image data that was previously uploaded.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.get_target_image, target_id)
def post_target_image(self, target_id, image_data):
"""POST target image. Image must be PNG or JPEG data.
Args:
target_id: The ID of the target for which to upload an image.
image_data: The image data (bytes loaded from file) to upload.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.post_target_image, target_id,
image_data)
def put_target_image(self, target_id, image_data):
"""PUT target image. Image must be PNG or JPEG data.
Args:
target_id: The ID of the target for which to upload an image.
image_data: The image data (bytes loaded from file) to upload.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.put_target_image, target_id,
image_data)
def delete_target_image(self, target_id):
"""DELETE target image.
Args:
target_id: The ID of the target image to delete.
Returns:
Future object which contains the return value or error from the
underlying Client.
"""
return self.executor.submit(self.client.delete_target_image, target_id)