-
Notifications
You must be signed in to change notification settings - Fork 562
/
Copy pathclient.py
520 lines (420 loc) · 21.9 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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# Copyright (c) 2023 Boston Dynamics, Inc. All rights reserved.
#
# Downloading, reproducing, distributing or otherwise using the SDK Software
# is subject to the terms and conditions of the Boston Dynamics Software
# Development Kit License (20191101-BDSDK-SL).
"""For clients to the mission service."""
import collections
from builtins import str as text
from google.protobuf import timestamp_pb2
from bosdyn.api.mission import mission_pb2, mission_service_pb2_grpc
from bosdyn.client import data_chunk
from bosdyn.client.common import (BaseClient, common_header_errors, error_factory,
handle_common_header_errors, handle_lease_use_result_errors,
handle_unset_status_error)
from bosdyn.client.exceptions import ResponseError, TimeSyncRequired, UnimplementedError
from bosdyn.client.lease import add_lease_wallet_processors
class MissionResponseError(ResponseError):
"""General class of errors for mission service."""
class InvalidQuestionId(MissionResponseError):
"""The indicated question is unknown."""
class InvalidAnswerCode(MissionResponseError):
"""The indicated answer code is invalid for the specified question."""
class QuestionAlreadyAnswered(MissionResponseError):
"""The indicated question was already answered."""
class CustomParamsError(MissionResponseError):
"""The indicated answer does not match the spec for the indicated answer"""
class IncompatibleAnswer(MissionResponseError):
"""The indicated answer is not in a format expected by the indicated question."""
class CompilationError(MissionResponseError):
"""Mission could not be compiled."""
class ValidationError(MissionResponseError):
"""Mission could not be validated."""
def __init__(self, response, error_message=None):
super(ValidationError, self).__init__(self, response)
self.failed_nodes = response.failed_nodes
def __str__(self):
return 'Mission validation failed with: {}'.format('; '.join(
[n.error for n in self.failed_nodes]))
class NoMissionError(MissionResponseError):
"""There is no mission to be played/restarted."""
class NoMissionPlayingError(MissionResponseError):
"""There is no mission to be paused."""
class MissionClient(BaseClient):
"""Client for the Mission service."""
default_service_name = 'robot-mission'
service_type = 'bosdyn.api.mission.MissionService'
def __init__(self):
super(MissionClient, self).__init__(mission_service_pb2_grpc.MissionServiceStub)
self._timesync_endpoint = None
def update_from(self, other):
super(MissionClient, self).update_from(other)
if self.lease_wallet:
add_lease_wallet_processors(self, self.lease_wallet)
# Grab a timesync endpoint if it is available.
try:
self._timesync_endpoint = other.time_sync.endpoint
except AttributeError:
pass # other doesn't have a time_sync accessor
@property
def timesync_endpoint(self):
"""Accessor for timesync endpoint that was grabbed via 'update_from()'."""
if not self._timesync_endpoint:
raise TimeSyncRequired
return self._timesync_endpoint
def get_state(self, upper_tick_bound=None, lower_tick_bound=None, past_ticks=None, **kwargs):
"""Obtain current mission state.
Raises:
RpcError: Problem communicating with the robot.
"""
req = self._get_state_request(upper_tick_bound, lower_tick_bound, past_ticks)
return self.call(self._stub.GetState, req, _get_state_value, common_header_errors,
copy_request=False, **kwargs)
def get_state_async(self, upper_tick_bound=None, lower_tick_bound=None, past_ticks=None,
**kwargs):
"""Async version of get_state()"""
req = self._get_state_request(upper_tick_bound, lower_tick_bound, past_ticks)
return self.call_async(self._stub.GetState, req, _get_state_value, common_header_errors,
copy_request=False, **kwargs)
def answer_question(self, question_id, code=None, custom_params=None, **kwargs):
"""Specify an answer to the question asked by the mission.
Args:
question_id (int): ID of the question to answer.
code (int): Answer code.
custom_params (DictParam): Answer to a custom params prompt.
Raises:
RpcError: Problem communicating with the robot.
InvalidQuestionId: question_id was not a valid id.
InvalidAnswerCode: code was not valid for the question.
QuestionAlreadyAnswered: The question for question_id was already answered.
CustomParamsError: The answer did not match the spec for the question.
IncompatibleAnswer: The answer did not match a type expected for the question.
"""
req = self._answer_question_request(question_id, code, custom_params)
return self.call(self._stub.AnswerQuestion, req, None, _answer_question_error_from_response,
copy_request=False, **kwargs)
def answer_question_async(self, question_id, code=None, custom_params=None, **kwargs):
"""Async version of answer_question()"""
req = self._answer_question_request(question_id, code, custom_params)
return self.call_async(self._stub.AnswerQuestion, req, None,
_answer_question_error_from_response, copy_request=False, **kwargs)
def load_mission(self, root, leases=[], **kwargs):
"""Load a mission onto the robot.
Args:
root: Root node in a mission.
leases: All leases necessary to initialize a mission.
Raises:
RpcError: Problem communicating with the robot.
bosdyn.mission.client.CompilationError: The mission failed to compile.
bosdyn.mission.client.ValidationError: The mission failed to validate.
"""
req = self._load_mission_request(root, leases)
return self.call(self._stub.LoadMission, req, None, _load_mission_error_from_response,
copy_request=False, **kwargs)
def load_mission_async(self, root, leases=[], **kwargs):
"""Async version of load_mission"""
req = self._load_mission_request(root, leases)
return self.call_async(self._stub.LoadMission, req, None, _load_mission_error_from_response,
copy_request=False, **kwargs)
def load_mission_as_chunks(self, root, leases=[], data_chunk_byte_size=1000 * 1000, **kwargs):
"""Load a mission onto the robot.
Args:
root: Root node in a mission.
leases: All leases necessary to initialize a mission.
data_chunk_byte_size: max size of each streamed message
Raises:
RpcError: Problem communicating with the robot.
bosdyn.mission.client.CompilationError: The mission failed to compile.
bosdyn.mission.client.ValidationError: The mission failed to validate.
"""
req = self._load_mission_request(root, leases)
self._apply_request_processors(req, copy_request=False)
return self.call(self._stub.LoadMissionAsChunks,
data_chunk.chunk_message(req, data_chunk_byte_size), None,
_load_mission_error_from_response, **kwargs)
def load_mission_as_chunks2(self, root, leases=[], data_chunk_byte_size=1000 * 1000, **kwargs):
"""Load a mission onto the robot.
Args:
root: Root node in a mission.
leases: All leases necessary to initialize a mission.
data_chunk_byte_size: max size of each streamed message
Raises:
RpcError: Problem communicating with the robot.
bosdyn.mission.client.CompilationError: The mission failed to compile.
bosdyn.mission.client.ValidationError: The mission failed to validate.
"""
req = self._load_mission_request(root, leases)
self._apply_request_processors(req, copy_request=False)
return self.call(self._stub.LoadMissionAsChunks2,
data_chunk.chunk_message(req, data_chunk_byte_size),
error_from_response=_load_mission_error_from_response,
assemble_type=mission_pb2.LoadMissionResponse, copy_request=False,
**kwargs)
def play_mission(
self,
pause_time_secs,
leases=[],
settings=None,
**kwargs):
"""Play the loaded mission.
Args:
pause_time_secs: Absolute time when the mission should pause execution. Subsequent RPCs
will override this value, so you can use this to say "if you don't hear from me again,
stop running the mission at this time."
leases: Leases the mission service will need to use. Unlike other clients, these MUST
be specified.
Raises:
RpcError: Problem communicating with the robot.
NoMissionError: No mission Loaded.
"""
req = self._play_mission_request(
pause_time_secs,
leases,
settings)
return self.call(self._stub.PlayMission, req, None, _play_mission_error_from_response,
copy_request=False, **kwargs)
def play_mission_async(
self,
pause_time_secs,
leases=[],
settings=None,
**kwargs):
"""Async version of play_mission."""
req = self._play_mission_request(
pause_time_secs,
leases,
settings)
return self.call_async(self._stub.PlayMission, req, None, _play_mission_error_from_response,
copy_request=False, **kwargs)
def restart_mission(self, pause_time_secs, leases=[], settings=None, **kwargs):
"""Restart the loaded mission.
Args:
pause_time_secs: Absolute time when the mission should pause execution. Subsequent RPCs
to RestartMission will override this value, so you can use this to say "if you don't hear
from me again, stop running the mission at this time."
leases: Leases the mission service will need to use. Unlike other clients, these MUST
be specified.
Raises:
RpcError: Problem communicating with the robot.
NoMissionError: No Mission Loaded.
bosdyn.mission.client.ValidationError: The mission failed to validate.
"""
req = self._restart_mission_request(pause_time_secs, leases, settings)
return self.call(self._stub.RestartMission, req, None, _restart_mission_error_from_response,
copy_request=False, **kwargs)
def restart_mission_async(self, pause_time_secs, leases=[], settings=None, **kwargs):
"""Async version of restart_mission."""
req = self._restart_mission_request(pause_time_secs, leases, settings)
return self.call_async(self._stub.RestartMission, req, None,
_restart_mission_error_from_response, copy_request=False, **kwargs)
def pause_mission(self, **kwargs):
"""Pause the running mission.
Raises:
RpcError: Problem communicating with the robot.
NoMissionPlayingError: No mission playing.
"""
req = self._pause_mission_request()
return self.call(self._stub.PauseMission, req, None, _pause_mission_error_from_response,
copy_request=False, **kwargs)
def pause_mission_async(self, **kwargs):
"""Async version of pause_mission()."""
req = self._pause_mission_request()
return self.call_async(self._stub.PauseMission, req, None,
_pause_mission_error_from_response, copy_request=False, **kwargs)
def stop_mission(self, **kwargs):
"""Stop the running mission.
Raises:
RpcError: Problem communicating with the robot.
NoMissionPlayingError: No mission playing.
"""
req = self._stop_mission_request()
return self.call(self._stub.StopMission, req, None, _stop_mission_error_from_response,
copy_request=False, **kwargs)
def stop_mission_async(self, **kwargs):
"""Async version of stop_mission()."""
req = self._stop_mission_request()
return self.call_async(self._stub.StopMission, req, None, _stop_mission_error_from_response,
copy_request=False, **kwargs)
def get_info(self, **kwargs):
"""Get static information about the loaded mission.
Raises:
RpcError: Problem communicating with the robot.
"""
req = self._get_info_request()
try:
return self._get_info_as_chunks_call(req)
except UnimplementedError as err:
# This indicates that the software release running on robot does not yet have
# the implementation for the streaming response of GetInfo.
return self.call(self._stub.GetInfo, req, _get_info_value, common_header_errors,
copy_request=False, **kwargs)
def _get_info_as_chunks_call(self, req, **kwargs):
"""Issues the GetInfoAsChunks RPC to the mission service."""
return self.call(self._stub.GetInfoAsChunks, req, _get_info_value,
error_from_response=common_header_errors,
assemble_type=mission_pb2.GetInfoResponse, copy_request=False, **kwargs)
def get_info_async(self, **kwargs):
"""Async version of get_info."""
req = self._get_info_request()
return self.call_async(self._stub.GetInfo, req, _get_info_value, common_header_errors,
copy_request=False, **kwargs)
def get_mission(self, **kwargs):
"""Get the loaded mission.
Raises:
RpcError: Problem communicating with the robot.
"""
req = self._get_mission_request()
try:
return self._get_mission_as_chunks_call(req)
except UnimplementedError as err:
# This indicates that the software release running on robot does not yet have
# the implementation for the streaming response of GetMission.
return self.call(self._stub.GetMission, req, None, common_header_errors,
copy_request=False, **kwargs)
def get_mission_async(self, **kwargs):
"""Async version of get_mission()."""
req = self._get_mission_request()
return self.call_async(self._stub.GetMission, req, None, common_header_errors,
copy_request=False, **kwargs)
def _get_mission_as_chunks_call(self, req, **kwargs):
"""Issues the GetMissionAsChunks RPC to the mission service."""
return self.call(self._stub.GetMissionAsChunks, req, value_from_response=None,
error_from_response=common_header_errors,
assemble_type=mission_pb2.GetMissionResponse, copy_request=False, **kwargs)
@staticmethod
def _get_state_request(upper_tick_bound, lower_tick_bound, past_ticks):
if lower_tick_bound is not None and past_ticks is not None:
raise ValueError('Cannot specify both lower_tick_bound and past_ticks')
request = mission_pb2.GetStateRequest(history_lower_tick_bound=lower_tick_bound,
history_past_ticks=past_ticks)
if upper_tick_bound is not None:
request.history_upper_tick_bound.value = upper_tick_bound
return request
@staticmethod
def _answer_question_request(question_id, code, custom_params):
return mission_pb2.AnswerQuestionRequest(question_id=question_id, code=code,
custom_params=custom_params)
@staticmethod
def _load_mission_request(root, leases):
request = mission_pb2.LoadMissionRequest(root=root)
for lease in leases:
request.leases.add().CopyFrom(lease.lease_proto)
return request
def _play_mission_request(
self,
pause_time_secs,
leases,
settings):
request = mission_pb2.PlayMissionRequest(
pause_time=self.timesync_endpoint.robot_timestamp_from_local_secs(pause_time_secs),
settings=settings)
for lease in leases:
request.leases.add().CopyFrom(lease.lease_proto)
return request
def _restart_mission_request(self, pause_time_secs, leases, settings):
request = mission_pb2.RestartMissionRequest(
pause_time=self.timesync_endpoint.robot_timestamp_from_local_secs(pause_time_secs),
settings=settings)
for lease in leases:
request.leases.add().CopyFrom(lease.lease_proto)
return request
@staticmethod
def _pause_mission_request():
return mission_pb2.PauseMissionRequest()
@staticmethod
def _stop_mission_request():
return mission_pb2.StopMissionRequest()
@staticmethod
def _get_info_request():
return mission_pb2.GetInfoRequest()
@staticmethod
def _get_mission_request():
return mission_pb2.GetMissionRequest()
def _get_state_value(response):
return response.state
def _get_info_value(response):
if response.HasField(text('mission_info')):
return response.mission_info
return None
_ANSWER_QUESTION_STATUS_TO_ERROR = collections.defaultdict(lambda: (MissionResponseError, None))
_ANSWER_QUESTION_STATUS_TO_ERROR.update({
mission_pb2.AnswerQuestionResponse.STATUS_OK: (None, None),
mission_pb2.AnswerQuestionResponse.STATUS_INVALID_QUESTION_ID:
(InvalidQuestionId, InvalidQuestionId.__doc__),
mission_pb2.AnswerQuestionResponse.STATUS_INVALID_CODE:
(InvalidAnswerCode, InvalidAnswerCode.__doc__),
mission_pb2.AnswerQuestionResponse.STATUS_ALREADY_ANSWERED:
(QuestionAlreadyAnswered, QuestionAlreadyAnswered.__doc__),
mission_pb2.AnswerQuestionResponse.STATUS_CUSTOM_PARAMS_ERROR:
(CustomParamsError, CustomParamsError.__doc__),
mission_pb2.AnswerQuestionResponse.STATUS_INCOMPATIBLE_ANSWER:
(IncompatibleAnswer, IncompatibleAnswer.__doc__),
})
@handle_common_header_errors
@handle_unset_status_error(unset='STATUS_UNKNOWN')
def _answer_question_error_from_response(response):
return error_factory(response, response.status,
status_to_string=mission_pb2.AnswerQuestionResponse.Status.Name,
status_to_error=_ANSWER_QUESTION_STATUS_TO_ERROR)
_LOAD_MISSION_STATUS_TO_ERROR = collections.defaultdict(lambda: (MissionResponseError, None))
_LOAD_MISSION_STATUS_TO_ERROR.update({
mission_pb2.LoadMissionResponse.STATUS_OK: (None, None),
mission_pb2.LoadMissionResponse.STATUS_VALIDATE_ERROR: (ValidationError, None),
mission_pb2.LoadMissionResponse.STATUS_COMPILE_ERROR: (CompilationError, None),
})
@handle_common_header_errors
@handle_unset_status_error(unset='STATUS_UNKNOWN')
@handle_lease_use_result_errors
def _load_mission_error_from_response(response):
return error_factory(response, response.status,
status_to_string=mission_pb2.LoadMissionResponse.Status.Name,
status_to_error=_LOAD_MISSION_STATUS_TO_ERROR)
_PLAY_MISSION_STATUS_TO_ERROR = collections.defaultdict(lambda: (MissionResponseError, None))
_PLAY_MISSION_STATUS_TO_ERROR.update({
mission_pb2.PlayMissionResponse.STATUS_OK: (None, None),
mission_pb2.PlayMissionResponse.STATUS_NO_MISSION: (NoMissionError, None),
})
@handle_common_header_errors
@handle_unset_status_error(unset='STATUS_UNKNOWN')
@handle_lease_use_result_errors
def _play_mission_error_from_response(response):
return error_factory(response, response.status,
status_to_string=mission_pb2.PlayMissionResponse.Status.Name,
status_to_error=_PLAY_MISSION_STATUS_TO_ERROR)
_PAUSE_MISSION_STATUS_TO_ERROR = collections.defaultdict(lambda: (MissionResponseError, None))
_PAUSE_MISSION_STATUS_TO_ERROR.update({
mission_pb2.PauseMissionResponse.STATUS_OK: (None, None),
mission_pb2.PauseMissionResponse.STATUS_NO_MISSION_PLAYING: (NoMissionPlayingError, None),
})
@handle_common_header_errors
@handle_unset_status_error(unset='STATUS_UNKNOWN')
@handle_lease_use_result_errors
def _pause_mission_error_from_response(response):
return error_factory(response, response.status,
status_to_string=mission_pb2.PauseMissionResponse.Status.Name,
status_to_error=_PAUSE_MISSION_STATUS_TO_ERROR)
_STOP_MISSION_STATUS_TO_ERROR = collections.defaultdict(lambda: (MissionResponseError, None))
_STOP_MISSION_STATUS_TO_ERROR.update({
mission_pb2.StopMissionResponse.STATUS_OK: (None, None),
mission_pb2.StopMissionResponse.STATUS_NO_MISSION_PLAYING: (NoMissionPlayingError, None),
})
@handle_common_header_errors
@handle_unset_status_error(unset='STATUS_UNKNOWN')
@handle_lease_use_result_errors
def _stop_mission_error_from_response(response):
return error_factory(response, response.status,
status_to_string=mission_pb2.StopMissionResponse.Status.Name,
status_to_error=_STOP_MISSION_STATUS_TO_ERROR)
_RESTART_MISSION_STATUS_TO_ERROR = collections.defaultdict(lambda: (MissionResponseError, None))
_RESTART_MISSION_STATUS_TO_ERROR.update({
mission_pb2.RestartMissionResponse.STATUS_OK: (None, None),
mission_pb2.RestartMissionResponse.STATUS_NO_MISSION: (NoMissionError, None),
mission_pb2.RestartMissionResponse.STATUS_VALIDATE_ERROR: (ValidationError, None),
})
@handle_common_header_errors
@handle_unset_status_error(unset='STATUS_UNKNOWN')
@handle_lease_use_result_errors
def _restart_mission_error_from_response(response):
return error_factory(response, response.status,
status_to_string=mission_pb2.RestartMissionResponse.Status.Name,
status_to_error=_RESTART_MISSION_STATUS_TO_ERROR)