forked from boston-dynamics/spot-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_nav.py
More file actions
1266 lines (1068 loc) · 63.2 KB
/
Copy pathgraph_nav.py
File metadata and controls
1266 lines (1068 loc) · 63.2 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
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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 graphnav service."""
import collections
import math
import os
import time
from deprecated.sphinx import deprecated
from bosdyn.api import data_chunk_pb2, lease_pb2
from bosdyn.api.graph_nav import (graph_nav_pb2, graph_nav_service_pb2, graph_nav_service_pb2_grpc,
map_pb2, nav_pb2)
from bosdyn.client.common import (BaseClient, common_header_errors, common_lease_errors,
error_factory, error_pair, handle_common_header_errors,
handle_lease_use_result_errors, handle_unset_status_error)
from bosdyn.client.exceptions import Error, InvalidRequestError, ResponseError
from bosdyn.client.lease import add_lease_wallet_processors
class GraphNavClient(BaseClient):
"""Client to the GraphNav service."""
default_service_name = 'graph-nav-service'
service_type = 'bosdyn.api.graph_nav.GraphNavService'
def __init__(self):
super(GraphNavClient, self).__init__(graph_nav_service_pb2_grpc.GraphNavServiceStub)
self._timesync_endpoint = None
self._data_chunk_size = 1024 * 1024 # bytes = 1 MB
def update_from(self, other):
super(GraphNavClient, 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
def set_localization_full_response(
self, initial_guess_localization, ko_tform_body=None, max_distance=None, max_yaw=None,
fiducial_init=graph_nav_pb2.SetLocalizationRequest.FIDUCIAL_INIT_NEAREST,
use_fiducial_id=None, refine_fiducial_result_with_icp=False, do_ambiguity_check=False,
refine_with_visual_features=False, verify_visual_features_quality=False, **kwargs):
"""Version of set_localization which returns the full response,
rather than only the Localization message.
"""
req = self._build_set_localization_request(
initial_guess_localization, ko_tform_body, max_distance, max_yaw, fiducial_init,
use_fiducial_id, refine_fiducial_result_with_icp, do_ambiguity_check,
refine_with_visual_features, verify_visual_features_quality)
return self.call(self._stub.SetLocalization, req, _get_response, _set_localization_error,
copy_request=False, **kwargs)
def set_localization_async_full_response(
self, initial_guess_localization, ko_tform_body=None, max_distance=None, max_yaw=None,
fiducial_init=graph_nav_pb2.SetLocalizationRequest.FIDUCIAL_INIT_NEAREST,
use_fiducial_id=None, refine_fiducial_result_with_icp=False, do_ambiguity_check=False,
refine_with_visual_features=False, verify_visual_features_quality=False, **kwargs):
"""Async version of set_localization_full_response()"""
req = self._build_set_localization_request(
initial_guess_localization, ko_tform_body, max_distance, max_yaw, fiducial_init,
use_fiducial_id, refine_fiducial_result_with_icp, do_ambiguity_check,
refine_with_visual_features, verify_visual_features_quality)
return self.call_async(self._stub.SetLocalization, req, _get_response,
_set_localization_error, copy_request=False, **kwargs)
def set_localization(
self, initial_guess_localization, ko_tform_body=None, max_distance=None, max_yaw=None,
fiducial_init=graph_nav_pb2.SetLocalizationRequest.FIDUCIAL_INIT_NEAREST,
use_fiducial_id=None, refine_fiducial_result_with_icp=False, do_ambiguity_check=False,
refine_with_visual_features=False, verify_visual_features_quality=False, **kwargs):
"""Trigger a manual localization. Typically done to provide the initial localization.
Args:
initial_guess_localization (nav_pb2.Localization): Operator-supplied guess at localization.
ko_tform_body: Robot SE3Pose protobuf when the initial_guess was made.
max_distance: [optional] Margin of distance (meters) away from the initial guess.
max_yaw: [optional] Margin of angle (radians) away from the initial guess.
fiducial_init: Tells the initializer whether to use fiducials, and how to use them.
use_fiducial_id: If using FIDUCIAL_INIT_SPECIFIC, this is the specific fiducial ID to use for initialization.
refine_fiducial_result_with_icp: Boolean determining if ICP will run after a fiducial is used for an initial guess.
do_ambiguity_check: Boolean where if true, consider how nearby localizations appear.
refine_with_visual_features: Boolean determining if visual features should be used to refine the estimate. When set,
this value overrides refine_fiducial_result_with_icp.
verify_visual_features_quality: When refine_with_visual_features is set, determines if an error is asserted when the
refinement is unsuccessful.
Returns:
The resulting localization after being triggered with a guess.
Raises:
RpcError: Problem communicating with the robot
RobotFaultedError: Robot is experiencing a fault condition that prevents localization.
UnknownMapInformationError: Specified waypoint is unknown.
bosdyn.client.exceptions.InvalidRequestError: The data provided is incomplete or invalid
GraphNavServiceResponseError: Localization was aborted or failed.
"""
req = self._build_set_localization_request(
initial_guess_localization, ko_tform_body, max_distance, max_yaw, fiducial_init,
use_fiducial_id, refine_fiducial_result_with_icp, do_ambiguity_check,
refine_with_visual_features, verify_visual_features_quality)
return self.call(self._stub.SetLocalization, req, _localization_from_response,
_set_localization_error, copy_request=False, **kwargs)
def set_localization_async(
self, initial_guess_localization, ko_tform_body=None, max_distance=None, max_yaw=None,
fiducial_init=graph_nav_pb2.SetLocalizationRequest.FIDUCIAL_INIT_NEAREST,
use_fiducial_id=None, refine_fiducial_result_with_icp=False, do_ambiguity_check=False,
refine_with_visual_features=False, verify_visual_features_quality=False, **kwargs):
"""Async version of set_localization()"""
req = self._build_set_localization_request(
initial_guess_localization, ko_tform_body, max_distance, max_yaw, fiducial_init,
use_fiducial_id, refine_fiducial_result_with_icp, do_ambiguity_check,
refine_with_visual_features, verify_visual_features_quality)
return self.call_async(self._stub.SetLocalization, req, _localization_from_response,
_set_localization_error, copy_request=False, **kwargs)
def get_localization_state(
self,
request_live_point_cloud=False,
request_live_images=False,
request_live_terrain_maps=False,
request_live_world_objects=False,
request_live_robot_state=False,
waypoint_id=None,
**kwargs):
"""Obtain current localization state of the robot.
Returns:
The current localization protobuf for the robot.
Raises:
RpcError: Problem communicating with the robot.
"""
req = self._build_get_localization_state_request(
request_live_point_cloud=request_live_point_cloud,
request_live_images=request_live_images,
request_live_terrain_maps=request_live_terrain_maps,
request_live_world_objects=request_live_world_objects,
request_live_robot_state=request_live_robot_state, waypoint_id=waypoint_id)
return self.call(self._stub.GetLocalizationState, req, None, common_header_errors,
copy_request=False, **kwargs)
def get_localization_state_async(self, request_live_point_cloud=False,
request_live_images=False, request_live_terrain_maps=False,
request_live_world_objects=False,
request_live_robot_state=False, waypoint_id=None, **kwargs):
"""Async version of get_localization_state()."""
req = self._build_get_localization_state_request(
request_live_point_cloud=request_live_point_cloud,
request_live_images=request_live_images,
request_live_terrain_maps=request_live_terrain_maps,
request_live_world_objects=request_live_world_objects,
request_live_robot_state=request_live_robot_state, waypoint_id=waypoint_id)
return self.call_async(self._stub.GetLocalizationState, req, None, common_header_errors,
copy_request=False, **kwargs)
def navigate_route(self, route, cmd_duration, route_follow_params=None, travel_params=None,
leases=None, timesync_endpoint=None, command_id=None,
destination_waypoint_tform_body_goal=None, **kwargs):
"""Navigate the given route.
Args:
route: Route protobuf of the route to follow.
route_follow_params: What should the robot do if it is not at the expected point in the
route, or the route is blocked.
travel_params: API TravelParams for the route.
cmd_duration: Number of seconds the command can run for.
leases: Leases to show ownership of necessary resources. Will use the client's leases by default.
timesync_endpoint: Use this endpoint for timesync fields. Will use the client's endpoint by default.
command_id: If not None, this continues an existing navigate_route command with the given ID. If None,
a new command_id will be used.
destination_waypoint_tform_body_goal: SE2Pose protobuf of an offset relative to the destination waypoint.
kwargs: Passed to underlying RPC. Example: timeout=5 to cancel the RPC after 5 seconds.
Returns:
Command ID to use in feedback lookup.
Raises:
RpcError: Problem communicating with the robot.
LeaseUseError: Error using provided leases.
graph_nav.NoTimeSyncError: Missing clock identifier.
graph_nav.CommandExpiredError: Command already expired.
graph_nav.TooDistantError: Time too far in the future.
graph_nav.RobotImpairedError: Robot cannot travel a route.
graph_nav.IsRecordingError: Robot cannot navigate while recording.
graph_nav.UnknownRouteElementsError: Unknown edges or waypoints
graph_nav.InvalidEdgeError: Mismatch between edges and waypoints.
graph_nav.NoPathError: No path to the specified route.
graph_nav.RobotNotLocalizedToRouteError: The robot is localized somewhere else.
graph_nav.ConstraintFaultError: The route involves invalid constraints.
graph_nav.RouteNavigationError: A subclass detailing trouble navigating the route.
"""
used_endpoint = timesync_endpoint or self._timesync_endpoint
if not used_endpoint:
raise GraphNavServiceResponseError(response=None, error_message='No timesync endpoint!')
request = self._build_navigate_route_request(route, route_follow_params, travel_params,
cmd_duration, leases, used_endpoint,
command_id,
destination_waypoint_tform_body_goal)
return self.call(self._stub.NavigateRoute, request,
_command_id_from_navigate_route_response, _navigate_route_error,
copy_request=False, **kwargs)
def navigate_route_async(self, route, cmd_duration, route_follow_params=None,
travel_params=None, leases=None, timesync_endpoint=None,
command_id=None, destination_waypoint_tform_body_goal=None, **kwargs):
"""Async version of navigate_route()"""
used_endpoint = timesync_endpoint or self._timesync_endpoint
if not used_endpoint:
raise GraphNavServiceResponseError(response=None, error_message='No timesync endpoint!')
request = self._build_navigate_route_request(route, route_follow_params, travel_params,
cmd_duration, leases, used_endpoint,
command_id,
destination_waypoint_tform_body_goal)
return self.call_async(self._stub.NavigateRoute, request,
_command_id_from_navigate_route_response, _navigate_route_error,
copy_request=False, **kwargs)
def navigate_route_full(self, route, route_follow_params, cmd_duration, travel_params=None,
leases=None, timesync_endpoint=None, command_id=None,
destination_waypoint_tform_body_goal=None, **kwargs):
"""Identical to navigate_route(), except will return the full NavigateRouteResponse."""
used_endpoint = timesync_endpoint or self._timesync_endpoint
if not used_endpoint:
raise GraphNavServiceResponseError(response=None, error_message='No timesync endpoint!')
request = self._build_navigate_route_request(route, route_follow_params, travel_params,
cmd_duration, leases, used_endpoint,
command_id,
destination_waypoint_tform_body_goal)
return self.call(self._stub.NavigateRoute, request,
error_from_response=_navigate_route_error, copy_request=False, **kwargs)
def navigate_route_full_async(self, route, cmd_duration, route_follow_params=None,
travel_params=None, leases=None, timesync_endpoint=None,
command_id=None, destination_waypoint_tform_body_goal=None,
**kwargs):
"""Async version of navigate_route_full()."""
used_endpoint = timesync_endpoint or self._timesync_endpoint
if not used_endpoint:
raise GraphNavServiceResponseError(response=None, error_message='No timesync endpoint!')
request = self._build_navigate_route_request(route, route_follow_params, travel_params,
cmd_duration, leases, used_endpoint,
command_id,
destination_waypoint_tform_body_goal)
return self.call_async(self._stub.NavigateRoute, request,
error_from_response=_navigate_route_error, copy_request=False,
**kwargs)
def navigate_to(self, destination_waypoint_id, cmd_duration, route_params=None,
travel_params=None, leases=None, timesync_endpoint=None, command_id=None,
destination_waypoint_tform_body_goal=None, route_blocked_behavior=None,
**kwargs):
"""Navigate to a specific waypoint along a route chosen by the GraphNav service.
Args:
destination_waypoint_id: Waypoint id string for where to go to.
cmd_duration: Number of seconds the command can run for.
route_params: API RouteGenParams for the route.
travel_params: API TravelParams for the route.
leases: Leases to show ownership of necessary resources. Will use the client's leases by default.
timesync_endpoint: Use this endpoint for timesync fields. Will use the client's endpoint by default.
command_id: If not None, this continues an existing navigate_to command with the given ID. If None,
a new command_id will be used.
destination_waypoint_tform_body_goal: SE2Pose protobuf of an offset relative to the destination waypoint.
route_blocked_behavior: Defines robot behavior when route is block. If None robot will reroute.
Returns:
int: Command ID to use in feedback lookup.
Raises:
RpcError: Problem communicating with the robot.
LeaseUseError: Error using provided leases.
graph_nav.NoTimeSyncError: Missing clock identifier.
graph_nav.CommandExpiredError: Command already expired.
graph_nav.TooDistantError: Time too far in the future.
graph_nav.RobotImpairedError: Robot cannot travel a route.
graph_nav.IsRecordingError: Robot cannot navigate while recording.
graph_nav.UnknownWaypointError: Destination waypoint is unknown.
graph_nav.NoPathError: No route to destination.
graph_nav.RobotNotLocalizedToRouteError: The robot not correctly localized.
graph_nav.RouteNavigationError: A subclass detailing trouble navigating the route.
"""
used_endpoint = timesync_endpoint or self._timesync_endpoint
if not used_endpoint:
raise GraphNavServiceResponseError(response=None, error_message='No timesync endpoint!')
request = self._build_navigate_to_request(destination_waypoint_id, travel_params,
route_params, cmd_duration, leases, used_endpoint,
command_id, destination_waypoint_tform_body_goal,
route_blocked_behavior)
return self.call(self._stub.NavigateTo, request,
value_from_response=_command_id_from_navigate_route_response,
error_from_response=_navigate_to_error, copy_request=False, **kwargs)
def navigate_to_async(self, destination_waypoint_id, cmd_duration, route_params=None,
travel_params=None, leases=None, timesync_endpoint=None, command_id=None,
destination_waypoint_tform_body_goal=None, route_blocked_behavior=None,
**kwargs):
"""Async version of navigate_to()."""
used_endpoint = timesync_endpoint or self._timesync_endpoint
if not used_endpoint:
raise GraphNavServiceResponseError(response=None, error_message='No timesync endpoint!')
request = self._build_navigate_to_request(destination_waypoint_id, travel_params,
route_params, cmd_duration, leases, used_endpoint,
command_id, destination_waypoint_tform_body_goal)
return self.call_async(self._stub.NavigateTo, request,
value_from_response=_command_id_from_navigate_route_response,
error_from_response=_navigate_to_error, copy_request=False, **kwargs)
def navigate_to_full(self, destination_waypoint_id, cmd_duration, route_params=None,
travel_params=None, leases=None, timesync_endpoint=None, command_id=None,
destination_waypoint_tform_body_goal=None, route_blocked_behavior=None,
**kwargs):
"""Identical to navigate_to(), except will return the full NavigateToResponse."""
used_endpoint = timesync_endpoint or self._timesync_endpoint
if not used_endpoint:
raise GraphNavServiceResponseError(response=None, error_message='No timesync endpoint!')
request = self._build_navigate_to_request(destination_waypoint_id, travel_params,
route_params, cmd_duration, leases, used_endpoint,
command_id, destination_waypoint_tform_body_goal,
route_blocked_behavior)
return self.call(self._stub.NavigateTo, request, error_from_response=_navigate_to_error,
copy_request=False, **kwargs)
def navigate_to_full_async(self, destination_waypoint_id, cmd_duration, route_params=None,
travel_params=None, leases=None, timesync_endpoint=None,
command_id=None, destination_waypoint_tform_body_goal=None,
route_blocked_behavior=None, **kwargs):
"""Async version of navigate_to_full()."""
used_endpoint = timesync_endpoint or self._timesync_endpoint
if not used_endpoint:
raise GraphNavServiceResponseError(response=None, error_message='No timesync endpoint!')
request = self._build_navigate_to_request(destination_waypoint_id, travel_params,
route_params, cmd_duration, leases, used_endpoint,
command_id, destination_waypoint_tform_body_goal,
route_blocked_behavior)
return self.call_async(self._stub.NavigateTo, request,
error_from_response=_navigate_to_error, copy_request=False, **kwargs)
def navigate_to_anchor(self, seed_tform_goal, cmd_duration, route_params=None,
travel_params=None, leases=None, timesync_endpoint=None,
goal_waypoint_rt_seed_ewrt_seed_tolerance=None, command_id=None,
**kwargs):
"""Navigate to a pose in seed frame along a route chosen by the GraphNav service.
Args:
seed_tform_goal: SE3Pose protobuf of the goal pose in seed frame.
cmd_duration: Number of seconds the command can run for.
route_params: API RouteGenParams for the route.
travel_params: API TravelParams for the route.
leases: Leases to show ownership of necessary resources. Will use the client's leases by default.
timesync_endpoint: Use this endpoint for timesync fields. Will use the client's endpoint by default.
goal_waypoint_rt_seed_ewrt_seed_tolerance: Vec3 protobuf of the tolerances for goal waypoint selection.
command_id: If not None, this continues an existing navigate_to command with the given ID. If None,
a new command_id will be used.
Returns:
int: Command ID to use in feedback lookup.
Raises:
RpcError: Problem communicating with the robot.
LeaseUseError: Error using provided leases.
graph_nav.NoTimeSyncError: Missing clock identifier.
graph_nav.CommandExpiredError: Command already expired.
graph_nav.TooDistantError: Time too far in the future.
graph_nav.RobotImpairedError: Robot cannot travel a route.
graph_nav.IsRecordingError: Robot cannot navigate while recording.
graph_nav.NoAnchoringError: There is no anchoring.
graph_nav.NoPathError: No route to goal waypoint, or no goal waypoint found.
graph_nav.InvalidPoseError: The requested pose is invalid, or known to be unachievable.
graph_nav.RobotNotLocalizedToRouteError: The robot not correctly localized.
graph_nav.RouteNavigationError: A subclass detailing trouble navigating the route.
"""
used_endpoint = timesync_endpoint or self._timesync_endpoint
if not used_endpoint:
raise GraphNavServiceResponseError(response=None, error_message='No timesync endpoint!')
request = self._build_navigate_to_anchor_request(seed_tform_goal, travel_params,
route_params, cmd_duration, leases,
used_endpoint, command_id,
goal_waypoint_rt_seed_ewrt_seed_tolerance)
return self.call(self._stub.NavigateToAnchor, request,
value_from_response=_command_id_from_navigate_route_response,
error_from_response=_navigate_to_anchor_error, copy_request=False,
**kwargs)
def navigate_to_anchor_async(self, seed_tform_goal, cmd_duration, route_params=None,
travel_params=None, leases=None, timesync_endpoint=None,
goal_waypoint_rt_seed_ewrt_seed_tolerance=None, command_id=None,
**kwargs):
"""Async version of navigate_to_anchor()."""
used_endpoint = timesync_endpoint or self._timesync_endpoint
if not used_endpoint:
raise GraphNavServiceResponseError(response=None, error_message='No timesync endpoint!')
request = self._build_navigate_to_anchor_request(seed_tform_goal, travel_params,
route_params, cmd_duration, leases,
used_endpoint, command_id,
goal_waypoint_rt_seed_ewrt_seed_tolerance)
return self.call_async(self._stub.NavigateTo, request,
value_from_response=_command_id_from_navigate_route_response,
error_from_response=_navigate_to_anchor_error, copy_request=False,
**kwargs)
def navigation_feedback(self, command_id=0, **kwargs):
"""Returns the feedback corresponding to the active route follow command.
Args:
command_id (int): If blank, will return current command status. If filled
out, will attempt to return that command status
Returns:
NavigationFeedbackResponse
Raises:
RpcError: Problem communicating with the robot.
"""
request = self._build_navigate_feedback_request(command_id)
return self.call(self._stub.NavigationFeedback, request, value_from_response=_get_response,
error_from_response=_navigate_feedback_error, copy_request=False, **kwargs)
def navigation_feedback_async(self, command_id=0, **kwargs):
"""Async version of navigation_feedback()."""
request = self._build_navigate_feedback_request(command_id)
return self.call_async(self._stub.NavigationFeedback, request,
value_from_response=_get_response,
error_from_response=_navigate_feedback_error, copy_request=False,
**kwargs)
def clear_graph(self, lease=None, **kwargs):
"""Clears the local graph structure. Also erases any snapshots currently in RAM.
Args:
lease: Leases to show ownership of necessary resources. Will use the client's leases by default.
Raises:
RpcError: Problem communicating with the robot.
LeaseUseError: Error using provided lease.
"""
request = self._build_clear_graph_request(lease)
return self.call(self._stub.ClearGraph, request, value_from_response=None,
error_from_response=_clear_graph_error, copy_request=False, **kwargs)
def clear_graph_async(self, lease=None, **kwargs):
"""Async version of clear_graph()."""
request = self._build_clear_graph_request(lease)
return self.call_async(self._stub.ClearGraph, request, value_from_response=None,
error_from_response=handle_common_header_errors(common_lease_errors),
copy_request=False, **kwargs)
def upload_graph(self, lease=None, graph=None, generate_new_anchoring=False, **kwargs):
"""Uploads a graph to the server and appends to the existing graph.
Args:
lease: Leases to show ownership of necessary resources. Will use the client's leases by default.
graph: Graph protobuf that represents the map with waypoints and edges.
generate_new_anchoring: Whether to generate an (overwrite the) anchoring on upload.
Returns:
The response, which includes waypoint and edge id's sorted by whether it was cached.
Raises:
RpcError: Problem communicating with the robot.
LeaseUseError: Error using provided lease.
"""
request = self._build_upload_graph_request(lease, graph, generate_new_anchoring)
return self.call(self._stub.UploadGraph, request, value_from_response=_get_response,
error_from_response=_upload_graph_error, copy_request=False, **kwargs)
def upload_graph_async(self, lease=None, graph=None, generate_new_anchoring=False, **kwargs):
"""Async version of upload_graph()."""
request = self._build_upload_graph_request(lease, graph, generate_new_anchoring)
return self.call_async(self._stub.UploadGraph, request, value_from_response=_get_response,
error_from_response=_upload_graph_error, copy_request=False,
**kwargs)
def upload_waypoint_snapshot(self, waypoint_snapshot, lease=None, **kwargs):
"""Uploads large waypoint snapshot as a stream for a particular waypoint.
Args:
lease: Leases to show ownership of necessary resources. Will use the client's leases by default.
waypoint_snapshot: WaypointSnapshot protobuf that will be stream-uploaded to the robot.
Returns:
The status of the upload request.
Raises:
RpcError: Problem communicating with the robot.
LeaseUseError: Error using provided lease.
"""
lease = lease or lease_pb2.Lease()
serialized = waypoint_snapshot.SerializeToString()
self.call(
self._stub.UploadWaypointSnapshot,
GraphNavClient._data_chunk_iterator_upload_waypoint_snapshot(
serialized, lease, self._data_chunk_size), value_from_response=None,
error_from_response=_upload_waypoint_snapshot_error, **kwargs)
def upload_edge_snapshot(self, edge_snapshot, lease=None, **kwargs):
"""Uploads large edge snapshot as a stream for a particular edge.
Args:
lease: Leases to show ownership of necessary resources. Will use the client's leases by default.
edge_snapshot: EdgeSnapshot protobuf that will be stream-uploaded to the robot.
Returns:
The status of the upload request.
Raises:
RpcError: Problem communicating with the robot.
LeaseUseError: Error using provided leases.
"""
lease = lease or lease_pb2.Lease()
serialized = edge_snapshot.SerializeToString()
self.call(
self._stub.UploadEdgeSnapshot,
GraphNavClient._data_chunk_iterator_upload_edge_snapshot(serialized, lease,
self._data_chunk_size),
value_from_response=None,
error_from_response=handle_common_header_errors(common_lease_errors), **kwargs)
def download_graph(self, **kwargs):
"""Downloads the graph from the server.
Returns:
The graph protobuf that represents the current map on the robot (with waypoints and edges).
Raises:
RpcError: Problem communicating with the robot
"""
request = self._build_download_graph_request()
return self.call(self._stub.DownloadGraph, request, value_from_response=_get_graph,
error_from_response=common_header_errors, copy_request=False, **kwargs)
def download_graph_async(self, **kwargs):
"""Async version of download_graph()."""
request = self._build_download_graph_request()
return self.call_async(self._stub.DownloadGraph, request, value_from_response=_get_graph,
error_from_response=common_header_errors, copy_request=False,
**kwargs)
def download_waypoint_snapshot(
self,
waypoint_snapshot_id,
download_images=False,
do_not_download_point_cloud=False,
**kwargs):
"""Download a specific waypoint snapshot with streaming from the server.
Args:
waypoint_snapshot_id: WaypointSnapshot string ID for which snapshot to download from robot.
download_images: Boolean indicating whether to include images in the download.
do_not_download_point_cloud: Boolean indicating if point cloud data should not be downloaded.
Returns:
The WaypointSnapshot protobuf from the robot's current map.
Raises:
RpcError: Problem communicating with the robot
UnknownMapInformationError: Snapshot id not found
"""
request = self._build_download_waypoint_snapshot_request(
waypoint_snapshot_id,
download_images,
do_not_download_point_cloud)
return self.call(self._stub.DownloadWaypointSnapshot, request,
value_from_response=_get_streamed_waypoint_snapshot,
error_from_response=_download_waypoint_snapshot_stream_errors,
copy_request=False, **kwargs)
def download_edge_snapshot(self, edge_snapshot_id, **kwargs):
"""Downloads a specific edge snapshot with streaming from the server.
Args:
edge_snapshot_id: EdgeSnapshot string ID for which snapshot to download from robot.
Returns:
The EdgeSnapshot protobuf from the robot's current map.
Raises:
RpcError: Problem communicating with the robot
UnknownMapInformationError: Snapshot id not found
"""
request = self._build_download_edge_snapshot_request(edge_snapshot_id)
return self.call(self._stub.DownloadEdgeSnapshot, request,
value_from_response=_get_streamed_edge_snapshot,
error_from_response=_download_edge_snapshot_stream_errors,
copy_request=False, **kwargs)
def _write_bytes(self, filepath, filename, data):
"""Write data to a file."""
os.makedirs(filepath, exist_ok=True)
with open(filepath + filename, 'wb+') as f:
f.write(data)
f.close()
def write_graph_and_snapshots(self, directory):
"""Download the graph and snapshots from robot to the specified directory."""
graph = self.download_graph()
graph_bytes = graph.SerializeToString()
self._write_bytes(directory, '/graph', graph_bytes)
for waypoint in graph.waypoints:
if len(waypoint.snapshot_id) == 0:
continue
waypoint_snapshot = self.download_waypoint_snapshot(waypoint.snapshot_id)
self._write_bytes(directory + '/waypoint_snapshots', '/' + waypoint.snapshot_id,
waypoint_snapshot.SerializeToString())
for edge in graph.edges:
if len(edge.snapshot_id) == 0:
continue
edge_snapshot = self.download_edge_snapshot(edge.snapshot_id)
self._write_bytes(directory + '/edge_snapshots', '/' + edge.snapshot_id,
edge_snapshot.SerializeToString())
@staticmethod
def _build_set_localization_request(
initial_guess_localization, ko_tform_body=None, max_distance=None, max_yaw=None,
fiducial_init=graph_nav_pb2.SetLocalizationRequest.FIDUCIAL_INIT_NEAREST,
use_fiducial_id=None, refine_fiducial_result_with_icp=False, do_ambiguity_check=False,
refine_with_visual_features=False, verify_visual_features_quality=False):
request = graph_nav_pb2.SetLocalizationRequest(fiducial_init=fiducial_init)
request.initial_guess.CopyFrom(initial_guess_localization)
if ko_tform_body is not None:
request.ko_tform_body.CopyFrom(ko_tform_body)
if max_distance is not None:
request.max_distance = max_distance
if max_yaw is not None:
request.max_yaw = max_yaw
if (fiducial_init == graph_nav_pb2.SetLocalizationRequest.FIDUCIAL_INIT_SPECIFIC):
if use_fiducial_id is not None:
request.use_fiducial_id = use_fiducial_id
if refine_with_visual_features:
request.refine_with_visual_features.verify_refinement_quality = verify_visual_features_quality
elif refine_fiducial_result_with_icp:
request.refine_fiducial_result_with_icp = refine_fiducial_result_with_icp
request.do_ambiguity_check = do_ambiguity_check
return request
@staticmethod
def _build_get_localization_state_request(request_live_point_cloud, request_live_images,
request_live_terrain_maps, request_live_world_objects,
request_live_robot_state, waypoint_id):
return graph_nav_pb2.GetLocalizationStateRequest(
request_live_point_cloud=request_live_point_cloud,
request_live_images=request_live_images,
request_live_terrain_maps=request_live_terrain_maps,
request_live_world_objects=request_live_world_objects,
request_live_robot_state=request_live_robot_state, waypoint_id=waypoint_id)
@staticmethod
def _build_navigate_route_request(route, route_follow_params, travel_params, end_time_secs,
leases, timesync_endpoint, command_id,
destination_waypoint_tform_body_goal):
converter = timesync_endpoint.get_robot_time_converter()
request = graph_nav_pb2.NavigateRouteRequest(
route=route, route_follow_params=route_follow_params,
destination_waypoint_tform_body_goal=destination_waypoint_tform_body_goal,
clock_identifier=timesync_endpoint.clock_identifier)
if travel_params is not None:
request.travel_params.CopyFrom(travel_params)
request.end_time.CopyFrom(
converter.robot_timestamp_from_local_secs(time.time() + end_time_secs))
if command_id is not None:
request.command_id = command_id
return request
@staticmethod
def _build_navigate_to_request(destination_waypoint_id, travel_params, route_params,
end_time_secs, leases, timesync_endpoint, command_id,
destination_waypoint_tform_body_goal, route_blocked_behavior):
converter = timesync_endpoint.get_robot_time_converter()
request = graph_nav_pb2.NavigateToRequest(
destination_waypoint_id=destination_waypoint_id,
destination_waypoint_tform_body_goal=destination_waypoint_tform_body_goal,
clock_identifier=timesync_endpoint.clock_identifier)
request.end_time.CopyFrom(
converter.robot_timestamp_from_local_secs(time.time() + end_time_secs))
if travel_params is not None:
request.travel_params.CopyFrom(travel_params)
if route_params is not None:
request.route_params.CopyFrom(route_params)
if command_id is not None:
request.command_id = command_id
if route_blocked_behavior is not None:
request.route_blocked_behavior = route_blocked_behavior
return request
@staticmethod
def _build_navigate_to_anchor_request(seed_tform_goal, travel_params, route_params,
end_time_secs, leases, timesync_endpoint, command_id,
goal_waypoint_rt_seed_ewrt_seed_tolerance):
converter = timesync_endpoint.get_robot_time_converter()
request = graph_nav_pb2.NavigateToAnchorRequest(
seed_tform_goal=seed_tform_goal,
goal_waypoint_rt_seed_ewrt_seed_tolerance=goal_waypoint_rt_seed_ewrt_seed_tolerance,
clock_identifier=timesync_endpoint.clock_identifier)
request.end_time.CopyFrom(
converter.robot_timestamp_from_local_secs(time.time() + end_time_secs))
if travel_params is not None:
request.travel_params.CopyFrom(travel_params)
if route_params is not None:
request.route_params.CopyFrom(route_params)
if command_id is not None:
request.command_id = command_id
return request
@staticmethod
def _build_clear_graph_request(lease):
lease = lease or lease_pb2.Lease()
return graph_nav_pb2.ClearGraphRequest(lease=lease)
@staticmethod
def _build_navigate_feedback_request(command_id=0):
return graph_nav_pb2.NavigationFeedbackRequest(command_id=command_id)
@staticmethod
def _build_upload_graph_request(lease, graph, generate_new_anchoring):
lease = lease or lease_pb2.Lease()
return graph_nav_pb2.UploadGraphRequest(lease=lease, graph=graph,
generate_new_anchoring=generate_new_anchoring)
@staticmethod
def _data_chunk_iterator_upload_waypoint_snapshot(serialized_waypoint_snapshot, lease,
data_chunk_byte_size):
total_bytes_size = len(serialized_waypoint_snapshot)
num_chunks = math.ceil(total_bytes_size / data_chunk_byte_size)
for i in range(num_chunks):
start_index = i * data_chunk_byte_size
end_index = (i + 1) * data_chunk_byte_size
chunk = data_chunk_pb2.DataChunk(total_size=total_bytes_size)
if (end_index > total_bytes_size):
chunk.data = serialized_waypoint_snapshot[start_index:total_bytes_size]
else:
chunk.data = serialized_waypoint_snapshot[start_index:end_index]
req = graph_nav_pb2.UploadWaypointSnapshotRequest(lease=lease, chunk=chunk)
yield req
@staticmethod
def _data_chunk_iterator_upload_edge_snapshot(serialized_edge_snapshot, lease,
data_chunk_byte_size):
total_bytes_size = len(serialized_edge_snapshot)
num_chunks = math.ceil(total_bytes_size / data_chunk_byte_size)
for i in range(num_chunks):
start_index = i * data_chunk_byte_size
end_index = (i + 1) * data_chunk_byte_size
chunk = data_chunk_pb2.DataChunk(total_size=total_bytes_size)
if (end_index > total_bytes_size):
chunk.data = serialized_edge_snapshot[start_index:total_bytes_size]
else:
chunk.data = serialized_edge_snapshot[start_index:end_index]
req = graph_nav_pb2.UploadEdgeSnapshotRequest(lease=lease, chunk=chunk)
yield req
@staticmethod
def _build_download_graph_request():
return graph_nav_pb2.DownloadGraphRequest()
@staticmethod
def _build_download_waypoint_snapshot_request(
waypoint_snapshot_id,
download_images,
do_not_download_point_cloud=False):
return graph_nav_pb2.DownloadWaypointSnapshotRequest(
waypoint_snapshot_id=waypoint_snapshot_id,
download_images=download_images,
do_not_download_point_cloud=do_not_download_point_cloud)
@staticmethod
def _build_download_edge_snapshot_request(edge_snapshot_id):
return graph_nav_pb2.DownloadEdgeSnapshotRequest(edge_snapshot_id=edge_snapshot_id)
@staticmethod
def generate_travel_params(max_distance, max_yaw, velocity_limit=None):
""" Generate the API TravelParams for navigation requests.
Args:
max_distance: Distances (meters) threshold for when we've reached the final waypoint.
max_yaw: Angle (radians) threshold for when we've reached the final waypoint.
velocity_limit: SE2VelocityLimit protobuf message for the speed the robot should use.
Returns:
The API TravelParams protobuf message.
"""
travel_params = graph_nav_pb2.TravelParams(max_distance=max_distance, max_yaw=max_yaw)
if velocity_limit is not None:
travel_params.velocity_limit.CopyFrom(velocity_limit)
return travel_params
@staticmethod
def build_route(waypoint_id_list, edge_id_list):
""" Generate the API Route for navigation requests.
Args:
waypoint_id_list: List of waypoint id strings in which a route should pass through.
The ids should be ordered from [start waypoint --> destination waypoint].
edge_id_list: List of the edge_id's which should be in the same ordering as the waypoint list.
Returns:
The API Route protobuf message.
"""
route = nav_pb2.Route()
route.waypoint_id.extend(waypoint_id_list)
route.edge_id.extend(edge_id_list)
return route
'''
Static helper methods for handing responses and errors.
'''
class GraphNavServiceResponseError(ResponseError):
"""General class of errors for the GraphNav Recording Service."""
class UploadWaypointSnapshotError(GraphNavServiceResponseError):
"""Errors related to uploading a waypoint snapshot"""
class UploadGraphError(GraphNavServiceResponseError):
"""Errors related to uploading a graph."""
class MapTooLargeLicenseError(UploadGraphError):
"""The map is too large for the license on the robot."""
class InvalidGraphError(UploadGraphError):
"""The graph is invalid topologically, e.g. missing waypoints referenced by edges."""
class IncompatibleSensorsError(GraphNavServiceResponseError):
"""The map was recorded with using a sensor configuration which is incompatible with the robot (for example, LIDAR configuration)."""
class AreaCallbackMapError(GraphNavServiceResponseError):
"""The map specified an area callback that is not registered or is faulted."""
class RequestAbortedError(GraphNavServiceResponseError):
"""Request was aborted by the system."""
class RequestFailedError(GraphNavServiceResponseError):
"""Request failed to complete by the system."""
class RobotFaultedError(GraphNavServiceResponseError):
"""Robot is experiencing a fault condition that prevents localization."""
class UnknownMapInformationError(GraphNavServiceResponseError):
"""The given map information (waypoints,edges,routes) is unknown by the system."""
class TimeError(GraphNavServiceResponseError):
"""Errors associated with timestamps and time sync."""
class CommandExpiredError(TimeError):
"""The command was received after its end time had already passed."""
class NoTimeSyncError(TimeError):
"""Client has not performed timesync with robot."""
class TooDistantError(TimeError):
"""The command was too far in the future."""
class RobotStateError(GraphNavServiceResponseError):
"""Errors associated with the current state of the robot."""
class IsRecordingError(RobotStateError):
"""Cannot navigate a route while recording a map."""
class CannotModifyMapDuringRecordingError(RobotStateError):
"""Cannot clear the map during recording. Call StopRecording first."""
class RobotImpairedError(RobotStateError):
"""Robot has a critical perception or behavior fault and cannot navigate."""
class RouteError(GraphNavServiceResponseError):
"""Errors associated with the specified route."""
class ConstraintFaultError(RouteError):
"""Route parameters contained a constraint fault."""
class InvalidEdgeError(RouteError):
"""One or more edges do not connect to expected waypoints."""
@deprecated(reason='Use UnknownRouteElementsError instead', version='3.0.0', action='ignore')
class UnkownRouteElementsError(RouteError):
"""One or more waypoints/edges are not in the map."""
class UnknownRouteElementsError(UnkownRouteElementsError):
"""One or more waypoints/edges are not in the map."""
class NoPathError(RouteError):
"""There is no path to the specified waypoint."""
class UnknownWaypointError(RouteError):
"""One or more waypoints are not in the map."""
class NoAnchoringError(RouteError):
"""There is no anchoring."""
class InvalidPoseError(RouteError):
"""The requested pose is invalid, or known to be unachievable."""
class RouteNavigationError(GraphNavServiceResponseError):
"""Errors related to how the robot navigates the route."""
class FeatureDesertError(RouteNavigationError):
"""Route contained too many waypoints with low-quality features."""
class RouteNotUpdatingError(RouteNavigationError):
"""Graph nav was unable to update and follow the specified route."""
class RobotLostError(RouteNavigationError):
"""Cannot issue a navigation request when the robot is already lost."""
class RobotNotLocalizedToRouteError(RouteNavigationError):
"""The current localization doesn't refer to any waypoint in the route (possibly uninitialized localization)."""
class RobotStuckError(RouteNavigationError):
"""The robot is stuck or unable to find a way forward. Resend the command with a new ID, or send a different command to try again."""
@deprecated(reason='Use UnrecognizedCommandError instead', version='3.1.0', action='ignore')
class UnrecongizedCommandError(RouteNavigationError):
"""Happens when you try to continue a command that was either expired, or had an unrecognized id."""
class UnrecognizedCommandError(UnrecongizedCommandError):
"""Happens when you try to continue a command that was either expired, or had an unrecognized id."""
def _localization_from_response(response):
"""Return the localization state from the response."""
return response.localization
def _command_id_from_navigate_route_response(response):
"""Return the navigation command id from the response."""
return response.command_id
def _get_status(response):
"""Return the status of the response."""
return response.status
def _get_response(response):
"""Return full response for RecordStatus to get environment and is_recording information."""
return response
def _get_graph(response):
"""Returns the graph from the response."""
return response.graph
def _get_streamed_waypoint_snapshot(response):
"""Reads a streamed response to recreate a waypoint snapshot."""
data = ''
num_chunks = 0
for resp in response:
if num_chunks == 0:
data = resp.chunk.data
else:
data += resp.chunk.data
num_chunks += 1
waypoint_snapshot = map_pb2.WaypointSnapshot()
if (num_chunks > 0):
waypoint_snapshot.ParseFromString(data)
return waypoint_snapshot
def _get_streamed_edge_snapshot(response):
"""Reads a streamed response to recreate an edge snapshot."""
data = ''
num_chunks = 0
for resp in response:
if num_chunks == 0:
data = resp.chunk.data
else:
data += resp.chunk.data
num_chunks += 1
edge_snapshot = map_pb2.EdgeSnapshot()
if (num_chunks > 0):
edge_snapshot.ParseFromString(data)
return edge_snapshot