-
Notifications
You must be signed in to change notification settings - Fork 0
/
spot_api.py
1568 lines (1295 loc) · 59.9 KB
/
spot_api.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
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
"""
A file containing the base code required to start up spot.
"""
import argparse
from contextlib import contextmanager
import io
import logging
import time
from typing import Any, Generator, Generic, List, Literal, Tuple, TypeVar, Union
from PIL.Image import Image
import PIL.Image
from scipy.ndimage import rotate as scirotate
import bosdyn.client
import bosdyn.client.lease
import bosdyn.client.util
from google.protobuf import duration_pb2
from bosdyn.client.power import PowerClient
from bosdyn.client.robot_state import RobotStateClient
from bosdyn.client.world_object import WorldObjectClient
from bosdyn.client.robot_id import RobotIdClient
from bosdyn.client.robot_command import (
RobotCommandClient,
RobotCommandBuilder,
blocking_selfright,
blocking_sit,
blocking_command,
block_for_trajectory_cmd,
block_until_arm_arrives,
)
from bosdyn.client.image import ImageClient, build_image_request
from bosdyn.client.lease import LeaseClient
from bosdyn.client.math_helpers import Quat, SE3Pose, math
from bosdyn.client.frame_helpers import (
GRAV_ALIGNED_BODY_FRAME_NAME,
ODOM_FRAME_NAME,
BODY_FRAME_NAME,
get_a_tform_b,
)
import bosdyn.api.basic_command_pb2 as basic_command_pb2
from bosdyn.api import (
geometry_pb2,
trajectory_pb2,
world_object_pb2,
arm_surface_contact_pb2,
arm_surface_contact_service_pb2,
#mobility_command_pb2,
arm_command_pb2,
synchronized_command_pb2,
robot_command_pb2,
mobility_command_pb2,
)
from bosdyn.client.manipulation_api_client import ManipulationApiClient
from bosdyn.util import seconds_to_timestamp
from bosdyn.client.arm_surface_contact import ArmSurfaceContactClient
import numpy as np
Num = int | float
class SpotConfig:
"""
A configuration for a Spot robot.
"""
def __init__(self):
self.hostname: str = "192.168.80.3" # The hostname of the Spot robot
self.log_level: int = logging.ERROR # what level to log at
def add_args_to(self, parser: argparse.ArgumentParser) -> "SpotConfig":
"""
Adds the arguments of the config to the given parser so that the user can query them.
"""
# hostname
parser.add_argument(
"--hostname",
default="192.168.80.3",
help="Hostname or address of robot," ' e.g. "beta25-p" or "192.168.80.3"',
)
# Logging Levels
parser.add_argument(
"--log_level",
help="Determines the level to log at.",
default="warning",
choices=["debug", "info", "warning", "error", "critical"],
)
return self
def arg_parse_set(self, namespace: argparse.Namespace) -> "SpotConfig":
"""
Sets the values of this config based on the given arg parse result.
"""
if namespace.loglevel:
match namespace.log_level:
case "debug":
level = logging.DEBUG
case "info":
level = logging.INFO
case "error":
level = logging.ERROR
case "critical":
level = logging.CRITICAL
case _:
level = logging.WARNING
self.log_level = level
return self
def arg_parse(self) -> "SpotConfig":
"""
Parses the config arguments.
"""
parser = argparse.ArgumentParser()
self.add_args_to(parser)
self.arg_parse_set(parser.parse_args())
return self
IMAGE_PIXEL_FORMAT = Union[
Literal["PIXEL_FORMAT_GREYSCALE_U16"],
Literal["PIXEL_FORMAT_DEPTH_U16"],
Literal["PIXEL_FORMAT_RGBA_U8"],
Literal["PIXEL_FORMAT_RGB_U8"],
Literal["PIXEL_FORMAT_GREYSCALE_U8"],
# Literal['PIXEL_FORMAT_UNKNOWN'],
]
IMAGE_FORMAT = Union[
Literal["FORMAT_RLE"],
Literal["FORMAT_RAW"],
Literal["FORMAT_JPEG"],
# Literal['FORMAT_UNKNOWN'],
]
T = TypeVar("T")
class SpotImageResponse(Generic[T]):
"""
A class to help return Spot's response when images are requested.
"""
def __init__(
self,
frontleft: T | None = None,
frontright: T | None = None,
left: T | None = None,
right: T | None = None,
back: T | None = None,
frontleft_response: Any | None = None,
frontright_response: Any | None = None,
left_response: Any | None = None,
right_response: Any | None = None,
back_response: Any | None = None,
):
self.frontleft: T | None = frontleft
self.frontright: T | None = frontright
self.left: T | None = left
self.right: T | None = right
self.back: T | None = back
self.frontleft_response: Any | None = frontleft_response
self.frontright_response: Any | None = frontright_response
self.left_response: Any | None = left_response
self.right_response: Any | None = right_response
self.back_response: Any | None = back_response
def response_list(self) -> List[Any]:
"""
Returns this response as a list of received images, omitting from the
list the images that were not received. The images are
otherwise in the same order as `self.maybe_response_list()` would return them.
"""
return [v for v in self.maybe_response_list() if v is not None]
def maybe_response_list(self) -> List[Any | None]:
"""
Returns this response as a list of received images in
`[frontleft, frontright, left, right, back]` order, replacing
any images that were not requested with `None`.
"""
return [
self.frontleft_response,
self.frontright_response,
self.left_response,
self.right_response,
self.back_response,
]
def image_list(self) -> List[T]:
"""
Returns this response as a list of received images, omitting from the
list the images that were not received. The images are
otherwise in the same order as `self.maybe_image_list()` would return them.
"""
return [v for v in self.maybe_image_list() if v is not None]
def maybe_image_list(self) -> List[T | None]:
"""
Returns this response as a list of received images in
`[frontleft, frontright, left, right, back]` order, replacing
any images that were not requested with `None`.
"""
return [self.frontleft, self.frontright, self.left, self.right, self.back]
async def dummy():
"""
A function is only run asynchronously after its first `await`. This function
only exists so that said `await` can be called up front rather than later.
"""
return None
class Fiducial:
"""
A class that encompasses the information of a fiducial.
"""
@staticmethod
def from_apriltag_world_object(world_object) -> "Fiducial":
"""
Returns a new `Fiducial` created from the given `WorldObject`.
"""
transforms = world_object.transforms_snapshot
apriltag_info = world_object.apriltag_properties
tag_id = apriltag_info.tag_id
frame_name = apriltag_info.frame_name_fiducial
frame_name_filtered = apriltag_info.frame_name_fiducial_filtered
#frame_name_camera = apriltag_info.frame_name_camera
return Fiducial(transforms, tag_id, frame_name, frame_name_filtered)
def __init__(self,
transforms,
tag_id: int,
frame_name_fiducial: str,
frame_name_fiducial_filtered: str
):
# A snapshot of the frame tree.
self.transforms_snapshot = transforms
self.id: int = tag_id
self.frame_name_fiducial: str = frame_name_fiducial
self.frame_name_fiducial_filtered: str = frame_name_fiducial_filtered
def body_t_fiducial(self) -> SE3Pose:
"""
Returns the grav-aligned body pose relative to the fiducial pose.
"""
return get_a_tform_b(self.transforms_snapshot, BODY_FRAME_NAME, self.frame_name_fiducial_filtered)
def odom_t_fiducial(self) -> SE3Pose:
"""
Returns the odom pose relative to the fiducial pose.
"""
return get_a_tform_b(self.transforms_snapshot, ODOM_FRAME_NAME, self.frame_name_fiducial_filtered)
def frame_t_fiducial(self, frame_name: str) -> SE3Pose | None:
"""
Returns the pose of this `Fiducial` relative to the given frame.
Args:
frame_name: the name of the "frame" in `frame_t_tag`
"""
return get_a_tform_b(self.transforms_snapshot, frame_name, self.frame_name_fiducial_filtered)
class LeaseTracker:
"""
A small class that keeps track of how many `LeasedSpot` objects there are
for a specific Spot, only dropping the lease when all `LeasedSpot` objects
have stopped requesting a lease.
"""
def __init__(self, lease_client: LeaseClient):
self._lease_client: LeaseClient = lease_client
self._count: int = 0
self._lease: None | bosdyn.client.lease.LeaseKeepAlive = None
# --- Lease Start ---
def _start_lease(self):
# check for previous lease
if self._lease is not None:
# end previous lease
self._lease.__exit__(None, None, None)
# start new lease
self._lease = bosdyn.client.lease.LeaseKeepAlive(
self._lease_client,
must_acquire=True,
return_at_exit=True,
)
self._lease.__enter__()
def _end_lease(self, exc_type, exc_val, traceback):
# check for lease
if self._lease is not None:
self._lease.__exit__(exc_type, exc_val, traceback)
self._lease = None
# --- Context Manager Functions ---
def __enter__(self):
self._count = max(self._count, 0)
if self._count == 0:
self._start_lease()
self._count += 1
def __exit__(self, exc_type, exc_val, traceback):
self._count -= 1
if self._count <= 0:
self._count = 0
class SpotShared:
"""
A class used to encompass the data shared by both leased and unleased spot robots.
"""
def __init__(
self,
config: SpotConfig,
bosdyn_sdk: bosdyn.client.Sdk,
robot: bosdyn.client.Robot,
image_client: ImageClient,
power_client: PowerClient,
lease_client: LeaseClient,
state_client: RobotStateClient,
command_client: RobotCommandClient,
world_client: WorldObjectClient,
id_client: RobotIdClient,
manipulation_client: ManipulationApiClient,
arm_surface_contact_client: ArmSurfaceContactClient,
):
self.config: SpotConfig = config
self.sdk: bosdyn.client.Sdk = bosdyn_sdk
self.robot: bosdyn.client.Robot = robot
self.image_client: ImageClient = image_client
self.power_client: PowerClient = power_client
self.lease_client: LeaseClient = lease_client
self.state_client: RobotStateClient = state_client
self.command_client: RobotCommandClient = command_client
self.world_object_client: WorldObjectClient = world_client
self.id_client: RobotIdClient = id_client
self.manipulation_client: ManipulationApiClient = manipulation_client
self.arm_surface_contact_client: ArmSurfaceContactClient = (
arm_surface_contact_client
)
self.lease_tracker: LeaseTracker = LeaseTracker(lease_client)
class Spot:
"""
A class to encapsulate the functionality of controlling a Boston Dynamics
Spot robot.
A Spot has a small amount of functionality that it can perform without a
lease. If you want to do more (such as making the robot move around) you can
use `with spot.leased() as spot: ...` to perform functionality that require
a lease.
"""
def __init__(
self,
config: SpotShared | SpotConfig | None = None,
bosdyn_sdk: bosdyn.client.Sdk | None = None,
setup_logging: bool = True,
):
# If the config is actually an instance of `SpotShared`, then the Spot
# is already initialized and we can just return
if isinstance(config, SpotShared):
self._shared = config
return
# --- Initalize Spot ---
if config is None:
config = SpotConfig()
# The Boston Dynamics Python library uses Python's logging module to
# generate output. Applications using the library can specify how
# the logging information should be output.
if setup_logging:
bosdyn.client.util.setup_logging(config.log_level)
# The SDK object is the primary entry point to the Boston Dynamics API.
# create_standard_sdk will initialize an SDK object with typical default
# parameters. The argument passed in is a string identifying the client.
if bosdyn_sdk is None:
sdk = bosdyn.client.create_standard_sdk("SpotClient")
else:
sdk = bosdyn_sdk
# The Spot robot.
robot = sdk.create_robot(config.hostname)
robot.logger.setLevel(config.log_level)
# Clients need to authenticate to a robot before being able to use it.
bosdyn.client.util.authenticate(robot)
robot.sync_with_directory()
# Establish time sync with the robot. This kicks off a background thread to establish time sync.
# Time sync is required to issue commands to the robot. After starting time sync thread, block
# until sync is established.
robot.time_sync.wait_for_sync()
# The robot state client will allow us to get the robot's state information, and construct
# a command using frame information published by the robot.
robot.logger.info("Ensuring State Client")
state_client = robot.ensure_client(RobotStateClient.default_service_name)
robot.logger.info("Ensuring Image Client")
image_client = robot.ensure_client(ImageClient.default_service_name)
robot.logger.info("Ensuring Command Client")
command_client = robot.ensure_client(RobotCommandClient.default_service_name)
robot.logger.info("Ensuring Power Client")
power_client = robot.ensure_client(PowerClient.default_service_name)
# The client
robot.logger.info("Ensuring World Object Client")
world_object_client = robot.ensure_client(
WorldObjectClient.default_service_name
)
robot.logger.info("Ensuring Robot ID Client")
id_client = robot.ensure_client(RobotIdClient.default_service_name)
robot.logger.info("Ensuring Robot Manipulation Client")
manip_client = robot.ensure_client(ManipulationApiClient.default_service_name)
robot.logger.info("Ensuring Robot Arm Surface Contact Client")
arm_surface_contact_client = robot.ensure_client(
ArmSurfaceContactClient.default_service_name
)
# Only one client at a time can operate a robot. Clients acquire a lease to
# indicate that they want to control a robot. Acquiring may fail if another
# client is currently controlling the robot. When the client is done
# controlling the robot, it should return the lease so other clients can
# control it. The LeaseKeepAlive object takes care of acquiring and returning
# the lease for us.
robot.logger.info("Ensuring Robot Lease Client")
lease_client = robot.ensure_client(LeaseClient.default_service_name)
self._shared: SpotShared = SpotShared(
config,
sdk,
robot,
image_client,
power_client,
lease_client,
state_client,
command_client,
world_object_client,
id_client,
manip_client,
arm_surface_contact_client,
)
def image_client(self) -> ImageClient:
"""Returns Spot's image client."""
return self._shared.image_client
def power_client(self) -> PowerClient:
"""Returns Spot's power client."""
return self._shared.power_client
def lease_client(self) -> LeaseClient:
"""Returns Spot's lease client."""
return self._shared.lease_client
def state_client(self) -> RobotStateClient:
"""Returns Spot's state client."""
return self._shared.state_client
def command_client(self) -> RobotCommandClient:
"""Returns Spot's command client."""
return self._shared.command_client
def world_object_client(self) -> WorldObjectClient:
"""Returns Spot's world object client."""
return self._shared.world_object_client
def id_client(self) -> RobotIdClient:
"""Returns Spot's id client."""
return self._shared.id_client
def manipulation_api_client(self) -> ManipulationApiClient:
"""Returns Spot's manipulation api client."""
return self._shared.manipulation_client
def arm_surface_contact_client(self) -> ArmSurfaceContactClient:
"""Returns Spot's surface contact client."""
return self._shared.arm_surface_contact_client
async def robot_state(self):
"""Returns the robot state information."""
return self.state_client().get_robot_state()
async def robot_hardware(self):
"""Returns the robot hardware information."""
return self.state_client().get_hardware_config_with_link_info()
async def robot_metrics(self):
"""Returns the robot's metrics."""
return self.state_client().get_robot_metrics()
def has_arm(self, timeout: Num | None = None) -> bool:
"""
Returns `true` if the robot has an arm and `false` otherwise.
Args:
timeout: If the robot does not respond in `timeout` seconds then an error will be thrown. If the value is `None` then the command will never time out.
"""
return self.robot().has_arm(timeout)
@contextmanager
def leased(
self, check_estop: bool = True, take: bool = False
) -> Generator["LeasedSpot", Any, Any]:
"""
Returns a context manager that yields a leased handle on Spot. The
leased handle allows you to do more advanced things like move the
Spot around or power it on/off.
Args:
check_estop: whether to check for whether Spot is currently estopped or not
take: Will forcefully take the lease if necessary. Useful for taking the lease from the tablet so that the robot can be positioned via the tablet before it passes the lease to us and we run our code.
"""
if take:
self.lease_client().take()
# Verify the robot is not estopped and that an external application has registered and holds
# an estop endpoint.
if check_estop:
# check if there is currently an estop
# if not robot.is_estopped() and create_estop_if_none:
# no estop currently so start up a new process that will display the
# estop as a GUI
# os.system(f'start cmd /k ; python ./estop_gui.py {config.hostname}')
# with open(os.devnull, 'r+b', 0) as devnull:
# Popen(['python', './estop_gui.py', f'{config.hostname}'],
# stdin=devnull, stdout=STDOUT, stderr=STDOUT, close_fds=True)
# time.sleep(3) # give the estop process a few seconds to launch
# assert that we have an estop
assert not self.robot().is_estopped(), (
"Robot is estopped. Please use an external E-Stop client, "
"such as the estop SDK example, to configure E-Stop."
)
with self._shared.lease_tracker as _:
yield LeasedSpot(self._shared)
def config(self) -> SpotConfig:
"""
Returns Spot's configuration.
"""
return self._shared.config
def robot(self) -> bosdyn.client.Robot:
"""
Returns the raw Spot robot client from boston dynamics.
"""
return self._shared.robot
async def fiducials_in_view(self) -> list[Fiducial]:
"""
Returns a list of all fiducials currently in view.
"""
await dummy()
return [
Fiducial.from_apriltag_world_object(obj)
for obj in self.world_object_client()
.list_world_objects(object_type=[world_object_pb2.WORLD_OBJECT_APRILTAG])
.world_objects
]
async def transforms_snapshot(self, robot_state = None):
"""
Returns the transforms snapshot from the given robot_state or from a newly-gotten state if the given one is `None`.
"""
if robot_state is None:
robot_state = await self.robot_state()
return robot_state.kinematic_state.transforms_snapshot
NAMED_ROTATION = Literal["floor", "ceil", "forward", "backward", "left", "right"]
async def named_rotation(self, name: NAMED_ROTATION, frame_name: str, robot_state_transforms_snapshot = None) -> Quat:
"""
Returns the quaternion in the given frame that corresponds to the given named rotation.
Args:
name: the named rotation
frame_name: the frame that the rotation should be in
robot_state_transforms_snapshot: The transforms from `spot.transforms_snapshot()` so that the given named rotation can be converted to the desired rotation. If `None`, then the transforms are gotten by the function.
"""
if robot_state_transforms_snapshot is None:
robot_state_transforms_snapshot = await self.transforms_snapshot()
# get the rotation in the GRAV_ALIGNED_BODY_FRAME_NAME frame
if name == "floor":
rot = Quat.from_pitch(math.pi / 2)
elif name == "ceil":
rot = Quat.from_pitch(-math.pi / 2)
elif name == "forward":
rot = Quat.from_pitch(0)
elif name == "backward":
rot = Quat.from_pitch(math.pi)
elif name == "left":
rot = Quat.from_yaw(math.pi / 2)
elif name == "right":
rot = Quat.from_yaw(-math.pi / 2)
else:
raise AssertionError(f"{rot} was not a known named rotation")
flatbody_t_frame: Quat = get_a_tform_b(robot_state_transforms_snapshot, GRAV_ALIGNED_BODY_FRAME_NAME, frame_name).rotation
return (flatbody_t_frame * rot)
BODYCAM_NAME_TYPE = Literal["frontleft", "frontright", "left", "right", "back"]
BODYCAM_NAME: BODYCAM_NAME_TYPE = [
"frontleft",
"frontright",
"left",
"right",
"back",
]
BODYCAM_ROTATION = {
"frontleft": -90,
"frontright": -90,
"left": 0,
"right": 180,
"back": 0,
}
async def get_images(
self,
frontleft: bool = False,
frontright: bool = False,
left: bool = False,
right: bool = False,
back: bool = False,
rgb: bool = False,
greyscale: bool = False,
depth: bool = False,
rotate: bool = False,
quality_percent: int = 100,
depth_in_visual_frame: bool | None = None,
) -> Tuple[
SpotImageResponse[Image],
SpotImageResponse[Image],
SpotImageResponse[np.ndarray[np.uint16]],
list[Any],
]:
"""
Returns a list of images from spot.
Args:
frontleft: whether to request an image from the front-left camera
frontright: whether to request an image from the front-right camera
left: whether to request an image from the left camera
right: whether to request an image from the right camera
back: whether to request an image from the back camera
rgb: whether an RGB image should be gotten from each of the requested cameras
greyscale: whether a greyscale image should be gotten from each of the requested cameras
depth: whether a depth image should be gotten from each of the requested cameras
rotate: whether to rotate the images so that they are all upright (otherwise some of them are on their side or upside down)
quality_percent: a value in the range [0, 100] used to determine how high-res the images should be (0 is 0% resolution and 100 is %100 resolution, with values in-between being some percantage between %0 and %100 possible resolution)
depth_in_visual_frame: If True, the depth image will have its positions aligned with the positions in the greyscale and rgb images taken in the same call. If False, then the greyscale and rgb images taken in the same call will be aligned with the depth images. If None (the default), all images will be taken independantly.
Returns:
a tuple of `(rgb, greyscale, depth)` image responses that contain the requested images or `None` for images that were not requested
"""
await dummy() # the rest of this function is done async
requests = [
r if c else None
for r, c in zip(
Spot.BODYCAM_NAME, [frontleft, frontright, left, right, back]
)
]
# --- Create the requests ---
reqs: List[None | str | Tuple[str, str, str, str]] = []
# req rgb
for req in requests:
if not rgb or req is None:
reqs.append(None)
continue
cam = (
f"{req}_fisheye_image"
if depth_in_visual_frame is not False
else f"{req}_visual_in_depth"
)
reqs.append((cam, req, "rgb", "PIXEL_FORMAT_RGB_U8"))
# req greyscale
for req in requests:
if not greyscale or req is None:
reqs.append(None)
continue
cam = (
f"{req}_fisheye_image"
if depth_in_visual_frame is not False
else f"{req}_visual_in_depth"
)
reqs.append((cam, req, "greyscale", "PIXEL_FORMAT_GREYSCALE_U8"))
# req depth
for req in requests:
if not depth or req is None:
reqs.append(None)
continue
cam = (
f"{req}_depth_in_visual_frame"
if depth_in_visual_frame is True
else f"{req}_depth"
)
reqs.append(cam)
# --- Send the requests and receive the images ---
q = min(max(quality_percent, 0), 100)
built_reqs = []
for req in reqs:
if req is None:
continue
elif isinstance(req, str):
built_reqs.append(build_image_request(req, quality_percent=q))
else:
built_reqs.append(
build_image_request(
req[0],
image_format="FORMAT_JPEG",
pixel_format=req[3],
quality_percent=q,
)
)
image_responses = self.image_client().get_image(built_reqs)
# --- Handle the received images ---
# create the output tuple
i = 0
images = []
responses = []
for req in reqs:
if req is None:
images.append(None)
responses.append(None)
continue
response = image_responses[i]
i += 1
(rows, cols) = (response.shot.image.rows, response.shot.image.cols)
# pixel_format = image.shot.image.pixel_format
data = response.shot.image.data
if isinstance(req, str):
# depth is raw bytestream
img = np.frombuffer(data, dtype=np.uint16)
img = img.reshape(rows, cols)
if rotate:
img = scirotate(img, angle=self.BODYCAM_ROTATION[loc])
images.append(img)
responses.append(response)
else:
(_, loc, ty, _) = req
if ty == "rgb":
# rgb images are JPEG
img = PIL.Image.open(io.BytesIO(data))
if rotate:
img = img.rotate(self.BODYCAM_ROTATION[loc], expand=True)
images.append(img)
responses.append(response)
elif ty == "greyscale":
# greyscale images are JPEG
img = PIL.Image.open(io.BytesIO(data))
if rotate:
img = img.rotate(self.BODYCAM_ROTATION[loc], expand=True)
images.append(img)
responses.append(response)
return (
SpotImageResponse(*images[0:5], *responses[0:5]),
SpotImageResponse(*images[5:10], *responses[5:10]),
SpotImageResponse(*images[10:15], *responses[10:15]),
)
async def are_motors_powered_on(self, timeout: Num | None = None) -> bool:
"""
Returns `True` if the robot is currently powered on and returns `False` otherwise.
Args:
cut_immediately: If `True`, then the robot will immediately have its power cut off, making it fall to the ground if it is standing. Otherwise, the robot sits down gently and then powers off.
timeout_sec: the max number of seconds to wait for the command to complete
Throws: error if `timeout_sec` seconds pass but the command has yet to complete
"""
await dummy()
return self.robot().is_powered_on(timeout)
class LeasedSpot(Spot):
"""
A class to encapsulate the functionality of controlling a Boston Dynamics
Spot robot once it has been leased.
"""
def __init__(self, shared: SpotShared):
super().__init__(shared, shared.sdk, False)
self._shared: SpotShared = shared
async def stop(self):
"""
Makes Spot stop doing everything that it is doing at the moment with
minimal movement.
"""
await dummy()
self.command_client().robot_command(RobotCommandBuilder.stop_command())
async def power_motors_on(self, timeout: Num = 20) -> bool:
"""
Powers on the Spot if it is not powered on already.
Args:
timeout_sec: the number of seconds Spot has to power on before an error is thrown
"""
await dummy()
# Now, we are ready to power on the robot. This call will block until the power
# is on. Commands would fail if this did not happen. We can also check that the robot is
# powered at any point.
self.robot().logger.info("Powering on robot... This may take several seconds.")
self.robot().power_on(timeout_sec=float(timeout))
assert await self.are_motors_powered_on(), "Robot power on failed."
self.robot().logger.info("Robot powered on.")
async def power_motors_off(
self, cut_immediately: bool = False, timeout: Num = 20
) -> bool:
"""
Powers off Spot's motors.
Args:
cut_immediately: If `True`, then the robot will immediately have its power cut off, making it fall to the ground if it is not already sitting. Otherwise, the robot sits down gently and then powers its motors off.
timeout_sec: the max number of seconds to wait for the command to complete
Throws:
an error if `timeout_sec` seconds pass but the command has yet to complete
Returns `True` the power was successufully turned off and `False` otherwise.
"""
await dummy()
if await self.are_motors_powered_on(timeout):
self.robot().logger.info("Robot Powering off...", cut_immediately)
# Power the robot off. By specifying "cut_immediately=False", a safe power off command
# is issued to the robot. This will attempt to sit the robot before powering off.
self.robot().power_off(
cut_immediately=cut_immediately, timeout_sec=float(timeout)
)
assert not self.are_motors_powered_on(), "Robot power off failed."
self.robot().logger.info(
"Robot powered off (cut_immediately=%s).", cut_immediately
)
return True
return False
async def stand(self, timeout: Num = 10):
"""
Make the robot stand up.
Args:
height: the height that Spot should stand relative to its normal height
timeout_sec: the max number of seconds to wait for the command to complete
Throws: error if `timeout_sec` seconds pass but the command has yet to complete
"""
await dummy()
def check_stand_status(response):
status = response.feedback.synchronized_feedback.mobility_command_feedback.stand_feedback.status
return status == basic_command_pb2.StandCommand.Feedback.STATUS_IS_STANDING
blocking_command(
self.command_client(),
RobotCommandBuilder.synchro_stand_command(),
check_stand_status,
timeout_sec=timeout,
)
async def sit(self, timeout: Num = 10):
"""
Make the robot sit down.
Args:
timeout_sec: the max number of seconds to wait for the command to complete
Throws: error if `timeout_sec` seconds pass but the command has yet to complete
"""
await dummy()
blocking_sit(self.command_client(), timeout_sec=float(timeout))
async def selfright(self, timeout: Num = 10):
"""
Make the robot right itself (assuming it fell over or is on its back).
Args:
timeout_sec: the max number of seconds to wait for the command to complete
Throws: error if `timeout_sec` seconds pass but the command has yet to complete
"""
await dummy()
blocking_selfright(self.command_client(), timeout_sec=float(timeout))
async def battery_change_pose(self, roll_right: bool):
"""
Make the robot sit down (if not already sitting) and roll into its side for easier battery access.
Args:
roll_right: if `True` then spot rolls to the right, otherwise Spot rolls to the left.
"""
await dummy()
self.command_client().robot_command(
RobotCommandBuilder.battery_change_pose_command(
dir_hint=1 if roll_right else 2
)
)
async def stow_arm(self, timeout: Num | None = None, extra_safe: bool = False):
"""
Stows Spot's arm.
Args:
timeout: the max amount of time (in seconds) Spot has to complete the command before throwing an error
extra_safe: Some commands (such as the `arm_floor_contact` command) leave the robot in a state where stowing the arm causes it to sometimes slam into the robot itself. Passing in `True` for this value will cause a command to be issued prior to stowing the arm that will leave it in a state where it can safely stow the arm without slaming it down.
Exceptions:
AssertionError: if Spot is not outfitted with an arm
"""
assert self.has_arm(), "Spot requires an arm to stow its arm"
await dummy()
if extra_safe:
# reset the arm position to make sure that it never slams when stowing the arm
await self.set_ee_pose(x=0.8, z=0.5, rot="forward", move_time=2)
stow_id = self.command_client().robot_command(
RobotCommandBuilder.arm_stow_command()
)
block_until_arm_arrives(self.command_client(), stow_id, timeout)
async def unstow_arm(self, timeout: Num | None = None):
"""
Unstows Spot's arm.
Args:
timeout: the max amount of time (in seconds) Spot has to complete the command before throwing an error
Exceptions:
AssertionError: if the command stalls or is cancelled before the arm can be complete being unstowed
"""
assert self.has_arm(), "Spot requires an arm to unstow its arm"
await dummy()
unstow_id = self.command_client().robot_command(
RobotCommandBuilder.arm_ready_command()
)
block_until_arm_arrives(self.command_client(), unstow_id, timeout)